The Postgres development platform. Supabase gives you a dedicated Postgres database to build your web, mobile, and AI applications.
TypeScript aialternativeauthdatabasedenoembeddingsexamplefirebasenextjsoauth2pgvectorpostgispostgrespostgresqlpostgrestrealtimesupabasevectorswebsockets
feat(marketing): add anti-spam protections to /go forms (DEBR-280) (#45842)
Alan Daniele492477ad479
diff --git a/packages/marketing/src/crm/notion.ts b/packages/marketing/src/crm/notion.tsindex c686823c303..ed517d45392 100644--- a/packages/marketing/src/crm/notion.ts+++ b/packages/marketing/src/crm/notion.ts@@ -65,6 +65,12 @@ export class NotionClient {* the database schema, so values can be passed as plain strings/numbers and* will be wrapped in the correct Notion property shape.* Unknown columns (not present in the database) are silently skipped.+ *+ * If the database has an `email`-typed column and `values` includes a value+ * for it, the database is first queried for an existing row with that email.+ * If one exists, the call is a no-op (skip-on-duplicate). Notion has no+ * native dedupe, so this is the only thing standing between us and a row+ * for every refresh of the form.*/async createDatabasePage(databaseId: string, values: Record<string, unknown>): Promise<void> {const schema = await this.getSchema(databaseId)@@ -78,11 +84,49 @@ export class NotionClient {if (encoded !== undefined) properties[name] = encoded}+ const emailColumn = Object.values(schema.properties).find((p) => p.type === 'email')+ if (emailColumn) {+ const incomingEmail = values[emailColumn.name]+ if (typeof incomingEmail === 'string' && incomingEmail.trim() !== '') {+ const exists = await this.pageExistsByEmail(+ databaseId,+ emailColumn.name,+ incomingEmail.trim()+ )+ if (exists) {+ console.warn('[crm/notion] Skipping duplicate submission', {+ databaseId,+ emailColumn: emailColumn.name,+ })+ return+ }+ }+ }+await this.request('/pages', 'POST', {parent: { database_id: databaseId },properties,})}++ private async pageExistsByEmail(+ databaseId: string,+ propertyName: string,+ email: string+ ): Promise<boolean> {+ const result = await this.request<{ results: unknown[] }>(+ `/databases/${encodeURIComponent(databaseId)}/query`,+ 'POST',+ {+ filter: {+ property: propertyName,+ email: { equals: email },+ },+ page_size: 1,+ }+ )+ return result.results.length > 0+ }}function encodePropertyValue(type: string, value: unknown): unknown {diff --git a/packages/marketing/src/forms/MarketingForm.tsx b/packages/marketing/src/forms/MarketingForm.tsxindex f91327e3ea7..42b8a12ce65 100644--- a/packages/marketing/src/forms/MarketingForm.tsx+++ b/packages/marketing/src/forms/MarketingForm.tsx@@ -1,6 +1,6 @@'use client'-import { useState } from 'react'+import { useRef, useState } from 'react'import ReactMarkdown from 'react-markdown'import {Button,@@ -62,6 +62,13 @@ export interface MarketingFormProps {type SubmitState = 'idle' | 'loading' | 'success' | 'error'+/** Build the sessionStorage key used to block double-submits of the same email to the same form. */+function dedupeKey(crm: MarketingFormCrmConfig | undefined, email: string): string | null {+ const formId = crm?.hubspot?.formGuid ?? crm?.notion?.database_id+ if (!formId || !email) return null+ return `marketing-form-submitted:${formId}:${email.trim().toLowerCase()}`+}+function FieldInput({field,value,@@ -168,6 +175,12 @@ export default function MarketingForm({)const [submitState, setSubmitState] = useState<SubmitState>('idle')const [errorMessages, setErrorMessages] = useState<string[]>([])+ // Anti-spam: tracks when the form was first rendered. Submissions that come+ // back faster than MIN_FORM_RENDER_MS on the server are rejected as bot-like.+ const formMountedAtRef = useRef<number>(Date.now())+ // Anti-spam: honeypot. Real users never see or focus this field. The value+ // is kept out of `values` so it never reaches the CRM payload.+ const honeypotRef = useRef<HTMLInputElement>(null)const handleChange = (name: string, value: string) => {setValues((prev) => ({ ...prev, [name]: value }))@@ -204,16 +217,54 @@ export default function MarketingForm({return}+ // Block repeat submissions of the same email to the same form within this+ // browser session. Render the success state instead of re-hitting the CRM.+ const emailValue =+ submittedValues['email'] ??+ submittedValues['workEmail'] ??+ submittedValues['work_email'] ??+ submittedValues['emailAddress'] ??+ submittedValues['email_address'] ??+ ''+ const sessionKey = dedupeKey(crm, emailValue)+ if (sessionKey && typeof window !== 'undefined') {+ try {+ if (window.sessionStorage.getItem(sessionKey)) {+ if (successRedirect) {+ window.location.href = successRedirect+ } else {+ setSubmitState('success')+ }+ return+ }+ } catch {+ // sessionStorage can throw in private mode / disabled storage — ignore.+ }+ }+setSubmitState('loading')setErrorMessages([])const pageUri = typeof window !== 'undefined' ? window.location.href : undefinedconst pageName = typeof document !== 'undefined' ? document.title : undefined+ const honeypot = honeypotRef.current?.value ?? ''try {- const result = await submitFormAction(crm, submittedValues, { pageUri, pageName })+ const result = await submitFormAction(crm, submittedValues, {+ pageUri,+ pageName,+ honeypot,+ formMountedAt: formMountedAtRef.current,+ })if (result.success) {+ if (sessionKey && typeof window !== 'undefined') {+ try {+ window.sessionStorage.setItem(sessionKey, '1')+ } catch {+ // Storage write can fail in private mode — non-fatal.+ }+ }if (successRedirect) {window.location.href = successRedirect} else {@@ -295,6 +346,27 @@ export default function MarketingForm({: 'flex flex-col gap-6'}>+ {/*+ Honeypot: positioned off-screen rather than display:none so that+ headless bots scraping the form still see and (often) fill it.+ aria-hidden + tabIndex=-1 keep it out of the user journey.+ */}+ <div+ aria-hidden="true"+ className="absolute -left-[9999px] top-auto h-px w-px overflow-hidden"+ >+ <label>+ Website+ <input+ ref={honeypotRef}+ type="text"+ name="website"+ tabIndex={-1}+ autoComplete="off"+ defaultValue=""+ />+ </label>+ </div>{rows.map((row, rowIndex) => (<divkey={rowIndex}diff --git a/packages/marketing/src/go/actions/submitForm.ts b/packages/marketing/src/go/actions/submitForm.tsindex 598d0462a65..c1770bb73ec 100644--- a/packages/marketing/src/go/actions/submitForm.ts+++ b/packages/marketing/src/go/actions/submitForm.ts@@ -8,6 +8,12 @@ export interface FormSubmitResult {errors: string[]}+/** Hidden field added by MarketingForm — bots fill it, humans never see it. */+const HONEYPOT_FIELD = 'website'++/** Minimum milliseconds a form must be on the page before a submission is accepted. */+const MIN_FORM_RENDER_MS = 3000+// Enable debug logging in local dev and on Vercel preview/development deploymentsconst isDebug =process.env.NODE_ENV === 'development' ||@@ -62,18 +68,43 @@ function buildCrmConfig(crm: GoFormCrmConfig): CRMConfig {export async function submitFormAction(crm: GoFormCrmConfig,values: Record<string, string>,- context?: { pageUri?: string; pageName?: string }+ context?: { pageUri?: string; pageName?: string; honeypot?: string; formMountedAt?: number }): Promise<FormSubmitResult> {debug('Form submission received', { crm, values, context })+ // Anti-spam: honeypot tripped or form submitted suspiciously fast. Return a+ // fake success so bots think they got through and don't retry with variations.+ const honeypot = context?.honeypot ?? values[HONEYPOT_FIELD] ?? ''+ if (honeypot.trim() !== '') {+ console.warn('[go/form] Rejected submission: honeypot tripped', {+ pageUri: context?.pageUri,+ })+ return { success: true, errors: [] }+ }++ if (+ typeof context?.formMountedAt === 'number' &&+ Date.now() - context.formMountedAt < MIN_FORM_RENDER_MS+ ) {+ console.warn('[go/form] Rejected submission: form submitted too quickly', {+ pageUri: context.pageUri,+ elapsedMs: Date.now() - context.formMountedAt,+ })+ return { success: true, errors: [] }+ }+try {+ // The honeypot field is never part of the real payload, even if a real+ // form happens to include a `website` field name.+ const { [HONEYPOT_FIELD]: _honeypot, ...payloadValues } = values+// Detect the email value from common field namesconst email =- values['email'] ??- values['workEmail'] ??- values['work_email'] ??- values['emailAddress'] ??- values['email_address'] ??+ payloadValues['email'] ??+ payloadValues['workEmail'] ??+ payloadValues['work_email'] ??+ payloadValues['emailAddress'] ??+ payloadValues['email_address'] ??''if (!email) {@@ -102,7 +133,7 @@ export async function submitFormAction(if (crm.hubspot) {const fieldMap = crm.hubspot.fieldMap ?? {}hubspotFields = {}- for (const [formField, value] of Object.entries(values)) {+ for (const [formField, value] of Object.entries(payloadValues)) {const hsField = fieldMap[formField] ?? formFieldhubspotFields[hsField] = value}@@ -115,13 +146,13 @@ export async function submitFormAction(if (crm.customerio?.profileMap) {customerioProfile = {}for (const [formField, attrName] of Object.entries(crm.customerio.profileMap)) {- customerioProfile[attrName] = values[formField]+ customerioProfile[attrName] = payloadValues[formField]}}if (crm.customerio) {debug('Customer.io payload', {event: crm.customerio.event,- properties: values,+ properties: payloadValues,customerioProfile,})}@@ -132,8 +163,8 @@ export async function submitFormAction(const columnMap = crm.notion.columnMap ?? {}const properties: Record<string, unknown> = {}for (const [formField, columnName] of Object.entries(columnMap)) {- if (formField in values) {- properties[columnName] = values[formField]+ if (formField in payloadValues) {+ properties[columnName] = payloadValues[formField]}}if (crm.notion.staticProperties) {@@ -146,11 +177,11 @@ export async function submitFormAction(const { errors } = await client.submitEvent({email,hubspotFields,- context,+ context: context && { pageUri: context.pageUri, pageName: context.pageName },consent,event: crm.customerio?.event,properties: crm.customerio- ? { ...(values as Record<string, unknown>), ...crm.customerio.staticProperties }+ ? { ...(payloadValues as Record<string, unknown>), ...crm.customerio.staticProperties }: undefined,customerioProfile,notion,