:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(support): validate email format on the logged-out support form (#81071)
Eleftheria Trivyzaki9f5656efd061
diff --git a/frontend/src/lib/components/Support/supportLogic.test.ts b/frontend/src/lib/components/Support/supportLogic.test.tsindex 6eb66a2701d0..789cc16a457c 100644--- a/frontend/src/lib/components/Support/supportLogic.test.ts+++ b/frontend/src/lib/components/Support/supportLogic.test.ts@@ -3,7 +3,7 @@ import posthog from 'posthog-js'import { sidePanelStateLogic } from '~/layout/navigation-3000/sidepanel/sidePanelStateLogic'import { initKeaTests } from '~/test/init'-import { SidePanelTab } from '~/types'+import { AppContext, SidePanelTab } from '~/types'import {CONVERSATIONS_MESSAGE_MAX_LENGTH,@@ -18,6 +18,13 @@ import * as SupportModal from './SupportModal'const openSupportModal = jest.spyOn(SupportModal, 'openSupportModal').mockImplementation(() => {})describe('supportLogic', () => {+ const conversationsMock = (sendMessage: jest.Mock): void => {+ ;(posthog as any).conversations = { isAvailable: () => true, sendMessage }+ }++ const sendFailures = (): unknown[][] =>+ (posthog.capture as jest.Mock).mock.calls.filter(([event]) => event === 'support ticket send blocked')+describe('openSupportForm modal vs side panel target', () => {let logic: ReturnType<typeof supportLogic.build>@@ -78,16 +85,9 @@ describe('supportLogic', () => {let logic: ReturnType<typeof supportLogic.build>- const conversationsMock = (sendMessage: jest.Mock): void => {- ;(posthog as any).conversations = { isAvailable: () => true, sendMessage }- }-const aiTicketCaptures = (): unknown[][] =>(posthog.capture as jest.Mock).mock.calls.filter(([event]) => event === 'posthog_ai_support_ticket_created')- const sendFailures = (): unknown[][] =>- (posthog.capture as jest.Mock).mock.calls.filter(([event]) => event === 'support ticket send blocked')-beforeEach(() => {;(posthog.capture as jest.Mock).mockClear()initKeaTests()@@ -264,4 +264,88 @@ describe('supportLogic', () => {expect(aiTicketCaptures()).toHaveLength(0)})})++ // Nobody is signed in on /login or /reset, so the form asks for an address, and it is the only+ // route back to whoever filed the ticket. An unusable one still files it but orphans it: replies+ // to a widget ticket are in-app only, and restore-by-email matches anonymous_traits.email, so a+ // first name in that field leaves the person no way back once the browser session is gone.+ describe('email validation when logged out', () => {+ let logic: ReturnType<typeof supportLogic.build>++ const LOGGED_OUT_FIELDS: SupportFormFields = {+ name: 'Jane',+ email: '[email protected]',+ kind: 'support',+ billing_issue: false,+ message: 'Help!',+ }++ beforeEach(() => {+ ;(posthog.capture as jest.Mock).mockClear()+ // initKeaTests bootstraps a user, which would leave the guard unreachable+ window.POSTHOG_APP_CONTEXT = { current_user: null } as unknown as AppContext+ initKeaTests()+ logic = supportLogic.build()+ logic.mount()+ })++ afterEach(() => {+ logic?.unmount()+ delete (posthog as any).conversations+ // Clear so the next test gets initKeaTests' usual bootstrapped user+ delete window.POSTHOG_APP_CONTEXT+ })++ it.each([+ ['a first name', 'Jane'],+ ['an address with no TLD to deliver to', 'jane@localhost'],+ ])('blocks the form submit and says why for %s', async (_case, email) => {+ const sendMessage = jest.fn().mockResolvedValue({ ticket_id: 't1' })+ conversationsMock(sendMessage)+ logic.actions.setSendSupportRequestValues({ ...LOGGED_OUT_FIELDS, email })++ await expectLogic(logic, () => {+ logic.actions.submitSendSupportRequest()+ }).toFinishAllListeners()++ expect(logic.values.sendSupportRequestErrors.email).toBe('Please enter a valid email address')+ expect(sendMessage).not.toHaveBeenCalled()+ })++ // Over-blocking would be the worse regression: it would take away the only support channel+ // someone locked out of their account has. Pasted addresses often carry stray whitespace,+ // so those must pass too — trimmed, since restore-by-email matches the stored value exactly.+ it.each([+ ['a real address', '[email protected]'],+ ['a real address pasted with whitespace', ' [email protected] '],+ ])('still files the ticket for %s, sending it trimmed', async (_case, email) => {+ const sendMessage = jest.fn().mockResolvedValue({ ticket_id: 't1' })+ conversationsMock(sendMessage)+ logic.actions.setSendSupportRequestValues({ ...LOGGED_OUT_FIELDS, email })++ await expectLogic(logic, () => {+ logic.actions.submitSendSupportRequest()+ }).toFinishAllListeners()++ expect(logic.values.sendSupportRequestErrors.email).toBeUndefined()+ expect(sendMessage).toHaveBeenCalledWith('Help!', { name: 'Jane', email: '[email protected]' }, true)+ })++ // The PostHog AI handovers submit through a plain onClick rather than a form submit, so they+ // never run the validator above — the address has to be checked on the path every caller shares+ it.each([+ ['a malformed address', 'Jane'],+ ['no address at all', ''],+ ])('files no ticket when a caller bypasses the form with %s', async (_case, email) => {+ const sendMessage = jest.fn().mockResolvedValue({ ticket_id: 't1' })+ conversationsMock(sendMessage)++ await logic.asyncActions.submitSupportTicket({ ...LOGGED_OUT_FIELDS, email })++ expect(sendMessage).not.toHaveBeenCalled()+ expect(logic.values.lastSubmittedTicketId).toBeNull()+ expect(sendFailures()).toHaveLength(1)+ expect(sendFailures()[0][1]).toMatchObject({ reason: 'invalid_email' })+ })+ })})diff --git a/frontend/src/lib/components/Support/supportLogic.ts b/frontend/src/lib/components/Support/supportLogic.tsindex b8697e487eed..e11609c8bb96 100644--- a/frontend/src/lib/components/Support/supportLogic.ts+++ b/frontend/src/lib/components/Support/supportLogic.ts@@ -4,6 +4,7 @@ import type { DeepPartial, DeepPartialMap, FieldName, ValidationErrorType } fromimport posthog from 'posthog-js'import { EMAIL_SUPPORT_BUTTON, lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'+import { isEmail } from 'lib/utils/url'import { billingLogic } from 'scenes/billing/billingLogic'import { userLogic } from 'scenes/userLogic'@@ -38,6 +39,11 @@ async function waitForConversations(timeoutMs = 5000): Promise<boolean> {// through posthog.conversations.sendMessage (the widget endpoint), so guard against the same cap.export const CONVERSATIONS_MESSAGE_MAX_LENGTH = 10000+// One email rule shared by the form validator and the submit guard, so the two can't drift.+// Trimmed because pasted addresses often carry stray whitespace; requireTLD because an address+// without one can't be delivered to, making it no better than a blank field for replying.+const isDeliverableEmail = (email: string): boolean => isEmail(email.trim(), { requireTLD: true })+/** Where the customer was when support broke for them. */export type SupportFailureSurface =| 'support_form' // the modal / side-panel support form (every "contact support" CTA)@@ -52,6 +58,7 @@ export type SupportSendFailureReason =| 'send_failed' // the request threw| 'message_too_long' // rejected by the client-side cap before we tried| 'not_entitled' // plan has no ticket channel, so the draft was dropped on the floor+ | 'invalid_email' // logged-out submit with no usable reply address, so the ticket would be orphaned/** Why a support surface couldn't function. Nothing was submitted, so no message is at risk. */export type SupportLoadFailureReason =@@ -427,7 +434,13 @@ export const supportLogic = kea<supportLogicType>([errors: ({ name, email, message }) => {return {name: !values.user && !name ? 'Please enter your name' : undefined,- email: !values.user && !email ? 'Please enter your email' : undefined,+ email: !values.user+ ? !email.trim()+ ? 'Please enter your email'+ : !isDeliverableEmail(email)+ ? 'Please enter a valid email address'+ : undefined+ : undefined,message: !message ? 'Please enter a message' : undefined,}},@@ -518,7 +531,10 @@ export const supportLogic = kea<supportLogicType>([actions.updateUrlParams()},submitSupportTicket: async (formValues: SupportFormFields) => {- const { name, email, kind, message, exception_event } = formValues+ const { name, kind, message, exception_event } = formValues+ // Trimmed before validating and sending: restore-by-email matches the stored trait+ // exactly, so stray whitespace would make the ticket unrecoverable+ const email = formValues.email.trim()const { ai_conversation_id, ai_trace_id, ai_feedback_rating } = formValues// Attribute PostHog AI (/ticket, feedback) handovers to the conversation. The ticket id@@ -553,6 +569,16 @@ export const supportLogic = kea<supportLogicType>([})}+ // The form's own validator only runs on a form submit, and the PostHog AI handovers submit+ // straight from a button — so the reply address is checked here, on the path every caller+ // shares. Without one a logged-out ticket is unreachable: widget replies are in-app only,+ // and restoring by email is the sole way back if that browser session is gone.+ if (!values.user && !isDeliverableEmail(email)) {+ captureSupportTicketBlocked({ surface: 'support_form', reason: 'invalid_email', message, kind })+ lemonToast.error('Please enter a valid email address so our support engineers can reply.')+ return+ }+if (!(await waitForConversations())) {sendFailed('widget_unavailable')return