Skip to content

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

Add spam validation check in auth email templates (#30188)

Joshen Limdb2e977f7d53
diff --git a/apps/studio/components/interfaces/Auth/EmailTemplates/EmailTemplates.tsx b/apps/studio/components/interfaces/Auth/EmailTemplates/EmailTemplates.tsx
index 435af941871..a0e0790ee04 100644
--- a/apps/studio/components/interfaces/Auth/EmailTemplates/EmailTemplates.tsx
+++ b/apps/studio/components/interfaces/Auth/EmailTemplates/EmailTemplates.tsx
@@ -1,18 +1,12 @@
import { ExternalLink } from 'lucide-react'
import { useParams } from 'common'
+import AlertError from 'components/ui/AlertError'
import { FormHeader } from 'components/ui/Forms/FormHeader'
import { FormPanel } from 'components/ui/Forms/FormPanel'
import { GenericSkeletonLoader } from 'components/ui/ShimmeringLoader'
import { useAuthConfigQuery } from 'data/auth/auth-config-query'
-import {
- AlertDescription_Shadcn_,
- AlertTitle_Shadcn_,
- Alert_Shadcn_,
- Button,
- Tabs,
- WarningIcon,
-} from 'ui'
+import { Button, Tabs } from 'ui'
import { TEMPLATES_SCHEMAS } from '../AuthTemplatesValidation'
import EmailRateLimitsAlert from '../EmailRateLimitsAlert'
import TemplateEditor from './TemplateEditor'
@@ -52,11 +46,7 @@ const EmailTemplates = () => {
</div>
</div>
{isError && (
- <Alert_Shadcn_ variant="destructive">
- <WarningIcon />
- <AlertTitle_Shadcn_>Failed to retrieve auth configuration</AlertTitle_Shadcn_>
- <AlertDescription_Shadcn_>{authConfigError.message}</AlertDescription_Shadcn_>
- </Alert_Shadcn_>
+ <AlertError error={authConfigError} subject="Failed to retrieve auth configuration" />
)}
{isLoading && <GenericSkeletonLoader />}
{isSuccess && (
@@ -77,11 +67,7 @@ const EmailTemplates = () => {
<EmailRateLimitsAlert />
</div>
) : null}
- <TemplateEditor
- key={template.title}
- template={template}
- authConfig={authConfig as any}
- />
+ <TemplateEditor key={template.title} template={template} />
</Tabs.Panel>
)
})}
diff --git a/apps/studio/components/interfaces/Auth/EmailTemplates/SpamValidation.tsx b/apps/studio/components/interfaces/Auth/EmailTemplates/SpamValidation.tsx
new file mode 100644
index 00000000000..889a8795e7d
--- /dev/null
+++ b/apps/studio/components/interfaces/Auth/EmailTemplates/SpamValidation.tsx
@@ -0,0 +1,60 @@
+import { Check } from 'lucide-react'
+
+import Table from 'components/to-be-cleaned/Table'
+import InformationBox from 'components/ui/InformationBox'
+import { ValidateSpamResponse } from 'data/auth/validate-spam-mutation'
+import { cn, WarningIcon } from 'ui'
+
+interface SpamValidationProps {
+ validationResult?: ValidateSpamResponse
+}
+
+// [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
+
+ return (
+ <InformationBox
+ className={cn('mb-2', hasSpamWarning && '!bg-alternative')}
+ icon={hasSpamWarning ? <WarningIcon /> : <Check size={16} className="text-brand" />}
+ title={
+ hasSpamWarning
+ ? 'Email has a high probability of being marked as spam and deliverability may be affected'
+ : 'Email content is unlikely to be marked as spam'
+ }
+ description={
+ hasSpamWarning ? (
+ <>
+ <p>
+ {spamRules.length > 0
+ ? hasSpamWarning
+ ? ` Rectify the following issues to improve your email's deliverability in order of priority:`
+ : ` Address the following issues to improve your email's deliverability:`
+ : ''}
+ </p>
+
+ {spamRules.length > 0 && (
+ <Table
+ className="mt-3"
+ head={[
+ <Table.th key="name">Warning</Table.th>,
+ <Table.th key="desc">Description</Table.th>,
+ ]}
+ body={spamRules.map((rule) => (
+ <Table.tr key={rule.name}>
+ <Table.td>{rule.name}</Table.td>
+ <Table.td>{rule.desc}</Table.td>
+ </Table.tr>
+ ))}
+ />
+ )}
+ </>
+ ) : null
+ }
+ />
+ )
+}
diff --git a/apps/studio/components/interfaces/Auth/EmailTemplates/TemplateEditor.tsx b/apps/studio/components/interfaces/Auth/EmailTemplates/TemplateEditor.tsx
index b0bb7cbaf96..bd30ff54ea6 100644
--- a/apps/studio/components/interfaces/Auth/EmailTemplates/TemplateEditor.tsx
+++ b/apps/studio/components/interfaces/Auth/EmailTemplates/TemplateEditor.tsx
@@ -1,5 +1,7 @@
import { PermissionAction } from '@supabase/shared-types/out/constants'
-import { useEffect, useMemo, useState } from 'react'
+import { debounce } from 'lodash'
+import { Code, Monitor } from 'lucide-react'
+import { useCallback, useEffect, useMemo, useState } from 'react'
import ReactMarkdown from 'react-markdown'
import { toast } from 'sonner'
@@ -9,18 +11,29 @@ import { FormActions } from 'components/ui/Forms/FormActions'
import { FormSection, FormSectionContent, FormSectionLabel } from 'components/ui/Forms/FormSection'
import InformationBox from 'components/ui/InformationBox'
import { useAuthConfigUpdateMutation } from 'data/auth/auth-config-update-mutation'
+import { useValidateSpamMutation, ValidateSpamResponse } from 'data/auth/validate-spam-mutation'
import { useCheckPermissions } from 'hooks/misc/useCheckPermissions'
import type { FormSchema } from 'types'
-import { AlertTitle_Shadcn_, Alert_Shadcn_, Form, Input, Tabs } from 'ui'
-import { Code, Monitor, Info } from 'lucide-react'
+import { Form, Input, Tabs } from 'ui'
+import { Admonition } from 'ui-patterns'
+import { SpamValidation } from './SpamValidation'
+import { useAuthConfigQuery } from 'data/auth/auth-config-query'
interface TemplateEditorProps {
template: FormSchema
- authConfig: Record<string, string>
}
-const TemplateEditor = ({ template, authConfig }: TemplateEditorProps) => {
+const TemplateEditor = ({ template }: TemplateEditorProps) => {
const { ref: projectRef } = useParams()
+ const canUpdateConfig = useCheckPermissions(PermissionAction.UPDATE, 'custom_config_gotrue')
+
+ // [Joshen] Error state is handled in the parent
+ const { data: authConfig, isSuccess } = useAuthConfigQuery({ projectRef })
+
+ const { mutate: validateSpam } = useValidateSpamMutation({
+ onSuccess: (res) => setValidationResult(res),
+ })
+
const { mutate: updateAuthConfig, isLoading: isUpdatingConfig } = useAuthConfigUpdateMutation({
onError: (error) => toast.error(`Failed to update email templates: ${error.message}`),
})
@@ -31,17 +44,27 @@ const TemplateEditor = ({ template, authConfig }: TemplateEditorProps) => {
const INITIAL_VALUES = useMemo(() => {
const result: { [x: string]: string } = {}
Object.keys(properties).forEach((key) => {
- result[key] = (authConfig && authConfig[key]) ?? ''
+ result[key] = ((authConfig && authConfig[key as keyof typeof authConfig]) ?? '') as string
})
return result
}, [authConfig, properties])
- const canUpdateConfig = useCheckPermissions(PermissionAction.UPDATE, 'custom_config_gotrue')
- const messageSlug = `MAILER_TEMPLATES_${id}_CONTENT`
+ const messageSlug = `MAILER_TEMPLATES_${id}_CONTENT` as keyof typeof authConfig
const messageProperty = properties[messageSlug]
+ const builtInSMTP =
+ isSuccess &&
+ authConfig &&
+ (!authConfig.SMTP_HOST || !authConfig.SMTP_USER || !authConfig.SMTP_PASS)
+
+ const [validationResult, setValidationResult] = useState<ValidateSpamResponse>()
const [bodyValue, setBodyValue] = useState((authConfig && authConfig[messageSlug]) ?? '')
const [hasUnsavedChanges, setHasUnsavedChanges] = useState(false)
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ const debounceValidateSpam = useCallback(debounce(validateSpam, 1000), [])
+ const spamRules = (validationResult?.rules ?? []).filter((rule) => rule.score > 0)
+ const preventSaveFromSpamCheck = builtInSMTP && spamRules.length > 0
+
const onSubmit = (values: any, { resetForm }: any) => {
const payload = { ...values }
@@ -80,6 +103,21 @@ const TemplateEditor = ({ template, authConfig }: TemplateEditorProps) => {
}
}, [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])
+
return (
<Form id={formId} className="!border-t-0" initialValues={INITIAL_VALUES} onSubmit={onSubmit}>
{({ resetForm, values, initialValues }: any) => {
@@ -127,7 +165,7 @@ const TemplateEditor = ({ template, authConfig }: TemplateEditorProps) => {
})}
</FormSectionContent>
</FormSection>
- <FormSection className="!mt-0 grid-cols-12 !border-t-0 !pt-0">
+ <FormSection className="!mt-0 grid-cols-12 !border-t-0 !pt-0 pb-7">
<FormSectionContent fullWidth loading={false}>
{messageProperty && (
<>
@@ -147,7 +185,8 @@ const TemplateEditor = ({ template, authConfig }: TemplateEditorProps) => {
/>
</div>
<Tabs defaultActiveId="source" type="underlined" size="tiny">
- <Tabs.Panel id={'source'} icon={<Code />} label="Source">
+ <Tabs.Panel id="source" icon={<Code size={14} />} label="Source">
+ <SpamValidation validationResult={validationResult} />
<div className="relative h-96">
<CodeEditor
id="code-id"
@@ -156,23 +195,26 @@ const TemplateEditor = ({ template, authConfig }: TemplateEditorProps) => {
className="!mb-0 h-96 overflow-hidden rounded border"
onInputChange={(e: string | undefined) => {
setBodyValue(e ?? '')
- if (bodyValue !== e) {
- setHasUnsavedChanges(true)
+ if (bodyValue !== e) setHasUnsavedChanges(true)
+
+ if (projectRef) {
+ const [subjectKey] = Object.keys(values)
+ debounceValidateSpam({
+ projectRef,
+ template: { subject: values[subjectKey], content: e ?? '' },
+ })
}
}}
- options={{ wordWrap: 'off', contextmenu: false }}
+ options={{ wordWrap: 'on', contextmenu: false }}
value={bodyValue}
/>
</div>
</Tabs.Panel>
- <Tabs.Panel id={'preview'} icon={<Monitor />} label="Preview">
- <Alert_Shadcn_ className="mb-2" variant="default">
- <Info strokeWidth={1.5} />
- <AlertTitle_Shadcn_>
- The preview may differ slightly from the actual rendering in the email
- client.
- </AlertTitle_Shadcn_>
- </Alert_Shadcn_>
+ <Tabs.Panel id="preview" icon={<Monitor size={14} />} label="Preview">
+ <Admonition
+ type="default"
+ title="The preview may differ slightly from the actual rendering in the email client"
+ />
<iframe
className="!mb-0 overflow-hidden h-96 w-full rounded border"
title={id}
@@ -194,11 +236,13 @@ const TemplateEditor = ({ template, authConfig }: TemplateEditorProps) => {
form={formId}
isSubmitting={isUpdatingConfig}
hasChanges={hasChanges}
- disabled={!canUpdateConfig}
+ disabled={preventSaveFromSpamCheck || !canUpdateConfig}
helper={
- !canUpdateConfig
- ? 'You need additional permissions to update authentication settings'
- : undefined
+ preventSaveFromSpamCheck
+ ? 'Please rectify all spam warnings before saving while using the built-in email service'
+ : !canUpdateConfig
+ ? 'You need additional permissions to update authentication settings'
+ : undefined
}
/>
</div>
diff --git a/apps/studio/components/ui/CodeEditor/CodeEditor.tsx b/apps/studio/components/ui/CodeEditor/CodeEditor.tsx
index 547bab47a34..44237bae589 100644
--- a/apps/studio/components/ui/CodeEditor/CodeEditor.tsx
+++ b/apps/studio/components/ui/CodeEditor/CodeEditor.tsx
@@ -4,13 +4,12 @@ import { editor } from 'monaco-editor'
import { MutableRefObject, useEffect, useRef, useState } from 'react'
import { Markdown } from 'components/interfaces/Markdown'
+import { formatQuery } from 'data/sql/format-sql-query'
+import { useSelectedProject } from 'hooks/misc/useSelectedProject'
import { timeout } from 'lib/helpers'
import { cn } from 'ui'
import { Loading } from '../Loading'
import { alignEditor } from './CodeEditor.utils'
-import { useSelectedProject } from 'hooks/misc/useSelectedProject'
-import { formatQuery } from 'data/sql/format-sql-query'
-import { useIsDatabaseFunctionsAssistantEnabled } from 'components/interfaces/App/FeaturePreview/FeaturePreviewContext'
type CodeEditorActions = { enabled: boolean; callback: (value: any) => void }
const DEFAULT_ACTIONS = {
diff --git a/apps/studio/data/auth/validate-spam-mutation.ts b/apps/studio/data/auth/validate-spam-mutation.ts
new file mode 100644
index 00000000000..78a46ac777d
--- /dev/null
+++ b/apps/studio/data/auth/validate-spam-mutation.ts
@@ -0,0 +1,51 @@
+import { useMutation, UseMutationOptions } from '@tanstack/react-query'
+import { toast } from 'sonner'
+
+import type { components } from 'data/api'
+import { handleError, post } from 'data/fetchers'
+import type { ResponseError } from 'types'
+
+export type ValidateSpamVariables = {
+ projectRef: string
+ template: components['schemas']['ValidateSpamBody']
+}
+export type ValidateSpamResponse = components['schemas']['ValidateSpamResponse']
+
+export async function validateSpam({ projectRef, template }: ValidateSpamVariables) {
+ const { data, error } = await post('/platform/auth/{ref}/validate/spam', {
+ // @ts-expect-error API doesnt have the param check cause it's not being used in the controller
+ params: { path: { ref: projectRef } },
+ body: template,
+ })
+
+ if (error) handleError(error)
+ return data
+}
+
+type ValidateSpamData = Awaited<ReturnType<typeof validateSpam>>
+
+export const useValidateSpamMutation = ({
+ onSuccess,
+ onError,
+ ...options
+}: Omit<
+ UseMutationOptions<ValidateSpamData, ResponseError, ValidateSpamVariables>,
+ 'mutationFn'
+> = {}) => {
+ return useMutation<ValidateSpamData, ResponseError, ValidateSpamVariables>(
+ (vars) => validateSpam(vars),
+ {
+ async onSuccess(data, variables, context) {
+ await onSuccess?.(data, variables, context)
+ },
+ async onError(data, variables, context) {
+ if (onError === undefined) {
+ toast.error(`Failed to validate template: ${data.message}`)
+ } else {
+ onError(data, variables, context)
+ }
+ },
+ ...options,
+ }
+ )
+}
diff --git a/packages/api-types/types/api.d.ts b/packages/api-types/types/api.d.ts
index a4cc902717f..6050797151f 100644
--- a/packages/api-types/types/api.d.ts
+++ b/packages/api-types/types/api.d.ts
@@ -145,6 +145,10 @@ export interface paths {
/** Delete all factors associated to a user */
delete: operations['FactorsController_deleteFactors']
}
+ '/platform/auth/{ref}/validate/spam': {
+ /** Validate spam based on the given email content */
+ post: operations['ValidateController_validateSpam']
+ }
'/platform/cli/login': {
/** Create CLI login session */
post: operations['CliLoginController_createCliLoginSession']
@@ -1346,6 +1350,10 @@ export interface paths {
/** Delete all factors associated to a user */
delete: operations['FactorsController_deleteFactors']
}
+ '/v0/auth/{ref}/validate/spam': {
+ /** Validate spam based on the given email content */
+ post: operations['ValidateController_validateSpam']
+ }
'/v0/database/{ref}/backups': {
/** Gets project backups */
get: operations['BackupsController_getBackups']
@@ -6777,6 +6785,18 @@ export interface components {
ValidateQueryResponse: {
valid: boolean
}
+ ValidateSpamBody: {
+ content: string
+ subject: string
+ }
+ ValidateSpamResponse: {
+ rules: components['schemas']['ValidateSpamRule'][]
+ }
+ ValidateSpamRule: {
+ desc: string
+ name: string
+ score: number
+ }
ValidationError: {
message: string
}
@@ -7486,6 +7506,28 @@ export interface operations {
}
}
}
+ /** Validate spam based on the given email content */
+ ValidateController_validateSpam: {
+ requestBody: {
+ content: {
+ 'application/json': components['schemas']['ValidateSpamBody']
+ }
+ }
+ responses: {
+ 200: {
+ content: {
+ 'application/json': components['schemas']['ValidateSpamResponse']
+ }
+ }
+ 403: {
+ content: never
+ }
+ /** @description Failed to validate spam based on the given email content */
+ 500: {
+ content: never
+ }
+ }
+ }
/** Create CLI login session */
CliLoginController_createCliLoginSession: {
requestBody: {
diff --git a/packages/ui/src/components/StatusIcon.tsx b/packages/ui/src/components/StatusIcon.tsx
index 1f4dea1d4e4..bb21335a5ce 100644
--- a/packages/ui/src/components/StatusIcon.tsx
+++ b/packages/ui/src/components/StatusIcon.tsx
@@ -1,5 +1,6 @@
import { SVGProps, forwardRef } from 'react'
import { cn } from '../lib/utils'
+import { Check } from 'lucide-react'
export interface StatusIconProps {
hideBackground?: boolean