The Postgres development platform. Supabase gives you a dedicated Postgres database to build your web, mobile, and AI applications.
TypeScript aialternativeauthdatabasedenoembeddingsexamplefirebasenextjsoauth2pgvectorpostgispostgrespostgresqlpostgrestrealtimesupabasevectorswebsockets
feat(studio): email template configuration (#40069)
Danny Whitee900020014ca
diff --git a/apps/design-system/content/docs/components/switch.mdx b/apps/design-system/content/docs/components/switch.mdxindex 3dcf332821f..6e7ec2d1f71 100644--- a/apps/design-system/content/docs/components/switch.mdx+++ b/apps/design-system/content/docs/components/switch.mdx@@ -1,6 +1,6 @@---title: Switch-description: A control that allows the user to toggle between checked and not checked.+description: A control for toggling between unchecked and checked.component: truelinks:doc: https://www.radix-ui.com/docs/primitives/components/switch@@ -60,6 +60,26 @@ import { Switch } from '@/components/ui/switch'<Switch />```+### Relative positioning++When using Switch in custom flex layouts (especially with height constraints like `h-full`), you may need to add `relative` positioning to the parent container to ensure proper rendering of focus rings, form validation messages, and overflow.++```tsx+<div className="relative">+ <FormField_Shadcn_+ control={form.control}+ name="enabled"+ render={({ field }) => (+ <FormControl_Shadcn_>+ <Switch checked={field.value} onCheckedChange={field.onChange} />+ </FormControl_Shadcn_>+ )}+ />+</div>+```++You don’t need to add `relative` manually when using FormItemLayout as it provides the necessary positioning context automatically.+## Examples### Formdiff --git a/apps/studio/components/interfaces/Auth/EmailTemplates/EmailTemplates.tsx b/apps/studio/components/interfaces/Auth/EmailTemplates/EmailTemplates.tsxindex 26ddf458cbb..24fde2379c7 100644--- a/apps/studio/components/interfaces/Auth/EmailTemplates/EmailTemplates.tsx+++ b/apps/studio/components/interfaces/Auth/EmailTemplates/EmailTemplates.tsx@@ -120,14 +120,14 @@ export const EmailTemplates = () => {</div>)}{isSuccess && (- <div className="my-12">+ <>{builtInSMTP ? (- <div className="mb-12">+ <div className="mt-12"><EmailRateLimitsAlert /></div>) : null}{isSecurityNotificationsEnabled ? (- <div className="space-y-12">+ <div className="mt-12 space-y-12"><div><ScaffoldSectionTitle className="mb-4">Authentication</ScaffoldSectionTitle><Card>@@ -149,11 +149,8 @@ export const EmailTemplates = () => {)}</div>- <div className="flex items-center gap-4 group">- <ChevronRight- size={16}- className="text-foreground-muted group-hover:text-foreground transition-colors"- />+ <div className="flex items-center gap-4">+ <ChevronRight size={16} className="text-foreground-muted" /></div></Link></CardContent>@@ -191,7 +188,7 @@ export const EmailTemplates = () => {)}</Link>- <div className="flex items-center gap-4 group h-full pl-2">+ <div className="flex items-center gap-4 h-full pl-2 relative"><FormField_Shadcn_control={notificationsForm.control}name={templateEnabledKey}@@ -210,10 +207,7 @@ export const EmailTemplates = () => {href={`/project/${projectRef}/auth/templates/${templateSlug}`}className="py-6 pr-6">- <ChevronRight- size={16}- className="text-foreground-muted hover:text-foreground transition-colors"- />+ <ChevronRight size={16} className="text-foreground-muted" /></Link></div></CardContent>@@ -271,7 +265,7 @@ export const EmailTemplates = () => {</Tabs_Shadcn_></Card>)}- </div>+ </>)}</ScaffoldSection>)diff --git a/apps/studio/components/interfaces/Auth/EmailTemplates/SpamValidation.tsx b/apps/studio/components/interfaces/Auth/EmailTemplates/SpamValidation.tsxindex 89d69e61ed8..7853be1b2d7 100644--- a/apps/studio/components/interfaces/Auth/EmailTemplates/SpamValidation.tsx+++ b/apps/studio/components/interfaces/Auth/EmailTemplates/SpamValidation.tsx@@ -1,66 +1,66 @@-import { Check, MailWarning } from 'lucide-react'+import { AnimatePresence, motion } from 'framer-motion'import { Markdown } from 'components/interfaces/Markdown'import { ValidateSpamResponse } from 'data/auth/validate-spam-mutation'-import { Separator, Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from 'ui'+import { CardContent, Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from 'ui'+import { Admonition } from 'ui-patterns'interface SpamValidationProps {- validationResult?: ValidateSpamResponse+ spamRules?: ValidateSpamResponse['rules']}// [Joshen] According to API, we label as a spam risk as long as there are spam// rules identified with scores above 0. Scores are irrelevant in our context and// are hence not visualized in the UI-export const SpamValidation = ({ validationResult }: SpamValidationProps) => {- const spamRules = (validationResult?.rules ?? []).filter((rule) => rule.score >= 0)- const hasSpamWarning = spamRules.length > 0+export const SpamValidation = ({ spamRules = [] }: SpamValidationProps) => {+ const rules = spamRules.filter((rule) => rule.score >= 0)return (- <div className="flex items-start gap-2">- <div className="mt-0.5">- {hasSpamWarning ? (- <MailWarning size={16} strokeWidth={1.5} className="text-warning" />- ) : (- <Check size={16} strokeWidth={1.5} className="text-brand" />- )}- </div>- <div className="flex flex-col gap-2">- <h5>- {hasSpamWarning- ? 'Email has a high probability of being marked as spam - review issues below to improve deliverability.'- : 'Email content is unlikely to be marked as spam'}- </h5>- {hasSpamWarning && (- <>- <div className="flex flex-col gap-y-3">- <Table>- <TableHeader className="font-mono uppercase text-xs [&_th]:h-auto [&_th]:py-2">- <TableRow className="hover:bg-transparent">- <TableHead className="pl-0">Warning</TableHead>- <TableHead className="pr-0">Description</TableHead>- </TableRow>- </TableHeader>- <TableBody>- {spamRules.map((rule) => (- <TableRow key={rule.name} className="hover:bg-transparent">- <TableCell className="pl-0 font-mono text-xs text-foreground">- {rule.name}- </TableCell>- <TableCell className="pr-0">{rule.desc}</TableCell>+ <AnimatePresence>+ {rules.length > 0 && (+ <motion.div+ className="border-b"+ initial={{ height: 0, opacity: 0 }}+ animate={{ height: 'auto', opacity: 1 }}+ exit={{ height: 0, opacity: 0 }}+ transition={{ duration: 0.2, ease: 'easeOut' }}+ >+ <CardContent className="py-6 flex flex-col gap-2">+ <Admonition+ type="destructive"+ title="Issues to resolve"+ description="This email is likely to be marked as spam by email servers. Please resolve the below issues before saving."+ className="bg-destructive-300/50 dark:bg-destructive-200 border-destructive-400"+ />++ <div className="flex flex-col gap-1">+ <div className="w-full border rounded-md overflow-hidden">+ <Table>+ <TableHeader>+ <TableRow>+ <TableHead>Warning</TableHead>+ <TableHead>Description</TableHead></TableRow>- ))}- </TableBody>- </Table>+ </TableHeader>+ <TableBody>+ {rules.map((rule) => (+ <TableRow key={rule.name}>+ <TableCell className="font-mono">{rule.name}</TableCell>+ <TableCell>{rule.desc}</TableCell>+ </TableRow>+ ))}+ </TableBody>+ </Table>+ </div>+ <Markdown+ className="!max-w-none text-foreground-lighter text-xs mt-2"+ content="Spam validation is powered by [SpamAssassin](https://spamassassin.apache.org/doc.html). Full list of all available warnings can be found [here](https://gist.github.com/ychaouche/a2faff159c2a1fea16019156972c7f8b)."+ /></div>- <Separator />- <Markdown- className="!max-w-none text-foreground-muted text-xs [&_a]:text-foreground-lighter mt-2"- content="Spam validation is powered by [SpamAssassin](https://spamassassin.apache.org/doc.html). Full list of all available warnings can be found [here](https://gist.github.com/ychaouche/a2faff159c2a1fea16019156972c7f8b)."- />- </>- )}- </div>- </div>+ </CardContent>+ </motion.div>+ )}+ </AnimatePresence>)}diff --git a/apps/studio/components/interfaces/Auth/EmailTemplates/TemplateEditor.tsx b/apps/studio/components/interfaces/Auth/EmailTemplates/TemplateEditor.tsxindex 47334435239..045bb4f3704 100644--- a/apps/studio/components/interfaces/Auth/EmailTemplates/TemplateEditor.tsx+++ b/apps/studio/components/interfaces/Auth/EmailTemplates/TemplateEditor.tsx@@ -1,5 +1,4 @@import { PermissionAction } from '@supabase/shared-types/out/constants'-import { Code, Monitor } from 'lucide-react'import { editor } from 'monaco-editor'import { useEffect, useMemo, useRef, useState } from 'react'import { useForm } from 'react-hook-form'@@ -8,6 +7,7 @@ import { toast } from 'sonner'import { useParams } from 'common'import CodeEditor from 'components/ui/CodeEditor/CodeEditor'+import TwoOptionToggle from 'components/ui/TwoOptionToggle'import { useAuthConfigQuery } from 'data/auth/auth-config-query'import { useAuthConfigUpdateMutation } from 'data/auth/auth-config-update-mutation'import { useValidateSpamMutation, ValidateSpamResponse } from 'data/auth/validate-spam-mutation'@@ -22,10 +22,6 @@ import {FormField_Shadcn_,Input_Shadcn_,Label_Shadcn_,- Tabs_Shadcn_,- TabsContent_Shadcn_,- TabsList_Shadcn_,- TabsTrigger_Shadcn_,Tooltip,TooltipContent,TooltipTrigger,@@ -44,16 +40,12 @@ export const TemplateEditor = ({ template }: TemplateEditorProps) => {PermissionAction.UPDATE,'custom_config_gotrue')-- // Add a ref to the code editorconst editorRef = useRef<editor.IStandaloneCodeEditor>()// [Joshen] Error state is handled in the parentconst { data: authConfig, isSuccess } = useAuthConfigQuery({ projectRef })- const { mutate: validateSpam } = useValidateSpamMutation({- onSuccess: (res) => setValidationResult(res),- })+ const { mutate: validateSpam } = useValidateSpamMutation()const { mutate: updateAuthConfig } = useAuthConfigUpdateMutation({onError: (error) => {@@ -75,11 +67,10 @@ export const TemplateEditor = ({ template }: TemplateEditorProps) => {const [bodyValue, setBodyValue] = useState((authConfig && authConfig[messageSlug]) ?? '')const [hasUnsavedChanges, setHasUnsavedChanges] = useState(false)const [isSavingTemplate, setIsSavingTemplate] = useState(false)+ const [activeView, setActiveView] = useState<'source' | 'preview'>('source')const spamRules = (validationResult?.rules ?? []).filter((rule) => rule.score > 0)- const preventSaveFromSpamCheck = builtInSMTP && spamRules.length > 0- // Create form valuesconst INITIAL_VALUES = useMemo(() => {const result: { [x: string]: string } = {}Object.keys(properties).forEach((key) => {@@ -88,27 +79,13 @@ export const TemplateEditor = ({ template }: TemplateEditorProps) => {return result}, [authConfig, properties])- // Setup React Hook Form- const form = useForm({- defaultValues: INITIAL_VALUES,- })-- // Update form values when authConfig changes- useEffect(() => {- if (authConfig) {- const values: { [key: string]: string } = {}- Object.keys(properties).forEach((key) => {- values[key] = ((authConfig && authConfig[key as keyof typeof authConfig]) ?? '') as string- })- form.reset(values)- setBodyValue((authConfig && authConfig[messageSlug]) ?? '')- }- }, [authConfig, properties, messageSlug, form])+ const form = useForm({ defaultValues: INITIAL_VALUES })const onSubmit = (values: any) => {if (!projectRef) return console.error('Project ref is required')setIsSavingTemplate(true)+const payload = { ...values }// Because the template content uses the code editor which is not a form component@@ -128,6 +105,7 @@ export const TemplateEditor = ({ template }: TemplateEditorProps) => {},{onSuccess: (res) => {+ setValidationResult(res)const spamRules = (res?.rules ?? []).filter((rule) => rule.score > 0)const preventSaveFromSpamCheck = builtInSMTP && spamRules.length > 0@@ -142,8 +120,8 @@ export const TemplateEditor = ({ template }: TemplateEditorProps) => {{onSuccess: () => {setIsSavingTemplate(false)- toast.success('Successfully updated settings')setHasUnsavedChanges(false) // Reset the unsaved changes state+ toast.success('Successfully updated email template')},})@@ -154,36 +132,6 @@ export const TemplateEditor = ({ template }: TemplateEditorProps) => {)}- useEffect(() => {- const handleBeforeUnload = (e: BeforeUnloadEvent) => {- if (hasUnsavedChanges) {- e.preventDefault()- e.returnValue = '' // deprecated, but older browsers still require this- }- }-- window.addEventListener('beforeunload', handleBeforeUnload)-- return () => {- window.removeEventListener('beforeunload', handleBeforeUnload)- }- }, [hasUnsavedChanges])-- useEffect(() => {- if (projectRef && id && !!authConfig) {- const [subjectKey] = Object.keys(properties)-- validateSpam({- projectRef,- template: {- subject: authConfig[subjectKey as keyof typeof authConfig] as string,- content: authConfig[messageSlug],- },- })- }- // eslint-disable-next-line react-hooks/exhaustive-deps- }, [id])-// Single useMemo hook to parse and prepare message variablesconst messageVariables = useMemo(() => {if (!messageProperty?.description) return []@@ -209,8 +157,10 @@ export const TemplateEditor = ({ template }: TemplateEditorProps) => {// Check if form values have changedconst formValues = form.watch()- const hasFormChanges = JSON.stringify(formValues) !== JSON.stringify(INITIAL_VALUES)- const hasChanges = hasFormChanges || ((authConfig && authConfig[messageSlug]) ?? '') !== bodyValue+ const baselineValues = INITIAL_VALUES+ const baselineBodyValue = (authConfig && authConfig[messageSlug]) ?? ''+ const hasFormChanges = JSON.stringify(formValues) !== JSON.stringify(baselineValues)+ const hasChanges = hasFormChanges || baselineBodyValue !== bodyValue// Function to insert text at cursor positionconst insertTextAtCursor = (text: string) => {@@ -240,6 +190,52 @@ export const TemplateEditor = ({ template }: TemplateEditorProps) => {}}+ // Update form values when authConfig changes+ useEffect(() => {+ if (authConfig) {+ const values: { [key: string]: string } = {}+ Object.keys(properties).forEach((key) => {+ values[key] = ((authConfig && authConfig[key as keyof typeof authConfig]) ?? '') as string+ })+ form.reset(values)+ setBodyValue((authConfig && authConfig[messageSlug]) ?? '')+ }+ }, [authConfig, properties, messageSlug, form])++ useEffect(() => {+ const handleBeforeUnload = (e: BeforeUnloadEvent) => {+ if (hasUnsavedChanges) {+ e.preventDefault()+ e.returnValue = '' // deprecated, but older browsers still require this+ }+ }++ window.addEventListener('beforeunload', handleBeforeUnload)++ return () => {+ window.removeEventListener('beforeunload', handleBeforeUnload)+ }+ }, [hasUnsavedChanges])++ useEffect(() => {+ if (projectRef && id && !!authConfig) {+ const [subjectKey] = Object.keys(properties)++ validateSpam({+ projectRef,+ template: {+ subject: authConfig[subjectKey as keyof typeof authConfig] as string,+ content: authConfig[messageSlug],+ },+ })+ }+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, [id])++ useEffect(() => {+ if (!hasChanges) setValidationResult(undefined)+ }, [hasChanges])+return (<Form_Shadcn_ {...form}><form onSubmit={form.handleSubmit(onSubmit)}>@@ -254,6 +250,8 @@ export const TemplateEditor = ({ template }: TemplateEditorProps) => {name={x}render={({ field }) => (<FormItemLayout+ className="gap-y-3"+ layout="vertical"label={property.title}description={property.description ? (@@ -284,76 +282,76 @@ export const TemplateEditor = ({ template }: TemplateEditorProps) => {{messageProperty && (<>- <CardContent className="p-0">- <Label_Shadcn_ className="p-6 pb-4 block">Message body</Label_Shadcn_>- <Tabs_Shadcn_ defaultValue="source">- <TabsList_Shadcn_ className="gap-3 px-6">- <TabsTrigger_Shadcn_ value="source" className="gap-2">- <Code size={14} />- Source- </TabsTrigger_Shadcn_>- <TabsTrigger_Shadcn_ value="preview" className="gap-2">- <Monitor size={14} />- Preview- </TabsTrigger_Shadcn_>- </TabsList_Shadcn_>- <TabsContent_Shadcn_ value="source" className="p-0 mt-0">- <CodeEditor- id="code-id"- language="html"- isReadOnly={!canUpdateConfig}- className="!mb-0 relative h-96 overflow-hidden p-0"- onInputChange={(e: string | undefined) => {- setBodyValue(e ?? '')- if (bodyValue !== e) setHasUnsavedChanges(true)- }}- options={{ wordWrap: 'on', contextmenu: false, padding: { top: 16 } }}- value={bodyValue}- editorRef={editorRef}- />+ <CardContent className="flex flex-col gap-4">+ <div className="flex items-center justify-between gap-2">+ <Label_Shadcn_>Body</Label_Shadcn_>+ <TwoOptionToggle+ width={60}+ options={['preview', 'source']}+ activeOption={activeView}+ onClickOption={(option: 'source' | 'preview') => setActiveView(option)}+ borderOverride="border-muted"+ />+ </div>+ {activeView === 'source' ? (+ <>+ <div className="overflow-hidden rounded-md border dark:border-control overflow-hidden [&_.monaco-editor]:outline-0 [&_.monaco-editor-background]:!bg-surface-200/30 [&_.monaco-editor_.margin]:!bg-surface-200/30 dark:[&_.monaco-editor-background]:!bg-surface-300 dark:[&_.monaco-editor_.margin]:!bg-surface-300">+ <CodeEditor+ id="code-id"+ language="html"+ isReadOnly={!canUpdateConfig}+ className="!mb-0 relative h-96 outline-none outline-offset-0 outline-width-0 outline-0"+ onInputChange={(e: string | undefined) => {+ setBodyValue(e ?? '')+ if (bodyValue !== e) setHasUnsavedChanges(true)+ }}+ options={{ wordWrap: 'on', contextmenu: false, padding: { top: 16 } }}+ value={bodyValue}+ editorRef={editorRef}+ />+ </div>{messageVariables.length > 0 && (- <div className="px-6 py-3 border-t bg-surface-200">- <div className="flex flex-wrap gap-1">- {messageVariables.map(({ variable, description }) => (- <Tooltip key={variable}>- <TooltipTrigger asChild>- <Button- type="outline"- size="tiny"- className="rounded-full"- onClick={() => insertTextAtCursor(variable)}- >- {variable}- </Button>- </TooltipTrigger>- <TooltipContent side="top">- <p>{description || 'Variable description not available'}</p>- </TooltipContent>- </Tooltip>- ))}- </div>+ <div className="flex flex-wrap gap-1">+ {messageVariables.map(({ variable, description }) => (+ <Tooltip key={variable}>+ <TooltipTrigger asChild>+ <Button+ type="outline"+ size="tiny"+ className="rounded-full"+ onClick={() => insertTextAtCursor(variable)}+ >+ {variable}+ </Button>+ </TooltipTrigger>+ <TooltipContent side="top">+ <p>{description || 'Variable description not available'}</p>+ </TooltipContent>+ </Tooltip>+ ))}</div>)}- </TabsContent_Shadcn_>- <TabsContent_Shadcn_ value="preview" className="pt-0 mt-0">+ </>+ ) : (+ <><iframe- className="!mb-0 mt-0 overflow-hidden h-96 w-full"+ className="!mb-0 mt-0 overflow-hidden h-96 w-full rounded-md border bg-white"title={id}srcDoc={bodyValue}sandbox="allow-scripts allow-forms"/><Admonitiontype="default"- title="The preview may differ slightly from the actual rendering in the email client"- className="rounded-none border-0 mb-0"+ title="Email rendering may differ"+ description="The preview shown here may differ slightly from how your email appears in the recipient’s email client."/>- </TabsContent_Shadcn_>- </Tabs_Shadcn_>- </CardContent>- <CardContent>- <SpamValidation validationResult={validationResult} />+ </>+ )}</CardContent>- <CardFooter className="justify-end space-x-2">++ <SpamValidation spamRules={spamRules} />++ <CardFooter className="flex flex-row justify-end gap-2">{hasChanges && (<Buttontype="default"@@ -369,9 +367,7 @@ export const TemplateEditor = ({ template }: TemplateEditorProps) => {<Buttontype="primary"htmlType="submit"- disabled={- !canUpdateConfig || isSavingTemplate || !hasChanges || preventSaveFromSpamCheck- }+ disabled={!canUpdateConfig || isSavingTemplate || !hasChanges}loading={isSavingTemplate}>Save changesdiff --git a/apps/studio/components/interfaces/Auth/SmtpForm/SmtpForm.tsx b/apps/studio/components/interfaces/Auth/SmtpForm/SmtpForm.tsxindex 8f2d69bc386..6b8c9357bc0 100644--- a/apps/studio/components/interfaces/Auth/SmtpForm/SmtpForm.tsx+++ b/apps/studio/components/interfaces/Auth/SmtpForm/SmtpForm.tsx@@ -1,7 +1,6 @@import { yupResolver } from '@hookform/resolvers/yup'import { PermissionAction } from '@supabase/shared-types/out/constants'-import { AlertTriangle, Eye, EyeOff } from 'lucide-react'-import Link from 'next/link'+import { Eye, EyeOff } from 'lucide-react'import { useEffect, useState } from 'react'import { useForm } from 'react-hook-form'import { toast } from 'sonner'@@ -10,14 +9,12 @@ import * as yup from 'yup'import { useParams } from 'common'import { ScaffoldSection } from 'components/layouts/Scaffold'import AlertError from 'components/ui/AlertError'+import { InlineLink } from 'components/ui/InlineLink'import NoPermission from 'components/ui/NoPermission'import { useAuthConfigQuery } from 'data/auth/auth-config-query'import { useAuthConfigUpdateMutation } from 'data/auth/auth-config-update-mutation'import { useAsyncCheckPermissions } from 'hooks/misc/useCheckPermissions'import {- AlertDescription_Shadcn_,- AlertTitle_Shadcn_,- Alert_Shadcn_,Button,Card,CardContent,@@ -29,6 +26,7 @@ import {PrePostTab,Switch,} from 'ui'+import { Admonition } from 'ui-patterns'import { FormItemLayout } from 'ui-patterns/form/FormItemLayout/FormItemLayout'import { urlRegex } from '../Auth.constants'import { defaultDisabledSmtpFormValues } from './SmtpForm.constants'@@ -65,7 +63,8 @@ export const SmtpForm = () => {const smtpSchema = yup.object({SMTP_ADMIN_EMAIL: yup.string().when('ENABLE_SMTP', {is: true,- then: (schema) => schema.email('Must be a valid email').required('Sender email is required'),+ then: (schema) =>+ schema.email('Must be a valid email').required('Sender email address is required'),otherwise: (schema) => schema,}),SMTP_SENDER_NAME: yup.string().when('ENABLE_SMTP', {@@ -205,17 +204,14 @@ export const SmtpForm = () => {render={({ field }) => (<FormItemLayoutlayout="flex-row-reverse"- label="Enable Custom SMTP"+ label="Enable custom SMTP"description={<p className="max-w-full prose text-sm text-foreground-lighter">Emails will be sent using your custom SMTP provider. Email rate limits canbe adjusted{' '}- <Link- className="underline"- href={`/project/${projectRef}/auth/rate-limits`}- >+ <InlineLink href={`/project/${projectRef}/auth/rate-limits`}>here- </Link>+ </InlineLink>.</p>}@@ -232,15 +228,12 @@ export const SmtpForm = () => {/>{enableSmtp && !isSmtpEnabled(form.getValues() as any) && (- <div className="mt-4">- <Alert_Shadcn_ variant="warning">- <AlertTriangle strokeWidth={2} />- <AlertTitle_Shadcn_>All fields below must be filled</AlertTitle_Shadcn_>- <AlertDescription_Shadcn_>- The following fields must be filled before custom SMTP can be properly enabled- </AlertDescription_Shadcn_>- </Alert_Shadcn_>- </div>+ <Admonition+ type="warning"+ title="All fields must be filled"+ description="Each of the fields below must be filled before custom SMTP can be enabled."+ className="bg-warning-200 border-warning-400 mt-4"+ />)}</CardContent>@@ -250,7 +243,7 @@ export const SmtpForm = () => {<div className="grid grid-cols-12 gap-6"><div className="col-span-4"><h3 className="text-sm mb-1">Sender details</h3>- <p className="text-sm text-foreground-lighter">+ <p className="text-sm text-foreground-lighter text-balance">Configure the sender information for your emails.</p></div>@@ -260,8 +253,8 @@ export const SmtpForm = () => {name="SMTP_ADMIN_EMAIL"render={({ field }) => (<FormItemLayout- label="Sender email"- description="This is the email address the emails are sent from"+ label="Sender email address"+ description="The email address the emails are sent from."><FormControl_Shadcn_><Input_Shadcn_@@ -280,12 +273,12 @@ export const SmtpForm = () => {render={({ field }) => (<FormItemLayoutlabel="Sender name"- description="Name displayed in the recipient's inbox"+ description="Name displayed in the recipient's inbox."><FormControl_Shadcn_><Input_Shadcn_{...field}- placeholder="The name shown on the email"+ placeholder="Your Name"disabled={!canUpdateConfig}/></FormControl_Shadcn_>@@ -299,26 +292,12 @@ export const SmtpForm = () => {<CardContent className="py-6"><div className="grid grid-cols-12 gap-6"><div className="col-span-4">- <h3 className="text-sm mb-1">SMTP Provider Settings</h3>- <p className="text-sm text-foreground-lighter">- Your SMTP Credentials will always be encrypted in our database.+ <h3 className="text-sm mb-1">SMTP provider settings</h3>+ <p className="text-sm text-foreground-lighter text-balance">+ Your SMTP credentials will always be encrypted in our database.</p></div><div className="col-span-8 space-y-4">- {form.watch('SMTP_HOST')?.endsWith('.gmail.com') && (- <Alert_Shadcn_ variant="warning" className="mb-4">- <AlertTriangle strokeWidth={2} />- <AlertTitle_Shadcn_>Check your SMTP provider</AlertTitle_Shadcn_>- <AlertDescription_Shadcn_>- Not all SMTP providers are designed for the email sending required by- Supabase Auth. It looks like the SMTP provider you entered is designed- for sending personal email messages and not for sending transactional- messages. Although you can ignore this warning, email deliverability may- be impacted.- </AlertDescription_Shadcn_>- </Alert_Shadcn_>- )}-<FormField_Shadcn_control={form.control}name="SMTP_HOST"@@ -338,6 +317,17 @@ export const SmtpForm = () => {)}/>+ {form.watch('SMTP_HOST')?.endsWith('.gmail.com') && (+ <Admonition+ type="warning"+ title="Check your SMTP provider"+ description="It looks like the SMTP provider you entered is designed+ for sending personal rather than transactional email messages. Email deliverability may+ be impacted."+ className="mb-4 bg-warning-200 border-warning-400"+ />+ )}+<FormField_Shadcn_control={form.control}name="SMTP_PORT"@@ -347,13 +337,9 @@ export const SmtpForm = () => {description={<><span className="block">- Port used by your SMTP server. Common ports include 25, 465, and- 587.{' '}- </span>- <span className="mt-2 block">- Avoid using port 25 as modern SMTP email clients shouldn't use- this port, it is traditionally blocked by residential ISPs and- Cloud Hosting Providers, to curb the amount of spam.+ Port used by your SMTP server. Common ports include 465 and 587.+ Avoid using port 25 as it is often blocked by providers to curb+ spam.</span></>}@@ -376,8 +362,8 @@ export const SmtpForm = () => {name="SMTP_MAX_FREQUENCY"render={({ field }) => (<FormItemLayout- label="Minimum interval between emails being sent to same user"- description="How long between each email can a new email be sent via your SMTP server to the same user."+ label="Minimum interval per user"+ description="The minimum time in seconds between emails before another email can be sent to the same user."><FormControl_Shadcn_><PrePostTab postTab="seconds">@@ -399,7 +385,7 @@ export const SmtpForm = () => {render={({ field }) => (<FormItemLayoutlabel="Username"- description="Username for your SMTP server"+ description="Username for your SMTP server."><FormControl_Shadcn_><Input_Shadcn_@@ -418,7 +404,7 @@ export const SmtpForm = () => {render={({ field }) => (<FormItemLayoutlabel="Password"- description="For security reasons, the password is write-only. Once saved, it cannot be retrieved or displayed."+ description="Password for your SMTP server. For security reasons, this password cannot be viewed once saved."><FormControl_Shadcn_><PrePostTabdiff --git a/apps/studio/components/ui/ResourceExhaustionWarningBanner/ResourceExhaustionWarningBanner.constants.ts b/apps/studio/components/ui/ResourceExhaustionWarningBanner/ResourceExhaustionWarningBanner.constants.tsindex 5fe7d297aa1..802b4bcd9bf 100644--- a/apps/studio/components/ui/ResourceExhaustionWarningBanner/ResourceExhaustionWarningBanner.constants.ts+++ b/apps/studio/components/ui/ResourceExhaustionWarningBanner/ResourceExhaustionWarningBanner.constants.ts@@ -183,7 +183,7 @@ export const RESOURCE_WARNING_MESSAGES: Record<string, ResourceWarningMessage> =},},docsUrl: `${DOCS_URL}/guides/platform/going-into-prod#auth-rate-limits`,- buttonText: 'Enable Custom SMTP',+ buttonText: 'Enable custom SMTP',metric: 'auth_email_rate_limit',},multiple_resource_warnings: {diff --git a/apps/studio/pages/project/[ref]/auth/templates/[templateId].tsx b/apps/studio/pages/project/[ref]/auth/templates/[templateId].tsxindex 30951b5af5b..6342ab306e5 100644--- a/apps/studio/pages/project/[ref]/auth/templates/[templateId].tsx+++ b/apps/studio/pages/project/[ref]/auth/templates/[templateId].tsx@@ -1,8 +1,13 @@+import { zodResolver } from '@hookform/resolvers/zod'import { PermissionAction } from '@supabase/shared-types/out/constants'import Link from 'next/link'import { useRouter } from 'next/router'import { useEffect } from 'react'+import { useForm } from 'react-hook-form'+import { toast } from 'sonner'+import { z } from 'zod'+import { useParams } from 'common'import { useIsSecurityNotificationsEnabled } from 'components/interfaces/App/FeaturePreview/FeaturePreviewContext'import { TEMPLATES_SCHEMAS } from 'components/interfaces/Auth/AuthTemplatesValidation'import { slugifyTitle } from 'components/interfaces/Auth/EmailTemplates/EmailTemplates.utils'@@ -10,14 +15,30 @@ import { TemplateEditor } from 'components/interfaces/Auth/EmailTemplates/Templaimport AuthLayout from 'components/layouts/AuthLayout/AuthLayout'import DefaultLayout from 'components/layouts/DefaultLayout'import { PageLayout } from 'components/layouts/PageLayout/PageLayout'-import { ScaffoldContainer, ScaffoldSection } from 'components/layouts/Scaffold'+import {+ ScaffoldContainer,+ ScaffoldSection,+ ScaffoldSectionTitle,+} from 'components/layouts/Scaffold'import { DocsButton } from 'components/ui/DocsButton'import NoPermission from 'components/ui/NoPermission'+import { useAuthConfigQuery } from 'data/auth/auth-config-query'+import { useAuthConfigUpdateMutation } from 'data/auth/auth-config-update-mutation'import { useAsyncCheckPermissions } from 'hooks/misc/useCheckPermissions'import { DOCS_URL } from 'lib/constants'import type { NextPageWithLayout } from 'types'-import { Button, Card } from 'ui'+import {+ Button,+ Card,+ CardContent,+ CardFooter,+ Form_Shadcn_,+ FormControl_Shadcn_,+ FormField_Shadcn_,+ Switch,+} from 'ui'import { Admonition, GenericSkeletonLoader } from 'ui-patterns'+import { FormItemLayout } from 'ui-patterns/form/FormItemLayout/FormItemLayout'const TemplatePage: NextPageWithLayout = () => {return <RedirectToTemplates />@@ -26,6 +47,7 @@ const TemplatePage: NextPageWithLayout = () => {const RedirectToTemplates = () => {const router = useRouter()const { templateId, ref } = router.query+ const { ref: projectRef } = useParams()const isSecurityNotificationsEnabled = useIsSecurityNotificationsEnabled()const { can: canReadAuthSettings, isSuccess: isPermissionsLoaded } = useAsyncCheckPermissions(@@ -33,6 +55,22 @@ const RedirectToTemplates = () => {'custom_config_gotrue')+ const { can: canUpdateConfig } = useAsyncCheckPermissions(+ PermissionAction.UPDATE,+ 'custom_config_gotrue'+ )++ const { data: authConfig, isLoading: isLoadingConfig } = useAuthConfigQuery({ projectRef })++ const { mutate: updateAuthConfig, isLoading: isUpdatingConfig } = useAuthConfigUpdateMutation({+ onError: (error) => {+ toast.error(`Failed to update settings: ${error?.message}`)+ },+ onSuccess: () => {+ toast.success('Successfully updated settings')+ },+ })+// Find template whose slug matches the URL slugconst template =templateId && typeof templateId === 'string'@@ -43,12 +81,56 @@ const RedirectToTemplates = () => {const templateIdForDocs =typeof templateId === 'string' ? templateId.replace(/-/g, '').toLowerCase() : ''+ // Determine if this is a security notification template+ const isSecurityTemplate = template?.misc?.emailTemplateType === 'security'++ // Get the enabled key for security templates+ const templateEnabledKey = isSecurityTemplate+ ? (`MAILER_NOTIFICATIONS_${template.id?.replace('_NOTIFICATION', '')}_ENABLED` as string)+ : null++ const showConfigurationSection = isSecurityTemplate && templateEnabledKey++ // Create form schema for security templates+ const TemplateFormSchema = templateEnabledKey+ ? z.object({+ [templateEnabledKey]: z.boolean(),+ })+ : z.object({})++ const defaultValues = templateEnabledKey+ ? {+ [templateEnabledKey]: authConfig+ ? Boolean(authConfig[templateEnabledKey as keyof typeof authConfig])+ : false,+ }+ : {}++ const templateForm = useForm<z.infer<typeof TemplateFormSchema>>({+ resolver: zodResolver(TemplateFormSchema),+ defaultValues,+ })++ const onSubmit = (values: any) => {+ if (!projectRef) return console.error('Project ref is required')+ updateAuthConfig({ projectRef: projectRef, config: { ...values } })+ }+useEffect(() => {if (isPermissionsLoaded && !isSecurityNotificationsEnabled) {router.replace(`/project/${ref}/auth/templates/`)}}, [isPermissionsLoaded, isSecurityNotificationsEnabled, ref, router])+ useEffect(() => {+ if (authConfig && templateEnabledKey) {+ templateForm.reset({+ [templateEnabledKey]: Boolean(authConfig[templateEnabledKey as keyof typeof authConfig]),+ })+ }+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, [authConfig, templateEnabledKey])+if (isPermissionsLoaded && !canReadAuthSettings) {return <NoPermission isFullPage resourceText="access your project's email settings" />}@@ -88,21 +170,77 @@ const RedirectToTemplates = () => {secondaryActions={[<DocsButtonkey="docs"- href={`${DOCS_URL}/guides/local-development/customizing-email-templates#authemailtemplate${templateIdForDocs}`}+ href={`${DOCS_URL}/guides/local-development/customizing-email-templates#${isSecurityTemplate ? 'security' : 'auth'}emailtemplate${templateIdForDocs}`}/>,]}><ScaffoldContainer bottomPadding>- {!isPermissionsLoaded ? (+ {!isPermissionsLoaded || isLoadingConfig ? (<ScaffoldSection isFullWidth><GenericSkeletonLoader /></ScaffoldSection>) : (- <ScaffoldSection isFullWidth>- <Card>- <TemplateEditor template={template} />- </Card>- </ScaffoldSection>+ <>+ {showConfigurationSection && (+ <ScaffoldSection isFullWidth>+ <ScaffoldSectionTitle className="mb-4">Configuration</ScaffoldSectionTitle>+ <Form_Shadcn_ {...templateForm}>+ <form onSubmit={templateForm.handleSubmit(onSubmit)} className="space-y-4">+ <Card>+ <CardContent>+ <FormField_Shadcn_+ control={templateForm.control}+ name={templateEnabledKey as keyof z.infer<typeof TemplateFormSchema>}+ render={({ field }) => (+ <FormItemLayout+ layout="flex-row-reverse"+ label="Enable notification"+ description="Send this email to users when triggered"+ >+ <FormControl_Shadcn_>+ <Switch+ checked={field.value}+ onCheckedChange={field.onChange}+ disabled={!canUpdateConfig}+ />+ </FormControl_Shadcn_>+ </FormItemLayout>+ )}+ />+ </CardContent>+ <CardFooter className="justify-end space-x-2">+ {templateForm.formState.isDirty && (+ <Button type="default" onClick={() => templateForm.reset()}>+ Cancel+ </Button>+ )}+ <Button+ type="primary"+ htmlType="submit"+ disabled={+ !canUpdateConfig || isUpdatingConfig || !templateForm.formState.isDirty+ }+ loading={isUpdatingConfig}+ >+ Save changes+ </Button>+ </CardFooter>+ </Card>+ </form>+ </Form_Shadcn_>+ </ScaffoldSection>+ )}++ <ScaffoldSection isFullWidth>+ {/* Only show title if there is an another section above */}+ {showConfigurationSection && (+ <ScaffoldSectionTitle className="mb-4">Contents</ScaffoldSectionTitle>+ )}+ <Card>+ <TemplateEditor template={template} />+ </Card>+ </ScaffoldSection>+ </>)}</ScaffoldContainer></PageLayout>