Skip to content

: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.

feat(auth): verify signup email with a 6 code instead of a link (#86493)

Alex Liderb875930f6106
diff --git a/frontend/src/generated/core/api.schemas.ts b/frontend/src/generated/core/api.schemas.ts
index 9cd8c2c3e60f..63cd18826880 100644
--- a/frontend/src/generated/core/api.schemas.ts
+++ b/frontend/src/generated/core/api.schemas.ts
@@ -4752,6 +4752,18 @@ export interface UserPushTokenUnregisterRequestApi {
token: string
}
+/**
+ * Request body for POST /api/users/verify_email/. Exactly one of token or code is required.
+ */
+export interface VerifyEmailRequestApi {
+ /** UUID of the user whose email is being verified. */
+ uuid: string
+ /** Verification token from the emailed link. Required unless a code is provided. */
+ token?: string
+ /** The 6-digit verification code emailed at signup. Whitespace, invisible characters, and grouping hyphens are removed and compatibility digits are folded to ASCII before checking. */
+ code?: string
+}
+
export type CimdVerificationTokensListParams = {
/**
* Number of results to return per page.
diff --git a/frontend/src/generated/core/api.ts b/frontend/src/generated/core/api.ts
index 2aed0839ec75..54bad2e4b9c8 100644
--- a/frontend/src/generated/core/api.ts
+++ b/frontend/src/generated/core/api.ts
@@ -88,6 +88,7 @@ import type {
UsersIntegrationsListParams,
UsersListParams,
UsersLoginSessionsListParams,
+ VerifyEmailRequestApi,
} from './api.schemas'
// https://stackoverflow.com/questions/49579094/typescript-conditional-types-filter-out-readonly-properties-pick-only-requir/49579497#49579497
@@ -3103,11 +3104,14 @@ export const getUsersVerifyEmailCreateUrl = () => {
return `/api/users/verify_email/`
}
-export const usersVerifyEmailCreate = async (userApi: NonReadonly<UserApi>, options?: RequestInit): Promise<void> => {
+export const usersVerifyEmailCreate = async (
+ verifyEmailRequestApi: VerifyEmailRequestApi,
+ options?: RequestInit
+): Promise<void> => {
return apiMutator<void>(getUsersVerifyEmailCreateUrl(), {
...options,
method: 'POST',
headers: { 'Content-Type': 'application/json', ...options?.headers },
- body: JSON.stringify(userApi),
+ body: JSON.stringify(verifyEmailRequestApi),
})
}
diff --git a/frontend/src/generated/core/api.zod.ts b/frontend/src/generated/core/api.zod.ts
index c090de42d7ac..63054a7f3d89 100644
--- a/frontend/src/generated/core/api.zod.ts
+++ b/frontend/src/generated/core/api.zod.ts
@@ -2007,90 +2007,18 @@ export const UsersRequestEmailVerificationCreateBody = /* @__PURE__ */ zod.objec
),
})
-export const usersVerifyEmailCreateBodyFirstNameMax = 150
-
-export const usersVerifyEmailCreateBodyLastNameMax = 150
-
-export const usersVerifyEmailCreateBodyEmailMax = 254
-
-export const usersVerifyEmailCreateBodyPasswordMax = 128
-
-export const UsersVerifyEmailCreateBody = /* @__PURE__ */ zod.object({
- first_name: zod.string().max(usersVerifyEmailCreateBodyFirstNameMax).optional(),
- last_name: zod.string().max(usersVerifyEmailCreateBodyLastNameMax).optional(),
- email: zod.email().max(usersVerifyEmailCreateBodyEmailMax),
- notification_settings: zod
- .record(zod.string(), zod.unknown())
- .optional()
- .describe(
- 'Map of notification preferences. Keys include `plugin_disabled`, `all_weekly_report_disabled`, `project_weekly_digest_disabled`, `error_tracking_weekly_digest_project_enabled`, `web_analytics_weekly_digest_project_enabled`, `organization_member_join_email_disabled`, `data_pipeline_error_threshold` (number between 0.0 and 1.0), and other per-topic switches. Values are either booleans, or (for per-project\/per-resource keys) a map of IDs to booleans. Only the keys you send are updated — other preferences stay as-is.'
- ),
- anonymize_data: zod
- .boolean()
- .nullish()
- .describe('Whether PostHog should anonymize events captured for this user when identified.'),
- allow_impersonation: zod.boolean().nullish(),
- toolbar_mode: zod
- .union([
- zod.enum(['disabled', 'toolbar']).describe('\* `disabled` - disabled\n\* `toolbar` - toolbar'),
- zod.enum(['']),
- zod.null(),
- ])
- .optional(),
- is_staff: zod.boolean().optional().describe('Designates whether the user can log into this admin site.'),
- set_current_organization: zod.string().optional(),
- set_current_team: zod.string().optional(),
- password: zod.string().max(usersVerifyEmailCreateBodyPasswordMax),
- current_password: zod
- .string()
- .optional()
- .describe(
- "The user's current password. Required when changing `password` if the user already has a usable password set."
- ),
- events_column_config: zod.unknown().optional(),
- has_seen_product_intro_for: zod.unknown().optional(),
- theme_mode: zod
- .union([
- zod
- .enum(['light', 'dark', 'system'])
- .describe('\* `light` - Light\n\* `dark` - Dark\n\* `system` - System'),
- zod.enum(['']),
- zod.null(),
- ])
- .optional(),
- hedgehog_config: zod.unknown().optional(),
- allow_sidebar_suggestions: zod.boolean().nullish(),
- shortcut_position: zod
- .union([
- zod
- .enum(['above', 'below', 'hidden'])
- .describe('\* `above` - Above\n\* `below` - Below\n\* `hidden` - Hidden'),
- zod.enum(['']),
- zod.null(),
- ])
- .optional(),
- role_at_organization: zod
- .enum(['engineering', 'data', 'product', 'founder', 'leadership', 'marketing', 'sales', 'student', 'other'])
- .optional()
- .describe(
- '\* `engineering` - Engineering\n\* `data` - Data\n\* `product` - Product Management\n\* `founder` - Founder\n\* `leadership` - Leadership\n\* `marketing` - Marketing\n\* `sales` - Sales \/ Success\n\* `student` - Student\n\* `other` - Other'
- ),
- passkeys_enabled_for_2fa: zod
- .boolean()
- .nullish()
- .describe(
- 'Whether passkeys are enabled for 2FA authentication. Users can disable this to use only TOTP for 2FA while keeping passkeys for login.'
- ),
- hide_mcp_hints: zod
- .boolean()
- .optional()
- .describe(
- 'When true, the user has opted out of in-app hints promoting the PostHog MCP integration after taking actions.'
- ),
- ui_configuration: zod
- .unknown()
- .optional()
- .describe(
- 'Per-user UI customization, validated against the `UserUIConfiguration` schema. Currently covers sidebar section and item visibility. Send the complete object: it replaces the stored value wholesale. Null means no customization; absent keys mean the element is shown.'
- ),
-})
+export const UsersVerifyEmailCreateBody = /* @__PURE__ */ zod
+ .object({
+ uuid: zod.string().describe('UUID of the user whose email is being verified.'),
+ token: zod
+ .string()
+ .optional()
+ .describe('Verification token from the emailed link. Required unless a code is provided.'),
+ code: zod
+ .string()
+ .optional()
+ .describe(
+ 'The 6-digit verification code emailed at signup. Whitespace, invisible characters, and grouping hyphens are removed and compatibility digits are folded to ASCII before checking.'
+ ),
+ })
+ .describe('Request body for POST \/api\/users\/verify_email\/. Exactly one of token or code is required.')
diff --git a/frontend/src/scenes/authentication/login/loginLogic.ts b/frontend/src/scenes/authentication/login/loginLogic.ts
index 74bdcbb2cbfd..cdda385b788e 100644
--- a/frontend/src/scenes/authentication/login/loginLogic.ts
+++ b/frontend/src/scenes/authentication/login/loginLogic.ts
@@ -16,6 +16,7 @@ import { isWebKitBrowser } from 'lib/utils/dom'
import { getCurrentTeamIdOrNone } from 'lib/utils/getAppContext'
import { getRelativeNextPath } from 'lib/utils/url'
import { devLoginLogic } from 'scenes/authentication/shared/devLoginLogic'
+import { normalizeVerificationCode } from 'scenes/authentication/shared/verificationCode'
import { twoFactorResetLogic } from 'scenes/authentication/two-factor-reset/twoFactorResetLogic'
import { preflightLogic } from 'scenes/PreflightCheck/preflightLogic'
import { urls } from 'scenes/urls'
@@ -139,14 +140,6 @@ export interface CodeVerificationForm {
code: string
}
-// Email clients and manual entry can wrap the emailed code in whitespace or invisible characters
-// (zero-width family, word joiner, BOM, soft hyphen) or group it as "123-456". Fold compatibility
-// digits (e.g. fullwidth) to ASCII and drop that noise so a pasted code matches the server's 6 digits.
-const CODE_NOISE_RE = /[\s\u200b-\u200d\u2060\ufeff\u00ad-]/g
-function normalizeVerificationCode(code: string): string {
- return (code ?? '').normalize('NFKC').replace(CODE_NOISE_RE, '')
-}
-
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface loginLogicValues {
devLoginTimeSavedLabel: string | null // devLoginLogic
@@ -579,6 +572,13 @@ export const loginLogic = kea<loginLogicType>([
}
throw e
}
+ if (code === 'verify_email_pending' && typeof detail === 'string') {
+ // detail carries the user uuid; the verification page has the code entry form
+ lemonToast.info('Verify your email to continue. We just sent you a new code.')
+ const next: string | undefined = router.values.searchParams.next
+ router.actions.push(urls.verifyEmail(detail), next ? { next } : {})
+ throw e
+ }
if (code === 'code_based_verification_required') {
const emailAddress = detail?.email || email
actions.setCodeVerificationRequired()
diff --git a/frontend/src/scenes/authentication/shared/verificationCode.ts b/frontend/src/scenes/authentication/shared/verificationCode.ts
new file mode 100644
index 000000000000..efbf215e76b9
--- /dev/null
+++ b/frontend/src/scenes/authentication/shared/verificationCode.ts
@@ -0,0 +1,22 @@
+// Email clients and manual entry can wrap the emailed code in whitespace or invisible characters
+// (zero-width family, word joiner, BOM, soft hyphen) or group it as "123-456". Fold compatibility
+// digits (e.g. fullwidth) to ASCII and drop that noise so a pasted code matches the server's 6 digits.
+const CODE_NOISE_RE = /[\s\u200b-\u200d\u2060\ufeff\u00ad-]/g
+
+export function normalizeVerificationCode(code: string): string {
+ return (code ?? '').normalize('NFKC').replace(CODE_NOISE_RE, '')
+}
+
+export function isValidVerificationCode(code: string): boolean {
+ return /^\d{6}$/.test(code)
+}
+
+export function verificationCodeErrorMessage(e: { code?: string; detail?: string }): string {
+ if (e.code === 'too_many_attempts') {
+ return 'Too many incorrect attempts. Request a new code and try again.'
+ }
+ if (e.code === 'throttled') {
+ return 'Too many attempts. Wait a few minutes and try again.'
+ }
+ return e.detail || 'This code is invalid or has expired.'
+}
diff --git a/frontend/src/scenes/authentication/verify-email/VerifyEmailForm.tsx b/frontend/src/scenes/authentication/verify-email/VerifyEmailForm.tsx
index 5337c9ef3f0d..d1d3c42b0c63 100644
--- a/frontend/src/scenes/authentication/verify-email/VerifyEmailForm.tsx
+++ b/frontend/src/scenes/authentication/verify-email/VerifyEmailForm.tsx
@@ -7,6 +7,7 @@ import { pngHoggie } from 'lib/brand/hoggies'
import { ExplorerHog, SleepingHog } from 'lib/components/hedgehogs'
import { supportLogic } from 'lib/components/Support/supportLogic'
import { LemonButton } from 'lib/lemon-ui/LemonButton'
+import { LemonInput } from 'lib/lemon-ui/LemonInput'
import { Link } from 'lib/lemon-ui/Link'
import { Spinner } from 'lib/lemon-ui/Spinner/Spinner'
import { AuthScene, AuthSceneCard } from 'scenes/authentication/shared/authScene/AuthScene'
@@ -105,6 +106,54 @@ function NotSeeingIt(): JSX.Element {
)
}
+function VerificationCodeEntry(): JSX.Element {
+ const { verificationCode, verificationCodeError, validatedEmailTokenLoading } = useValues(verifyEmailLogic)
+ const { setVerificationCode, submitVerificationCode } = useActions(verifyEmailLogic)
+
+ return (
+ <form
+ className="flex w-full flex-col gap-2.5"
+ onSubmit={(e) => {
+ e.preventDefault()
+ if (!validatedEmailTokenLoading) {
+ submitVerificationCode()
+ }
+ }}
+ >
+ <LemonInput
+ autoFocus
+ value={verificationCode}
+ onChange={setVerificationCode}
+ placeholder="123456"
+ aria-label="Email verification code"
+ inputMode="numeric"
+ autoComplete="one-time-code"
+ size="large"
+ className="text-center ph-replay-block"
+ data-attr="verify-email-code"
+ status={verificationCodeError ? 'danger' : 'default'}
+ />
+ {verificationCodeError && (
+ <p className="m-0 text-sm text-danger" role="alert">
+ {verificationCodeError}
+ </p>
+ )}
+ <LemonButton
+ type="primary"
+ size="large"
+ center
+ fullWidth
+ htmlType="submit"
+ loading={validatedEmailTokenLoading}
+ disabledReason={verificationCode ? undefined : 'Enter the code from your email'}
+ data-attr="verify-email-code-submit"
+ >
+ Verify email
+ </LemonButton>
+ </form>
+ )
+}
+
export function VerifyEmailForm(): JSX.Element {
const { view, uuid, newlyRequestedVerificationLinkLoading } = useValues(verifyEmailLogic)
const { requestVerificationLink } = useActions(verifyEmailLogic)
@@ -169,7 +218,7 @@ export function VerifyEmailForm(): JSX.Element {
loading={newlyRequestedVerificationLinkLoading}
onClick={() => requestVerificationLink(uuid)}
>
- Email me a new link
+ Resend verification email
</LemonButton>
)}
<LemonButton
@@ -228,9 +277,13 @@ export function VerifyEmailForm(): JSX.Element {
Check your inbox
</h1>
<p className="AuthScene__sub mt-2 mb-4 text-sm text-secondary text-center text-pretty">
- We sent you a verification link. Click the link inside and you're in. It's valid for 24 hours.
+ We emailed you a 6-digit code. Enter it below to verify your email address. The code is valid
+ for 30 minutes.
</p>
- <NotSeeingIt />
+ <VerificationCodeEntry />
+ <div className="mt-3">
+ <NotSeeingIt />
+ </div>
</div>
</AuthSceneCard>
</AuthScene>
diff --git a/frontend/src/scenes/authentication/verify-email/verifyEmailLogic.ts b/frontend/src/scenes/authentication/verify-email/verifyEmailLogic.ts
index 551875cbae25..edb7307800f3 100644
--- a/frontend/src/scenes/authentication/verify-email/verifyEmailLogic.ts
+++ b/frontend/src/scenes/authentication/verify-email/verifyEmailLogic.ts
@@ -5,6 +5,11 @@ import { router, urlToAction } from 'kea-router'
import api from 'lib/api'
import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'
import { getRelativeNextPath } from 'lib/utils/url'
+import {
+ isValidVerificationCode,
+ normalizeVerificationCode,
+ verificationCodeErrorMessage,
+} from 'scenes/authentication/shared/verificationCode'
import { urls } from 'scenes/urls'
import { userLogic } from 'scenes/userLogic'
@@ -13,6 +18,13 @@ import type { UserType } from '../../../types'
// Must stay in sync with the `VerifyEmail__Progress` animation duration in VerifyEmail.scss.
export const VERIFY_EMAIL_REDIRECT_DELAY_MS = 2000
+type PostVerifyResponse = {
+ success: boolean
+ requires_2fa?: boolean
+ requires_login?: boolean
+ requires_sso?: boolean
+}
+
const resolvePostVerifyDefault = (values: {
user?: { team?: { has_completed_onboarding_for?: Record<string, boolean> } | null } | null
}): string => {
@@ -24,6 +36,30 @@ const resolvePostVerifyDefault = (values: {
return hasCompletedSomething ? urls.default() : urls.onboarding()
}
+// A verify success without a session (2FA, blocked member, SSO-enforced domain) routes to
+// login with a matching toast. Otherwise the user goes straight into the app.
+const redirectAfterVerification = (
+ response: PostVerifyResponse,
+ values: Parameters<typeof resolvePostVerifyDefault>[0]
+): void => {
+ const nextUrl = getRelativeNextPath(new URLSearchParams(location.search).get('next'), location)
+ const loginMessage = response.requires_2fa
+ ? 'Email verified! Please log in with your password to complete two-factor authentication.'
+ : response.requires_login
+ ? 'Email verified! Log in to continue.'
+ : response.requires_sso
+ ? 'Email verified! Log in with SSO to continue.'
+ : null
+ if (loginMessage) {
+ lemonToast.success(loginMessage)
+ router.actions.push(urls.login(), nextUrl ? { next: nextUrl } : {})
+ return
+ }
+ // this url is validated in getRelativeNextPath as either being relative or on the same origin
+ // nosemgrep: javascript.browser.security.open-redirect.js-open-redirect
+ location.href = nextUrl || resolvePostVerifyDefault(values)
+}
+
export interface ResponseType {
success: boolean
errorCode?: string
@@ -43,6 +79,8 @@ export interface verifyEmailLogicValues {
uuid: string | null
validatedEmailToken: ValidatedTokenResponseType | null
validatedEmailTokenLoading: boolean
+ verificationCode: string
+ verificationCodeError: string | null
view: 'invalid' | 'pending' | 'success' | 'verify' | null
}
@@ -72,9 +110,36 @@ export interface verifyEmailLogicActions {
setUuid: (uuid: string | null) => {
uuid: string | null
}
+ setVerificationCode: (code: string) => {
+ code: string
+ }
+ setVerificationCodeError: (error: string | null) => {
+ error: string | null
+ }
setView: (view: 'invalid' | 'pending' | 'success' | 'verify' | null) => {
view: 'invalid' | 'pending' | 'success' | 'verify' | null
}
+ submitVerificationCode: () => {
+ value: true
+ }
+ submitVerificationCodeFailure: (
+ error: string,
+ errorObject?: any
+ ) => {
+ error: string
+ errorObject?: any
+ }
+ submitVerificationCodeSuccess: (
+ validatedEmailToken: ValidatedTokenResponseType | null,
+ payload?: {
+ value: true
+ }
+ ) => {
+ validatedEmailToken: ValidatedTokenResponseType | null
+ payload?: {
+ value: true
+ }
+ }
validateEmailToken: ({ uuid, token }: { token: string; uuid: string }) => {
uuid: string
token: string
@@ -138,6 +203,9 @@ export const verifyEmailLogic = kea<verifyEmailLogicType>([
setView: (view: 'verify' | 'pending' | 'invalid' | 'success' | null) => ({ view }),
setUuid: (uuid: string | null) => ({ uuid }),
requestVerificationLink: (uuid: string) => ({ uuid }),
+ setVerificationCode: (code: string) => ({ code }),
+ setVerificationCodeError: (error: string | null) => ({ error }),
+ submitVerificationCode: true,
}),
loaders(({ actions, values }) => ({
validatedEmailToken: [
@@ -145,26 +213,13 @@ export const verifyEmailLogic = kea<verifyEmailLogicType>([
{
validateEmailToken: async ({ uuid, token }: { uuid: string; token: string }, breakpoint) => {
try {
- const response = await api.create<{ success: boolean; token?: string; requires_2fa?: boolean }>(
- `api/users/verify_email/`,
- { token, uuid }
- )
+ const response = await api.create<PostVerifyResponse>(`api/users/verify_email/`, {
+ token,
+ uuid,
+ })
actions.setView('success')
await breakpoint(VERIFY_EMAIL_REDIRECT_DELAY_MS)
-
- const nextUrl = getRelativeNextPath(new URLSearchParams(location.search).get('next'), location)
- if (response.requires_2fa) {
- lemonToast.success(
- 'Email verified! Please log in with your password to complete two-factor authentication.'
- )
- router.actions.push(urls.login(), nextUrl ? { next: nextUrl } : {})
- return { success: true, token, uuid }
- }
-
- // this url is validated in getRelativeNextPath as either being relative or on the same origin
- // this url is also secret and so we can trust it's not attacker controlled
- // nosemgrep: javascript.browser.security.open-redirect.js-open-redirect
- location.href = nextUrl || resolvePostVerifyDefault(values)
+ redirectAfterVerification(response, values)
return { success: true, token, uuid }
} catch (e: any) {
const user = (values as any).user
@@ -184,6 +239,30 @@ export const verifyEmailLogic = kea<verifyEmailLogicType>([
return { success: false, errorCode: e.code, errorDetail: e.detail }
}
},
+ submitVerificationCode: async (_, breakpoint) => {
+ const uuid = values.uuid
+ const code = normalizeVerificationCode(values.verificationCode)
+ if (!uuid) {
+ return values.validatedEmailToken
+ }
+ if (!isValidVerificationCode(code)) {
+ actions.setVerificationCodeError('Enter the 6-digit code from your email.')
+ return values.validatedEmailToken
+ }
+ try {
+ const response = await api.create<PostVerifyResponse>(`api/users/verify_email/`, {
+ uuid,
+ code,
+ })
+ actions.setView('success')
+ await breakpoint(VERIFY_EMAIL_REDIRECT_DELAY_MS)
+ redirectAfterVerification(response, values)
+ return { success: true, uuid }
+ } catch (e: any) {
+ actions.setVerificationCodeError(verificationCodeErrorMessage(e))
+ return values.validatedEmailToken
+ }
+ },
},
],
newlyRequestedVerificationLink: [
@@ -193,8 +272,14 @@ export const verifyEmailLogic = kea<verifyEmailLogicType>([
try {
await api.create(`api/users/request_email_verification/`, { uuid })
lemonToast.success(
- 'A new verification link has been sent to the associated email address. Please check your inbox.'
+ 'A new verification email has been sent to the associated email address. Please check your inbox.'
)
+ // A resend invalidates the previous code, so drop it and its error (the
+ // setVerificationCode reducer clears the error too). The 6-char field is
+ // otherwise full and blocks typing the freshly sent code.
+ actions.setVerificationCode('')
+ // Show the pending view after a resend - it has the code entry form.
+ actions.setView('pending')
return true
} catch (e: any) {
if (e.code === 'throttled') {
@@ -225,6 +310,20 @@ export const verifyEmailLogic = kea<verifyEmailLogicType>([
setUuid: (_, { uuid }) => uuid,
},
],
+ verificationCode: [
+ '',
+ {
+ setVerificationCode: (_, { code }) => code,
+ },
+ ],
+ verificationCodeError: [
+ null as string | null,
+ {
+ setVerificationCode: () => null,
+ submitVerificationCode: () => null,
+ setVerificationCodeError: (_, { error }) => error,
+ },
+ ],
}),
urlToAction(({ actions }) => ({
'/verify_email/:uuid': ({ uuid }) => {
diff --git a/frontend/src/scenes/settings/user/EmailChangeVerificationModal.tsx b/frontend/src/scenes/settings/user/EmailChangeVerificationModal.tsx
new file mode 100644
index 000000000000..dcca4c30fcae
--- /dev/null
+++ b/frontend/src/scenes/settings/user/EmailChangeVerificationModal.tsx
@@ -0,0 +1,106 @@
+import { useActions, useValues } from 'kea'
+
+import * as magnifyingGlassPng from '@posthog/brand/hoggies/png/magnifying-glass-1'
+
+import { pngHoggie } from 'lib/brand/hoggies'
+import { supportLogic } from 'lib/components/Support/supportLogic'
+import { LemonButton } from 'lib/lemon-ui/LemonButton'
+import { LemonInput } from 'lib/lemon-ui/LemonInput'
+import { LemonModal } from 'lib/lemon-ui/LemonModal'
+import { userLogic } from 'scenes/userLogic'
+
+import { MAX_RESENDS, emailChangeVerificationLogic } from './emailChangeVerificationLogic'
+
+const HedgehogMagnifyingGlass = pngHoggie(magnifyingGlassPng)
+
+export function EmailChangeVerificationModal(): JSX.Element {
+ const {
+ modalOpen,
+ verificationCode,
+ verificationCodeError,
+ verificationResultLoading,
+ resendResultLoading,
+ resendCooldown,
+ resendsUsed,
+ } = useValues(emailChangeVerificationLogic)
+ const { closeModal, setVerificationCode, submitVerificationCode, resendCode } =
+ useActions(emailChangeVerificationLogic)
+ const { openSupportForm } = useActions(supportLogic)
+ const { user } = useValues(userLogic)
+
+ return (
+ <LemonModal isOpen={modalOpen} onClose={closeModal} simple width={480}>
+ <form
+ className="flex flex-col items-center gap-2.5 p-6 text-center"
+ onSubmit={(e) => {
+ e.preventDefault()
+ if (!verificationResultLoading) {
+ submitVerificationCode()
+ }
+ }}
+ >
+ <HedgehogMagnifyingGlass className="block w-auto mx-auto h-28" />
+ <h2 className="m-0 text-2xl font-bold">Check your inbox</h2>
+ <p className="m-0 mb-2 text-secondary text-pretty">
+ We emailed a 6-digit code to <strong>{user?.pending_email}</strong>. Enter it below to verify your
+ new address. The code is valid for 30 minutes.
+ </p>
+ <LemonInput
+ autoFocus
+ value={verificationCode}
+ onChange={setVerificationCode}
+ placeholder="123456"
+ aria-label="Email verification code"
+ inputMode="numeric"
+ autoComplete="one-time-code"
+ size="large"
+ fullWidth
+ data-attr="email-change-verification-code"
+ className="ph-replay-block"
+ status={verificationCodeError ? 'danger' : 'default'}
+ />
+ {verificationCodeError && (
+ <p className="m-0 text-sm text-danger" role="alert">
+ {verificationCodeError}
+ </p>
+ )}
+ <LemonButton
+ type="primary"
+ size="large"
+ center
+ fullWidth
+ htmlType="submit"
+ loading={verificationResultLoading}
+ disabledReason={verificationCode ? undefined : 'Enter the code from your email'}
+ data-attr="email-change-verification-submit"
+ >
+ Verify email
+ </LemonButton>
+ {resendsUsed < MAX_RESENDS ? (
+ <LemonButton
+ size="small"
+ center
+ loading={resendResultLoading}
+ disabledReason={resendCooldown > 0 ? `You can resend in ${resendCooldown}s` : undefined}
+ onClick={resendCode}
+ data-attr="email-change-verification-resend"
+ >
+ Not seeing it? Resend code
+ </LemonButton>
+ ) : (
+ <LemonButton
+ size="small"
+ center
+ onClick={() => {
+ closeModal()
+ openSupportForm({ kind: 'support' })
+ }}
+ data-attr="email-change-verification-contact-support"
+ >
+ Still not seeing it? Contact support
+ </LemonButton>
+ )}
+ </form>
+ </LemonModal>
+ )
+}
diff --git a/frontend/src/scenes/settings/user/UserDetails.tsx b/frontend/src/scenes/settings/user/UserDetails.tsx
index 0caab0e209d6..2ad84169c759 100644
--- a/frontend/src/scenes/settings/user/UserDetails.tsx
+++ b/frontend/src/scenes/settings/user/UserDetails.tsx
@@ -4,73 +4,87 @@ import { Form } from 'kea-forms'
import { LemonButton } from 'lib/lemon-ui/LemonButton'
import { LemonField } from 'lib/lemon-ui/LemonField'
import { LemonInput } from 'lib/lemon-ui/LemonInput/LemonInput'
+import { emailChangeVerificationLogic } from 'scenes/settings/user/emailChangeVerificationLogic'
+import { EmailChangeVerificationModal } from 'scenes/settings/user/EmailChangeVerificationModal'
import { userLogic } from 'scenes/userLogic'
export function UserDetails(): JSX.Element {
const { userLoading, isUserDetailsSubmitting, userDetailsChanged, user } = useValues(userLogic)
const { cancelEmailChangeRequest } = useActions(userLogic)
+ const { openModal } = useActions(emailChangeVerificationLogic)
return (
- <Form
- logic={userLogic}
- formKey="userDetails"
- enableFormOnSubmit
- className="deprecated-space-y-4"
- style={{
- maxWidth: '28rem',
- }}
- >
- <LemonField name="first_name" label="First name">
- <LemonInput
- className="ph-ignore-input"
- data-attr="settings-update-first-name"
- placeholder="Jane"
- disabled={userLoading}
- />
- </LemonField>
+ <>
+ <EmailChangeVerificationModal />
+ <Form
+ logic={userLogic}
+ formKey="userDetails"
+ enableFormOnSubmit
+ className="deprecated-space-y-4"
+ style={{
+ maxWidth: '28rem',
+ }}
+ >
+ <LemonField name="first_name" label="First name">
+ <LemonInput
+ className="ph-ignore-input"
+ data-attr="settings-update-first-name"
+ placeholder="Jane"
+ disabled={userLoading}
+ />
+ </LemonField>
- <LemonField name="last_name" label="Last name">
- <LemonInput
- className="ph-ignore-input"
- data-attr="settings-update-last-name"
- placeholder="Doe"
- disabled={userLoading}
- />
- </LemonField>
+ <LemonField name="last_name" label="Last name">
+ <LemonInput
+ className="ph-ignore-input"
+ data-attr="settings-update-last-name"
+ placeholder="Doe"
+ disabled={userLoading}
+ />
+ </LemonField>
- <LemonField name="email" label="Email">
- <LemonInput
- className="ph-ignore-input"
- data-attr="settings-update-email"
- placeholder="[email protected]"
- disabled={userLoading}
- />
- </LemonField>
- {user?.pending_email && (
- <div className="flex flex-row gap-2">
- <div className="text-danger text-xs font-medium mt-1.25">
- Pending verification for {user.pending_email}
+ <LemonField name="email" label="Email">
+ <LemonInput
+ className="ph-ignore-input"
+ data-attr="settings-update-email"
+ placeholder="[email protected]"
+ disabled={userLoading}
+ />
+ </LemonField>
+ {user?.pending_email && (
+ <div className="flex flex-row gap-2">
+ <div className="text-danger text-xs font-medium mt-1.25">
+ Pending verification for {user.pending_email}
+ </div>
+ <LemonButton
+ type="tertiary"
+ size="xsmall"
+ data-attr="enter-email-verification-code-button"
+ onClick={openModal}
+ >
+ Enter verification code
+ </LemonButton>
+ <LemonButton
+ type="tertiary"
+ size="xsmall"
+ data-attr="cancel-email-change-request-button"
+ onClick={cancelEmailChangeRequest}
+ >
+ Cancel change
+ </LemonButton>
</div>
- <LemonButton
- type="tertiary"
- size="xsmall"
- data-attr="cancel-email-change-request-button"
- onClick={cancelEmailChangeRequest}
- >
- Cancel change
- </LemonButton>
- </div>
- )}
+ )}
- <LemonButton
- type="primary"
- htmlType="submit"
- loading={isUserDetailsSubmitting}
- disabled={!userDetailsChanged}
- data-attr="user-details-submit-bottom"
- >
- Save name and email
- </LemonButton>
- </Form>
+ <LemonButton
+ type="primary"
+ htmlType="submit"
+ loading={isUserDetailsSubmitting}
+ disabled={!userDetailsChanged}
+ data-attr="user-details-submit-bottom"
+ >
+ Save name and email
+ </LemonButton>
+ </Form>
+ </>
)
}
diff --git a/frontend/src/scenes/settings/user/emailChangeVerificationLogic.ts b/frontend/src/scenes/settings/user/emailChangeVerificationLogic.ts
new file mode 100644
index 000000000000..b7c3fef7709d
--- /dev/null
+++ b/frontend/src/scenes/settings/user/emailChangeVerificationLogic.ts
@@ -0,0 +1,267 @@
+import { MakeLogicType, actions, connect, kea, listeners, path, reducers } from 'kea'
+import { loaders } from 'kea-loaders'
+import { subscriptions } from 'kea-subscriptions'
+
+import api from 'lib/api'
+import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'
+import {
+ isValidVerificationCode,
+ normalizeVerificationCode,
+ verificationCodeErrorMessage,
+} from 'scenes/authentication/shared/verificationCode'
+import { userLogic } from 'scenes/userLogic'
+
+import type { UserType } from '~/types'
+
+// Each resend increases the wait before the next one. After the last resend the modal
+// offers support instead.
+export const RESEND_COOLDOWNS_SECONDS = [30, 60]
+export const MAX_RESENDS = 2
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface emailChangeVerificationLogicValues {
+ user: UserType | null // userLogic
+ modalOpen: boolean
+ resendCooldown: number
+ resendResult: boolean | null
+ resendResultLoading: boolean
+ resendsUsed: number
+ verificationCode: string
+ verificationCodeError: string | null
+ verificationResult: {
+ success: boolean
+ } | null
+ verificationResultLoading: boolean
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface emailChangeVerificationLogicActions {
+ loadUser: (resetOnFailure?: boolean | undefined) => {
+ resetOnFailure: boolean | undefined
+ } // userLogic
+ closeModal: () => {
+ value: true
+ }
+ emailChangeStaged: () => {
+ value: true
+ }
+ openModal: () => {
+ value: true
+ }
+ resendCode: () => {
+ value: true
+ }
+ resendCodeFailure: (
+ error: string,
+ errorObject?: any
+ ) => {
+ error: string
+ errorObject?: any
+ }
+ resendCodeSuccess: (
+ resendResult: boolean | null,
+ payload?: {
+ value: true
+ }
+ ) => {
+ resendResult: boolean | null
+ payload?: {
+ value: true
+ }
+ }
+ resendLimitReached: () => {
+ value: true
+ }
+ setVerificationCode: (code: string) => {
+ code: string
+ }
+ setVerificationCodeError: (error: string | null) => {
+ error: string | null
+ }
+ startResendCooldown: (seconds: number) => {
+ seconds: number
+ }
+ submitVerificationCode: () => {
+ value: true
+ }
+ submitVerificationCodeFailure: (
+ error: string,
+ errorObject?: any
+ ) => {
+ error: string
+ errorObject?: any
+ }
+ submitVerificationCodeSuccess: (
+ verificationResult: {
+ success: true
+ } | null,
+ payload?: {
+ value: true
+ }
+ ) => {
+ verificationResult: {
+ success: true
+ } | null
+ payload?: {
+ value: true
+ }
+ }
+ tickResendCooldown: () => {
+ value: true
+ }
+}
+
+export type emailChangeVerificationLogicType = MakeLogicType<
+ emailChangeVerificationLogicValues,
+ emailChangeVerificationLogicActions
+>
+
+export const emailChangeVerificationLogic = kea<emailChangeVerificationLogicType>([
+ path(['scenes', 'settings', 'user', 'emailChangeVerificationLogic']),
+ connect(() => ({
+ values: [userLogic, ['user']],
+ actions: [userLogic, ['loadUser']],
+ })),
+ actions({
+ openModal: true,
+ closeModal: true,
+ emailChangeStaged: true,
+ setVerificationCode: (code: string) => ({ code }),
+ setVerificationCodeError: (error: string | null) => ({ error }),
+ submitVerificationCode: true,
+ resendCode: true,
+ resendLimitReached: true,
+ startResendCooldown: (seconds: number) => ({ seconds }),
+ tickResendCooldown: true,
+ }),
+ reducers({
+ modalOpen: [
+ false,
+ {
+ openModal: () => true,
+ closeModal: () => false,
+ },
+ ],
+ verificationCode: [
+ '',
+ {
+ setVerificationCode: (_, { code }) => code,
+ openModal: () => '',
+ },
+ ],
+ verificationCodeError: [
+ null as string | null,
+ {
+ setVerificationCode: () => null,
+ submitVerificationCode: () => null,
+ setVerificationCodeError: (_, { error }) => error,
+ openModal: () => null,
+ },
+ ],
+ resendsUsed: [
+ 0,
+ {
+ emailChangeStaged: () => 0,
+ resendCodeSuccess: (state, { resendResult }) => (resendResult ? state + 1 : state),
+ // A throttled response means the backend budget is spent, whatever this
+ // session counted.
+ resendLimitReached: () => MAX_RESENDS,
+ },
+ ],
+ resendCooldown: [
+ 0,
+ {
+ startResendCooldown: (_, { seconds }) => seconds,
+ tickResendCooldown: (state) => Math.max(0, state - 1),
+ },
+ ],
+ }),
+ loaders(({ actions, values }) => ({
+ verificationResult: [
+ null as { success: boolean } | null,
+ {
+ submitVerificationCode: async () => {
+ const uuid = values.user?.uuid
+ const code = normalizeVerificationCode(values.verificationCode)
+ if (!uuid) {
+ return null
+ }
+ if (!isValidVerificationCode(code)) {
+ actions.setVerificationCodeError('Enter the 6-digit code from your email.')
+ return null
+ }
+ try {
+ await api.create(`api/users/verify_email/`, { uuid, code })
+ actions.closeModal()
+ lemonToast.success('Email address verified.')
+ actions.loadUser()
+ return { success: true }
+ } catch (e: any) {
+ actions.setVerificationCodeError(verificationCodeErrorMessage(e))
+ return null
+ }
+ },
+ },
+ ],
+ resendResult: [
+ null as boolean | null,
+ {
+ resendCode: async () => {
+ const uuid = values.user?.uuid
+ if (!uuid || values.resendCooldown > 0 || values.resendsUsed >= MAX_RESENDS) {
+ return null
+ }
+ try {
+ await api.create(`api/users/request_email_verification/`, { uuid })
+ lemonToast.success('We sent a new code to the address pending verification.')
+ return true
+ } catch (e: any) {
+ if (e.code === 'throttled') {
+ actions.resendLimitReached()
+ lemonToast.error('You have requested a new code too many times. Please try again later.')
+ } else {
+ lemonToast.error('Requesting a new code failed. Please try again later.')
+ }
+ return false
+ }
+ },
+ },
+ ],
+ })),
+ listeners(({ actions, values, cache }) => ({
+ emailChangeStaged: () => {
+ actions.openModal()
+ actions.startResendCooldown(RESEND_COOLDOWNS_SECONDS[0])
+ },
+ resendCodeSuccess: ({ resendResult }) => {
+ if (resendResult && values.resendsUsed < MAX_RESENDS) {
+ actions.startResendCooldown(RESEND_COOLDOWNS_SECONDS[values.resendsUsed] ?? 60)
+ }
+ },
+ startResendCooldown: () => {
+ cache.disposables.add(
+ () => {
+ const intervalId = setInterval(() => actions.tickResendCooldown(), 1000)
+ return () => clearInterval(intervalId)
+ },
+ 'resendCooldown',
+ // Keep counting while the user reads their inbox in another tab.
+ { pauseOnPageHidden: false }
+ )
+ },
+ tickResendCooldown: () => {
+ if (values.resendCooldown <= 0) {
+ cache.disposables.dispose('resendCooldown')
+ }
+ },
+ })),
+ subscriptions(({ actions }) => ({
+ // The form submit action fires before the API response lands. Watch the user object
+ // instead: a new pending_email means a change was staged and the code was sent.
+ user: (user: UserType | null, oldUser: UserType | null) => {
+ if (user?.pending_email && oldUser && oldUser.pending_email !== user.pending_email) {
+ actions.emailChangeStaged()
+ }
+ },
+ })),
+])
diff --git a/posthog/api/authentication.py b/posthog/api/authentication.py
index c6858516ccdc..5500b7dce86a 100644
--- a/posthog/api/authentication.py
+++ b/posthog/api/authentication.py
@@ -3,7 +3,6 @@ import json
import time
import random
import datetime
-import unicodedata
from typing import Any, TypedDict, cast
from urllib.parse import urlencode
from uuid import uuid4
@@ -64,6 +63,7 @@ from posthog.helpers.two_factor_session import (
clear_two_factor_session_flags,
code_based_verifier,
has_passkeys,
+ normalize_verification_code,
set_two_factor_verified_in_session,
)
from posthog.helpers.user_devices import has_valid_known_device_cookie
@@ -187,6 +187,19 @@ class CodeBasedVerificationRequired(APIException):
super().__init__(detail=detail, code=self.default_code)
+class EmailVerificationPending(APIException):
+ """Login blocked because the signup email is unverified and a fresh code was just sent.
+ Like CodeBasedVerificationRequired, `detail` carries data (the user uuid) so the frontend
+ can route to the code entry page at /verify_email/<uuid>."""
+
+ status_code = 401
+ default_detail = "Email verification is required."
+ default_code = "verify_email_pending"
+
+ def __init__(self, user_uuid: str):
+ super().__init__(detail=user_uuid, code=self.default_code)
+
+
def is_email_verified_for_login(user: User, next_url: str | None = None) -> bool:
"""
Send a verification email when the login policy requires it.
@@ -326,6 +339,10 @@ class LoginSerializer(serializers.Serializer):
raise serializers.ValidationError("Invalid email or password.", code="invalid_credentials")
if not is_email_verified_for_login(user, next_url):
+ if EmailVerifier.use_verification_code(user):
+ # A fresh code was just emailed; hand the frontend the uuid so it can route to
+ # the code entry page. The legacy link flow keeps the plain error below.
+ raise EmailVerificationPending(str(user.uuid))
raise serializers.ValidationError(
"Your account is awaiting verification. Please check your email for a verification link.",
code="not_verified",
@@ -976,12 +993,6 @@ class TwoFactorPasskeyViewSet(NonCreatingViewSetMixin, viewsets.GenericViewSet):
return Response(json.loads(options_to_json(options)))
-# Characters an email client or manual entry can inject around/within the code without the
-# user seeing them: whitespace, the zero-width family, word joiner, BOM, soft hyphen, and the
-# hyphen someone types when grouping the code as "123-456".
-_CODE_NOISE_RE = re.compile(r"[\s\u200b-\u200d\u2060\ufeff\u00ad-]")
-
-
class CodeBasedVerificationSerializer(serializers.Serializer):
code = serializers.CharField(
help_text="The 6-digit verification code emailed to the user. Whitespace, invisible characters, "
@@ -994,10 +1005,9 @@ class CodeBasedVerificationSerializer(serializers.Serializer):
)
def validate_code(self, value: str) -> str:
- # Fold compatibility forms (fullwidth digits become ASCII) then drop the noise an email client
- # or manual grouping injects. Require exactly 6 digits so malformed input is rejected outright
+ # Require exactly 6 digits after normalization so malformed input is rejected outright
# rather than mining digits out of arbitrary text.
- cleaned = _CODE_NOISE_RE.sub("", unicodedata.normalize("NFKC", value or ""))
+ cleaned = normalize_verification_code(value)
if not re.fullmatch(r"\d{6}", cleaned):
raise serializers.ValidationError("Enter the 6-digit code from your email.")
return cleaned
diff --git a/posthog/api/email_verification.py b/posthog/api/email_verification.py
index 7543fb27638f..41c5c1578af3 100644
--- a/posthog/api/email_verification.py
+++ b/posthog/api/email_verification.py
@@ -1,15 +1,30 @@
+import time
+
from django.contrib.auth.models import AbstractBaseUser
from django.contrib.auth.tokens import PasswordResetTokenGenerator
+import structlog
from rest_framework import exceptions
from posthog.exceptions_capture import capture_exception
+from posthog.helpers.two_factor_session import (
+ CODE_MAX_ATTEMPTS,
+ CODE_TTL_SECONDS,
+ code_based_verification_token_generator,
+ is_code_based_verification_globally_disabled,
+)
from posthog.models.user import User
from posthog.ph_client import feature_enabled_or_false
-from posthog.tasks.email import send_email_verification
+from posthog.redis import get_client
+from posthog.tasks.email import send_email_verification, send_email_verification_code
+
+logger = structlog.get_logger(__name__)
VERIFICATION_DISABLED_FLAG = "email-verification-disabled"
+EMAIL_CODE_STATE_REDIS_KEY_PREFIX = "email_verification_code_state"
+EMAIL_CODE_ATTEMPTS_REDIS_KEY_PREFIX = "email_verification_code_attempts"
+
def is_email_verification_disabled(user: User) -> bool:
# using disabled here so that the default state (if no flag exists) is that verification defaults to ON.
@@ -34,9 +49,124 @@ class EmailVerificationTokenGenerator(PasswordResetTokenGenerator):
email_verification_token_generator = EmailVerificationTokenGenerator()
+class EmailVerificationCodeVerifier:
+ """Issues and checks the 6-digit code for signup and email-change verification.
+
+ Unlike the login code flow, pending state (issuance time, target address, attempt counter)
+ lives in Redis keyed by user id, not in the session. Verification must work after the user
+ closes the tab or opens the app in a different browser. The code itself is derived by
+ `code_based_verification_token_generator` and never stored.
+
+ The stored target address does for codes what the `pending_email` hash input does for link
+ tokens: a code verifies only the address it was issued for. One Redis slot per user means
+ a new code always invalidates the previous one.
+
+ The attempt budget is separate from the code. It is not reset by issuing a new code, because
+ the resend endpoint is public: a reset there would let a caller alternate resends and guesses
+ to brute-force the code. Exceeding the budget refuses checks until it expires, but keeps the
+ code alive, so a stranger who knows the user's uuid cannot destroy a live verification.
+ """
+
+ @staticmethod
+ def _state_key(user_id: int) -> str:
+ return f"{EMAIL_CODE_STATE_REDIS_KEY_PREFIX}:{user_id}"
+
+ @staticmethod
+ def _attempts_key(user_id: int) -> str:
+ return f"{EMAIL_CODE_ATTEMPTS_REDIS_KEY_PREFIX}:{user_id}"
+
+ def send_code(self, user: User, target_email: str | None = None) -> bool:
+ """Issue a fresh code and email it to the address it authorizes.
+
+ Returns False when the code was not issued or sent, so the caller can send the
+ link email instead."""
+ try:
+ # Signup verification always proves the account address. Only a verified user's
+ # email change targets the staged address; an unverified user's staged change must
+ # not let a code sent to the unverified new address verify the account.
+ target: str | None = target_email
+ if target is None and user.is_email_verified:
+ target = user.pending_email
+ issued_at = int(time.time())
+ code = code_based_verification_token_generator.make_code(user, issued_at)
+ # Write the state before the send, so a delivered code can always verify.
+ get_client().set(self._state_key(user.pk), f"{issued_at}:{target or ''}", ex=CODE_TTL_SECONDS)
+ send_email_verification_code(user.pk, code, target)
+ return True
+ except Exception as e:
+ logger.exception("Email verification code send failed", user_id=user.pk, error=str(e))
+ capture_exception(Exception(f"Email verification code send failed: {e}"))
+ return False
+
+ def _get_state(self, user: User) -> tuple[int, str] | None:
+ """Return (issued_at, target_email) for the pending code. target_email is '' for signup."""
+ try:
+ raw = get_client().get(self._state_key(user.pk))
+ if not raw:
+ return None
+ text = raw.decode() if isinstance(raw, bytes) else raw
+ issued_at_raw, _, target = text.partition(":")
+ return int(issued_at_raw), target
+ except Exception:
+ logger.exception("Failed to read email verification code state", user_id=user.pk)
+ return None
+
+ def reserve_attempt(self, user: User) -> int:
+ """Count one verification attempt atomically.
+
+ Returns the running total, including this attempt. Returns 0 on Redis failure,
+ failing open - the endpoint throttle is the backstop."""
+ try:
+ client = get_client()
+ count = int(client.incr(self._attempts_key(user.pk)))
+ if count == 1:
+ # Only the first attempt starts the window, so further guesses cannot extend a lockout.
+ client.expire(self._attempts_key(user.pk), CODE_TTL_SECONDS)
+ return count
+ except Exception:
+ logger.exception("Failed to reserve email verification code attempt", user_id=user.pk)
+ return 0
+
+ def check_code(self, user: User, code: str) -> bool:
+ state = self._get_state(user)
+ if not state:
+ return False
+ issued_at, target = state
+ # A code verifies only the address it was issued for. Signup codes store '' as the target.
+ expected_target = (user.pending_email or "") if user.is_email_verified else ""
+ if target != expected_target:
+ return False
+ return code_based_verification_token_generator.check_code(user, code, issued_at)
+
+ def invalidate(self, user: User) -> None:
+ try:
+ get_client().delete(self._state_key(user.pk), self._attempts_key(user.pk))
+ except Exception:
+ logger.exception("Failed to invalidate email verification code", user_id=user.pk)
+
+ def attempts_exceeded(self, attempts: int) -> bool:
+ return attempts > CODE_MAX_ATTEMPTS
+
+ def _clear_attempts_for_test(self, user: User) -> None:
+ get_client().delete(self._attempts_key(user.pk))
+
+
+email_verification_code_verifier = EmailVerificationCodeVerifier()
+
+
class EmailVerifier:
+ @staticmethod
+ def use_verification_code(user: User) -> bool:
+ """Signup and email-change verification use an emailed code. The code-based-verification
+ kill-switch reverts both to the token-link flow."""
+ return (not user.is_email_verified or bool(user.pending_email)) and (
+ not is_code_based_verification_globally_disabled()
+ )
+
@staticmethod
def create_token_and_send_email_verification(user: User, next_url: str | None = None) -> None:
+ if EmailVerifier.use_verification_code(user) and email_verification_code_verifier.send_code(user):
+ return
token = email_verification_token_generator.make_token(user)
EmailVerifier.send_verification_email(user, token, next_url=next_url)
diff --git a/posthog/api/test/test_authentication.py b/posthog/api/test/test_authentication.py
index d98dd14adec9..ea24c8fc3fdc 100644
--- a/posthog/api/test/test_authentication.py
+++ b/posthog/api/test/test_authentication.py
@@ -547,6 +547,25 @@ class TestLoginAPI(APIBaseTest):
# Assert the email was sent.
mock_send_email_verification.assert_called_once_with(self.user, None)
+ @pytest.mark.disable_mock_email_code_verification
+ @patch("posthog.api.authentication.is_email_available", return_value=True)
+ @patch("posthog.api.email_verification.send_email_verification_code")
+ def test_email_unverified_login_returns_verify_email_pending_with_uuid(
+ self, mock_send_code, mock_is_email_available
+ ):
+ # The signup code flow blocks login with the user uuid in `detail`, so the frontend can
+ # route to /verify_email/<uuid> where the code entry form lives.
+ self.user.is_email_verified = False
+ self.user.save()
+ response = self.client.post("/api/login", {"email": self.CONFIG_EMAIL, "password": self.CONFIG_PASSWORD})
+ self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)
+ self.assertEqual(response.json()["code"], "verify_email_pending")
+ self.assertEqual(response.json()["detail"], str(self.user.uuid))
+ mock_send_code.assert_called_once()
+
+ response = self.client.get("/api/users/@me/")
+ self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)
+
@parameterized.expand(
[
# A relative `next` (e.g. an /oauth/authorize continuation) must be forwarded so the
diff --git a/posthog/api/test/test_user.py b/posthog/api/test/test_user.py
index a215e32187bf..4a9e024260d1 100644
--- a/posthog/api/test/test_user.py
+++ b/posthog/api/test/test_user.py
@@ -25,7 +25,7 @@ from parameterized import parameterized
from rest_framework import status
from social_django.models import UserSocialAuth
-from posthog.api.email_verification import email_verification_token_generator
+from posthog.api.email_verification import email_verification_code_verifier, email_verification_token_generator
from posthog.api.oauth.toolbar_service import ToolbarOAuthState, build_toolbar_oauth_state, new_state_nonce
from posthog.api.user import UserSerializer
from posthog.constants import AvailableFeature
@@ -2978,22 +2978,28 @@ class TestEmailVerificationAPI(APIBaseTest):
},
)
- def test_can_only_validate_email_token_one_time(self):
+ def test_reused_token_reports_already_verified_without_a_session(self):
token = email_verification_token_generator.make_token(self.user)
response = self.client.post(f"/api/users/verify_email/", {"uuid": self.user.uuid, "token": token})
self.assertEqual(response.status_code, status.HTTP_200_OK)
+ # A second use (double click, or the link prefetched by an email scanner) reports success
+ # for the already-verified address, but must not hand out a session: the spent token no
+ # longer proves anything.
+ self.client.logout()
response = self.client.post(f"/api/users/verify_email/", {"uuid": self.user.uuid, "token": token})
- self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
- self.assertEqual(
- response.json(),
- {
- "type": "validation_error",
- "code": "invalid_token",
- "detail": "This verification token is invalid or has expired.",
- "attr": "token",
- },
- )
+ self.assertEqual(response.status_code, status.HTTP_200_OK)
+ self.assertEqual(response.json(), {"success": True, "requires_login": True})
+ assert self.client.session.get("_auth_user_id") is None
+
+ def test_already_verified_user_gets_success_even_with_a_bad_token(self):
+ self.user.is_email_verified = True
+ self.user.save()
+
+ response = self.client.post(f"/api/users/verify_email/", {"uuid": self.user.uuid, "token": "garbage"})
+ self.assertEqual(response.status_code, status.HTTP_200_OK)
+ self.assertEqual(response.json(), {"success": True, "requires_login": True})
+ assert self.client.session.get("_auth_user_id") is None
def test_email_verification_logs_in_user(self):
token = email_verification_token_generator.make_token(self.user)
@@ -3116,6 +3122,227 @@ class TestEmailVerificationAPI(APIBaseTest):
self.assertEqual(mail.outbox[0].to, ["[email protected]"])
[email protected]_mock_email_code_verification
+class TestEmailVerificationCodeAPI(APIBaseTest):
+ CONFIG_AUTO_LOGIN = False
+
+ def setUp(self):
+ cache.clear()
+ super().setUp()
+ set_instance_setting("EMAIL_HOST", "localhost")
+ email_verification_code_verifier.invalidate(self.user)
+
+ def _request_code(self) -> str:
+ """Trigger a resend and capture the emailed code at the send boundary."""
+ with patch("posthog.api.email_verification.send_email_verification_code") as mock_send:
+ with self.settings(CELERY_TASK_ALWAYS_EAGER=True):
+ response = self.client.post("/api/users/request_email_verification/", {"uuid": self.user.uuid})
+ assert response.status_code == status.HTTP_200_OK
+ mock_send.assert_called_once()
+ return mock_send.call_args[0][1]
+
+ def test_code_verifies_email_and_logs_in(self):
+ code = self._request_code()
+
+ response = self.client.post("/api/users/verify_email/", {"uuid": self.user.uuid, "code": code})
+ self.assertEqual(response.status_code, status.HTTP_200_OK)
+
+ self.user.refresh_from_db()
+ assert self.user.is_email_verified
+ assert self.client.session.get("_auth_user_id") == str(self.user.id)
+
+ def test_code_with_pasted_noise_verifies(self):
+ code = self._request_code()
+ noisy = f" {code[:3]}-{code[3:]} "
+
+ response = self.client.post("/api/users/verify_email/", {"uuid": self.user.uuid, "code": noisy})
+ self.assertEqual(response.status_code, status.HTTP_200_OK)
+ self.user.refresh_from_db()
+ assert self.user.is_email_verified
+
+ def test_wrong_code_is_rejected_but_correct_code_still_works_within_budget(self):
+ code = self._request_code()
+ wrong = "000000" if code != "000000" else "000001"
+
+ for _ in range(4):
+ response = self.client.post("/api/users/verify_email/", {"uuid": self.user.uuid, "code": wrong})
+ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
+ self.assertEqual(response.json()["code"], "invalid_code")
+
+ response = self.client.post("/api/users/verify_email/", {"uuid": self.user.uuid, "code": code})
+ self.assertEqual(response.status_code, status.HTTP_200_OK)
+
+ def test_attempt_cap_refuses_checks_but_keeps_the_code_alive(self):
+ code = self._request_code()
+ wrong = "000000" if code != "000000" else "000001"
+
+ for _ in range(5):
+ self.client.post("/api/users/verify_email/", {"uuid": self.user.uuid, "code": wrong})
+
+ # A stranger who knows the uuid can exhaust the budget, but must not be able to destroy
+ # the real user's code: once the budget expires, the same code still verifies.
+ response = self.client.post("/api/users/verify_email/", {"uuid": self.user.uuid, "code": code})
+ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
+ self.assertEqual(response.json()["code"], "too_many_attempts")
+
+ email_verification_code_verifier._clear_attempts_for_test(self.user)
+ cache.clear()
+ response = self.client.post("/api/users/verify_email/", {"uuid": self.user.uuid, "code": code})
+ self.assertEqual(response.status_code, status.HTTP_200_OK)
+
+ def test_resend_does_not_restore_guesses(self):
+ code = self._request_code()
+ wrong = "000000" if code != "000000" else "000001"
+ for _ in range(4):
+ self.client.post("/api/users/verify_email/", {"uuid": self.user.uuid, "code": wrong})
+
+ # A public resend must not hand the guesser a fresh budget.
+ new_code = self._request_code()
+ response = self.client.post("/api/users/verify_email/", {"uuid": self.user.uuid, "code": wrong})
+ self.assertEqual(response.json()["code"], "invalid_code")
+ response = self.client.post("/api/users/verify_email/", {"uuid": self.user.uuid, "code": new_code})
+ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
+ self.assertEqual(response.json()["code"], "too_many_attempts")
+
+ @parameterized.expand([("letters", "aaaaaa"), ("short", "12345"), ("list", ["1"]), ("object", {"a": 1})])
+ def test_malformed_code_is_rejected_without_spending_an_attempt(self, _name, bad_code):
+ code = self._request_code()
+
+ for _ in range(6):
+ response = self.client.post(
+ "/api/users/verify_email/", {"uuid": str(self.user.uuid), "code": bad_code}, format="json"
+ )
+ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
+
+ # Six junk submissions later, the budget is untouched and the real code still works.
+ cache.clear()
+ response = self.client.post("/api/users/verify_email/", {"uuid": self.user.uuid, "code": code})
+ self.assertEqual(response.status_code, status.HTTP_200_OK)
+
+ def test_guesses_are_capped_per_source_across_target_accounts(self):
+ # Rotating target uuids must not multiply the guess budget: the per-source cap holds.
+ self._request_code()
+ for _ in range(30):
+ self.client.post("/api/users/verify_email/", {"uuid": uuid.uuid4(), "code": "000000"})
+
+ response = self.client.post("/api/users/verify_email/", {"uuid": self.user.uuid, "code": "000000"})
+ self.assertEqual(response.status_code, status.HTTP_429_TOO_MANY_REQUESTS)
+
+ def test_numeric_json_code_is_a_normal_guess(self):
+ # A client that sends the six digits as a JSON number must get a 400, not a 500, and the
+ # coerced string counts as an ordinary attempt.
+ code = self._request_code()
+ if code.startswith("0"):
+ # A JSON number cannot carry a leading zero; the real client sends a string in that case.
+ self.skipTest("code has a leading zero")
+ response = self.client.post(
+ "/api/users/verify_email/", {"uuid": str(self.user.uuid), "code": int(code)}, format="json"
+ )
+ self.assertEqual(response.status_code, status.HTTP_200_OK)
+
+ def test_expired_code_is_rejected(self):
+ code = self._request_code()
+
+ with freeze_time(timezone.now() + datetime.timedelta(minutes=31)):
+ response = self.client.post("/api/users/verify_email/", {"uuid": self.user.uuid, "code": code})
+ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
+ self.assertEqual(response.json()["code"], "invalid_code")
+
+ def test_code_is_single_use(self):
+ code = self._request_code()
+
+ assert (
+ self.client.post("/api/users/verify_email/", {"uuid": self.user.uuid, "code": code}).status_code
+ == status.HTTP_200_OK
+ )
+
+ # The user is now verified, so a replay reports already-verified instead of consuming anything.
+ self.client.logout()
+ response = self.client.post("/api/users/verify_email/", {"uuid": self.user.uuid, "code": code})
+ self.assertEqual(response.status_code, status.HTTP_200_OK)
+ self.assertEqual(response.json(), {"success": True, "requires_login": True})
+ assert self.client.session.get("_auth_user_id") is None
+
+ def test_code_send_failure_falls_back_to_link_email(self):
+ with patch(
+ "posthog.api.email_verification.send_email_verification_code",
+ side_effect=Exception("template missing"),
+ ):
+ with self.settings(CELERY_TASK_ALWAYS_EAGER=True, SITE_URL="https://my.posthog.net"):
+ response = self.client.post("/api/users/request_email_verification/", {"uuid": self.user.uuid})
+ self.assertEqual(response.status_code, status.HTTP_200_OK)
+ assert len(mail.outbox) == 1
+ html_message = mail.outbox[0].alternatives[0][0] # type: ignore
+ assert f"https://my.posthog.net/verify_email/{self.user.uuid}/" in html_message
+
+ def test_email_change_code_goes_to_the_pending_address_and_completes_the_swap(self):
+ self.user.is_email_verified = True
+ self.user.pending_email = "[email protected]"
+ self.user.save()
+
+ with patch("posthog.api.email_verification.send_email_verification_code") as mock_send:
+ with self.settings(CELERY_TASK_ALWAYS_EAGER=True):
+ response = self.client.post("/api/users/request_email_verification/", {"uuid": self.user.uuid})
+ self.assertEqual(response.status_code, status.HTTP_200_OK)
+ code = mock_send.call_args[0][1]
+ assert mock_send.call_args[0][2] == "[email protected]"
+
+ response = self.client.post("/api/users/verify_email/", {"uuid": self.user.uuid, "code": code})
+ self.assertEqual(response.status_code, status.HTTP_200_OK)
+ self.user.refresh_from_db()
+ assert self.user.email == "[email protected]"
+ assert self.user.pending_email is None
+
+ def test_signup_code_does_not_authorize_an_email_change(self):
+ code = self._request_code()
+ self.user.is_email_verified = True
+ self.user.pending_email = "[email protected]"
+ self.user.save()
+
+ response = self.client.post("/api/users/verify_email/", {"uuid": self.user.uuid, "code": code})
+ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
+ self.assertEqual(response.json()["code"], "invalid_code")
+ self.user.refresh_from_db()
+ assert self.user.pending_email == "[email protected]"
+
+ def test_unverified_user_with_staged_change_verifies_only_the_account_address(self):
+ # A signup code for an unverified user must go to the account address and prove that one,
+ # even if a change to another address is staged: the staged address is itself unproven.
+ self.user.pending_email = "[email protected]"
+ self.user.save()
+
+ with patch("posthog.api.email_verification.send_email_verification_code") as mock_send:
+ with self.settings(CELERY_TASK_ALWAYS_EAGER=True):
+ self.client.post("/api/users/request_email_verification/", {"uuid": self.user.uuid})
+ assert mock_send.call_args[0][2] is None
+ code = mock_send.call_args[0][1]
+
+ response = self.client.post("/api/users/verify_email/", {"uuid": self.user.uuid, "code": code})
+ self.assertEqual(response.status_code, status.HTTP_200_OK)
+ self.user.refresh_from_db()
+ assert self.user.is_email_verified
+ assert self.user.email != "[email protected]"
+
+ def test_code_dies_when_a_different_pending_address_is_staged(self):
+ self.user.is_email_verified = True
+ self.user.pending_email = "[email protected]"
+ self.user.save()
+ with patch("posthog.api.email_verification.send_email_verification_code") as mock_send:
+ with self.settings(CELERY_TASK_ALWAYS_EAGER=True):
+ self.client.post("/api/users/request_email_verification/", {"uuid": self.user.uuid})
+ code_for_first = mock_send.call_args[0][1]
+
+ self.user.pending_email = "[email protected]"
+ self.user.save()
+
+ response = self.client.post("/api/users/verify_email/", {"uuid": self.user.uuid, "code": code_for_first})
+ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
+ self.assertEqual(response.json()["code"], "invalid_code")
+ self.user.refresh_from_db()
+ assert self.user.email != "[email protected]"
+ assert self.user.pending_email == "[email protected]"
+
+
class TestUserTwoFactor(APIBaseTest):
def setUp(self):
super().setUp()
diff --git a/posthog/api/user.py b/posthog/api/user.py
index 483625cc0397..cbb6606a7250 100644
--- a/posthog/api/user.py
+++ b/posthog/api/user.py
@@ -46,7 +46,11 @@ from two_factor.utils import default_device
from posthog.schema import UserUIConfiguration
-from posthog.api.email_verification import EmailVerifier, email_verification_token_generator
+from posthog.api.email_verification import (
+ EmailVerifier,
+ email_verification_code_verifier,
+ email_verification_token_generator,
+)
from posthog.api.oauth.toolbar_service import (
ToolbarOAuthError,
ToolbarOAuthState,
@@ -92,7 +96,11 @@ from posthog.helpers.email_utils import (
)
from posthog.helpers.impersonation import is_impersonated
from posthog.helpers.session_cache import SessionCache
-from posthog.helpers.two_factor_session import has_passkeys, set_two_factor_verified_in_session
+from posthog.helpers.two_factor_session import (
+ has_passkeys,
+ normalize_verification_code,
+ set_two_factor_verified_in_session,
+)
from posthog.helpers.verified_domain_enforcement import VERIFIED_DOMAIN_REQUIRED_ERROR, resolve_login_organization
from posthog.middleware import (
IMPERSONATION_REASON_SESSION_KEY,
@@ -119,6 +127,8 @@ from posthog.rate_limit import (
ToolbarOAuthRefreshThrottle,
UserAuthenticationThrottle,
UserEmailVerificationThrottle,
+ UserVerifyEmailThrottle,
+ VerifyEmailIPThrottle,
)
from posthog.session.activity import (
list_user_sessions,
@@ -188,6 +198,40 @@ class PendingInviteSerializer(serializers.Serializer):
created_at = serializers.DateTimeField()
+class VerifyEmailRequestSerializer(serializers.Serializer):
+ """Request body for POST /api/users/verify_email/. Exactly one of token or code is required."""
+
+ # A string, not a UUIDField: the E2E test sentinel is not a UUID, and an unknown uuid must
+ # answer the same way as a wrong credential rather than as a shape error.
+ uuid = serializers.CharField(help_text="UUID of the user whose email is being verified.")
+ token = serializers.CharField(
+ required=False,
+ allow_blank=True,
+ help_text="Verification token from the emailed link. Required unless a code is provided.",
+ )
+ code = serializers.CharField(
+ required=False,
+ allow_blank=True,
+ help_text="The 6-digit verification code emailed at signup. Whitespace, invisible characters, "
+ "and grouping hyphens are removed and compatibility digits are folded to ASCII before checking.",
+ )
+
+ def validate_code(self, value: str) -> str:
+ if not value:
+ return value
+ # Same rule as the login code: exactly 6 digits after normalization, so malformed input is
+ # rejected here and never reaches the attempt budget.
+ cleaned = normalize_verification_code(value)
+ if not re.fullmatch(r"\d{6}", cleaned):
+ raise serializers.ValidationError("Enter the 6-digit code from your email.")
+ return cleaned
+
+ def validate(self, attrs: dict[str, Any]) -> dict[str, Any]:
+ if not attrs.get("token") and not attrs.get("code"):
+ raise serializers.ValidationError({"token": ["This field is required."]}, code="required")
+ return attrs
+
+
class OnboardingSkipRequestSerializer(serializers.Serializer):
"""Request body for POST /api/users/{id}/onboarding/skip/.
@@ -802,8 +846,13 @@ class UserSerializer(serializers.ModelSerializer):
token = email_verification_token_generator.make_token(instance)
# Send after the transaction commits (never inside the atomic block), pinning the
# recipient to the captured address so a later pending_email change can't redirect
- # this token's verification email.
- EmailVerifier.send_verification_email(instance, token, target_email=new_email)
+ # this verification email. The code path stores that address as the code's target,
+ # so a stale code stops verifying once a different address is staged.
+ if not (
+ EmailVerifier.use_verification_code(instance)
+ and email_verification_code_verifier.send_code(instance, target_email=new_email)
+ ):
+ EmailVerifier.send_verification_email(instance, token, target_email=new_email)
if validated_data.get("notification_settings"):
validated_data["partial_notification_settings"] = validated_data.pop("notification_settings")
@@ -1136,13 +1185,19 @@ class UserViewSet(
revoked_count = revoke_other_sessions(user, request.session.session_key)
return Response({"revoked_count": revoked_count})
- @action(methods=["POST"], detail=False, permission_classes=[AllowAny])
+ @extend_schema(request=VerifyEmailRequestSerializer)
+ @action(
+ methods=["POST"],
+ detail=False,
+ permission_classes=[AllowAny],
+ throttle_classes=[UserVerifyEmailThrottle, VerifyEmailIPThrottle],
+ )
def verify_email(self, request, **kwargs):
- token = request.data["token"] if "token" in request.data else None
- user_uuid = request.data["uuid"]
-
- if not token:
- raise serializers.ValidationError({"token": ["This field is required."]}, code="required")
+ body = VerifyEmailRequestSerializer(data=request.data if isinstance(request.data, dict) else {})
+ body.is_valid(raise_exception=True)
+ token = body.validated_data.get("token") or None
+ code = body.validated_data.get("code") or None
+ user_uuid = body.validated_data["uuid"]
# Special handling for E2E tests
if settings.E2E_TESTING and user_uuid == "e2e_test_user" and token == "e2e_test_token":
@@ -1153,13 +1208,41 @@ class UserViewSet(
except User.DoesNotExist:
user = None
- if not user or not EmailVerifier.check_token(user, token):
+ # A replay of a spent token or code (double click, scanner prefetch) is not a failure:
+ # the address is verified. Do not create a session - no valid credential was presented.
+ if user and user.is_email_verified is True and not user.pending_email:
+ return Response({"success": True, "requires_login": True})
+
+ if code and not token:
+ if not user:
+ raise serializers.ValidationError(
+ {"code": ["This verification code is invalid or has expired."]},
+ code="invalid_code",
+ )
+ attempts = email_verification_code_verifier.reserve_attempt(user)
+ if email_verification_code_verifier.attempts_exceeded(attempts):
+ # Refuse until the budget expires, but keep the code: anyone with the uuid can
+ # reach this endpoint, and deleting the code here would let them block the user.
+ raise serializers.ValidationError(
+ {"code": ["Too many incorrect attempts. Try again later."]},
+ code="too_many_attempts",
+ )
+ if not email_verification_code_verifier.check_code(user, code):
+ raise serializers.ValidationError(
+ {"code": ["This verification code is invalid or has expired."]},
+ code="invalid_code",
+ )
+ email_verification_code_verifier.invalidate(user)
+ elif not user or not token or not EmailVerifier.check_token(user, token):
raise serializers.ValidationError(
{"token": ["This verification token is invalid or has expired."]},
code="invalid_token",
)
- if user.pending_email:
+ # The swap needs a credential issued for the staged address. A token always is (its hash
+ # includes pending_email). A code is only for a verified user; an unverified user's code
+ # proves the account address, so their staged change stays pending.
+ if user.pending_email and (token or user.is_email_verified):
old_email = user.email
with transaction.atomic():
user.email = user.pending_email
@@ -1237,6 +1320,9 @@ class UserViewSet(
instance.pending_email = None
instance.save()
+ # The target binding already rejects the code once pending_email clears. Delete the
+ # state so no dead code or attempt counter waits out its TTL.
+ email_verification_code_verifier.invalidate(instance)
return Response(self.get_serializer(instance=instance).data)
diff --git a/posthog/conftest.py b/posthog/conftest.py
index 7331d29ea88b..53d0627e4b9a 100644
--- a/posthog/conftest.py
+++ b/posthog/conftest.py
@@ -505,6 +505,22 @@ def mock_code_based_verifier(request, mocker):
)
[email protected](autouse=True)
+def mock_email_code_verification(request, mocker):
+ """
+ Keep the pre-existing email-verification tests on the link flow. Codes are the default and
+ would bypass every mock of the link-email sender. Code-flow tests opt out with
+ @pytest.mark.disable_mock_email_code_verification.
+ """
+ if "disable_mock_email_code_verification" in request.keywords:
+ return
+
+ mocker.patch(
+ "posthog.api.email_verification.EmailVerifier.use_verification_code",
+ return_value=False,
+ )
+
+
class _JUnitTimingsPlugin:
"""Capture wall-clock offsets and surface them as JUnit `<testsuite>` properties.
diff --git a/posthog/email.py b/posthog/email.py
index 372d979883bb..1e394c0e885e 100644
--- a/posthog/email.py
+++ b/posthog/email.py
@@ -129,6 +129,7 @@ CUSTOMER_IO_TEMPLATE_ID_MAP = {
"login_notification": "44",
"personal_api_key_exposed": "45",
"code_based_verification": "75",
+ "email_verification_code": "79",
"feature_flags_secure_api_key_exposed": "49",
"project_secret_api_key_exposed": "76",
"oauth_token_exposed": "50",
diff --git a/posthog/helpers/two_factor_session.py b/posthog/helpers/two_factor_session.py
index 05da64f0ff25..2ea335e212cd 100644
--- a/posthog/helpers/two_factor_session.py
+++ b/posthog/helpers/two_factor_session.py
@@ -1,6 +1,8 @@
+import re
import json
import time
import datetime
+import unicodedata
from dataclasses import dataclass
from typing import Optional
@@ -290,6 +292,19 @@ def is_sso_authentication_backend(request: HttpRequest):
CODE_LENGTH = 6
CODE_TTL_SECONDS = 1800 # 30 minutes
CODE_MAX_ATTEMPTS = 5
+
+# Characters an email client or manual entry can inject around/within the code without the
+# user seeing them: whitespace, the zero-width family, word joiner, BOM, soft hyphen, and the
+# hyphen someone types when grouping the code as "123-456".
+CODE_NOISE_RE = re.compile(r"[\s\u200b-\u200d\u2060\ufeff\u00ad-]")
+
+
+def normalize_verification_code(value: str) -> str:
+ """Fold compatibility forms (fullwidth digits become ASCII) then drop the noise an email client
+ or manual grouping injects. Callers still validate the result is exactly CODE_LENGTH digits."""
+ return CODE_NOISE_RE.sub("", unicodedata.normalize("NFKC", value or ""))
+
+
# Failed-attempt budget for a pending login is tracked in Redis so the cap is enforced atomically
# (INCR) rather than via a raceable session read-modify-write, which parallel guesses could sidestep.
CODE_ATTEMPTS_REDIS_KEY_PREFIX = "code_based_verification_attempts"
diff --git a/posthog/rate_limit.py b/posthog/rate_limit.py
index 7e1ab2f1e847..916810b924dd 100644
--- a/posthog/rate_limit.py
+++ b/posthog/rate_limit.py
@@ -1,6 +1,7 @@
import re
import json
import time
+import uuid
import hashlib
from contextlib import suppress
from datetime import timedelta
@@ -1054,6 +1055,38 @@ class UserEmailVerificationThrottle(UserOrEmailRateThrottle):
rate = "6/day"
+class VerifyEmailIPThrottle(IPThrottle):
+ """Aggregate cap per source, so rotating target uuids cannot multiply the per-account budget."""
+
+ scope = "verify_email_ip"
+ rate = "30/hour"
+
+
+class UserVerifyEmailThrottle(UserOrEmailRateThrottle):
+ scope = "user_verify_email"
+ rate = "6/20minutes"
+
+ def get_cache_key(self, request, view):
+ # Key on the target user's uuid from the request body. The endpoint is unauthenticated,
+ # so the base class would key on IP and let a distributed guesser spread attempts across
+ # addresses. Per-target keying caps the guess budget for one account. The Redis attempt
+ # counter is the hard limit underneath.
+ target_uuid = request.data.get("uuid") if isinstance(request.data, dict) else None
+ if target_uuid:
+ try:
+ # Canonicalize first: uuid.UUID accepts case-insensitive, hyphen-free, brace, and
+ # urn:uuid forms of one value, so hashing the raw text would mint a fresh bucket per
+ # spelling and let a caller sidestep the per-target limit. Fall back to the raw text
+ # (never raise from a cache key) when it isn't a parseable UUID.
+ key_source = str(uuid.UUID(str(target_uuid)))
+ except (ValueError, AttributeError, TypeError):
+ key_source = str(target_uuid)
+ ident = hashlib.sha256(key_source.encode()).hexdigest()
+ return self.cache_format % {"scope": self.scope, "ident": ident}
+
+ return super().get_cache_key(request, view)
+
+
class OnboardingDelegationThrottle(UserRateThrottle):
# Delegation sends PostHog-branded emails to caller-supplied recipients, so we cap it tightly
# to prevent a compromised admin session (or a misbehaving integration) from using the endpoint
diff --git a/posthog/tasks/email.py b/posthog/tasks/email.py
index 46463db66eab..93a0aa94f41a 100644
--- a/posthog/tasks/email.py
+++ b/posthog/tasks/email.py
@@ -555,6 +555,40 @@ def send_email_verification(
)
+@shared_task(**EMAIL_TASK_KWARGS)
+@skip_team_scope_audit
+def send_email_verification_code(user_id: int, code: str, target_email: str | None = None) -> None:
+ """Send the 6-digit email-verification code.
+
+ `target_email` pins the recipient to the address the code authorizes, which is the staged
+ address for email changes. Signup sends leave it None."""
+ user: User = User.objects.get(pk=user_id)
+ message = EmailMessage(
+ use_http=True,
+ campaign_key=f"email-verification-code-{user.uuid}-{timezone.now().timestamp()}",
+ subject="Verify your email address",
+ template_name="email_verification_code",
+ template_context={
+ # Code first so inbox previews and push notifications always show it, even truncated.
+ "preheader": f"{code} is your code.",
+ "code": code,
+ "expiration_minutes": CODE_TTL_SECONDS // 60,
+ # Only email changes set target_email, so it selects the flow. Templates use the
+ # action to pick the footer line.
+ "action": "email_change" if target_email is not None else "signup",
+ "site_url": settings.SITE_URL,
+ },
+ )
+ message.add_user_recipient(user, email_override=target_email)
+ message.send(send_async=False)
+ with ph_scoped_capture() as capture:
+ capture(
+ distinct_id=str(user.distinct_id),
+ event="verification code sent",
+ groups={"organization": str(user.current_organization.id)}, # type: ignore
+ )
+
+
@shared_task(**EMAIL_TASK_KWARGS)
@skip_team_scope_audit
def send_code_based_verification(user_id: int, code: str) -> None:
diff --git a/posthog/tasks/test/__snapshots__/test_task_registration.ambr b/posthog/tasks/test/__snapshots__/test_task_registration.ambr
index 16ca5815d058..69e6880bca0c 100644
--- a/posthog/tasks/test/__snapshots__/test_task_registration.ambr
+++ b/posthog/tasks/test/__snapshots__/test_task_registration.ambr
@@ -39,6 +39,7 @@
'posthog.tasks.email.send_email_sending_suspended',
'posthog.tasks.email.send_email_sending_unsuspended',
'posthog.tasks.email.send_email_verification',
+ 'posthog.tasks.email.send_email_verification_code',
'posthog.tasks.email.send_error_tracking_issue_assigned',
'posthog.tasks.email.send_error_tracking_weekly_digest',
'posthog.tasks.email.send_error_tracking_weekly_digest_for_org',
diff --git a/posthog/tasks/test/test_email.py b/posthog/tasks/test/test_email.py
index cce62d79f166..512f4caeb156 100644
--- a/posthog/tasks/test/test_email.py
+++ b/posthog/tasks/test/test_email.py
@@ -30,6 +30,7 @@ from posthog.tasks.email import (
send_discussions_mentioned,
send_email_change_emails,
send_email_verification,
+ send_email_verification_code,
send_external_data_failure_digest,
send_fatal_plugin_error,
send_hog_function_disabled,
@@ -537,6 +538,21 @@ class TestEmail(APIBaseTest, ClickhouseTestMixin):
assert mocked_email_messages[0].send.call_count == 1
assert mocked_email_messages[0].html_body
+ @patch("posthog.tasks.email.ph_scoped_capture")
+ def test_send_email_verification_code(self, mock_scoped_capture: MagicMock, MockEmailMessage: MagicMock) -> None:
+ mocked_email_messages = mock_email_messages(MockEmailMessage)
+ org, user = create_org_team_and_user("2022-01-02 00:00:00", "[email protected]")
+ send_email_verification_code(user.id, "123456")
+
+ mock_scoped_capture.return_value.__enter__.return_value.assert_called_once_with(
+ event="verification code sent",
+ distinct_id=user.distinct_id,
+ groups={"organization": str(user.current_organization_id)},
+ )
+ assert len(mocked_email_messages) == 1
+ assert mocked_email_messages[0].send.call_count == 1
+ assert mocked_email_messages[0].html_body
+
def test_send_fatal_plugin_error(self, MockEmailMessage: MagicMock) -> None:
mocked_email_messages = mock_email_messages(MockEmailMessage)
org, user = create_org_team_and_user("2022-01-02 00:00:00", "[email protected]")
diff --git a/posthog/templates/email/email_verification_code.html b/posthog/templates/email/email_verification_code.html
new file mode 100644
index 000000000000..f3ed50606091
--- /dev/null
+++ b/posthog/templates/email/email_verification_code.html
@@ -0,0 +1,15 @@
+{% extends "email/base.html" %} {% load posthog_assets %} {% load posthog_filters %}{% block section %}
+<p>Enter this code to verify your email address:</p>
+
+<div class="mb mt text-center">
+ <p style="font-size: 32px; font-weight: 700; letter-spacing: 8px; margin: 0;">{{code}}</p>
+</div>
+
+<p>This code expires in {{expiration_minutes}} minutes.</p>
+
+<hr />
+
+<p class="muted">
+ If you didn't {% if action == "email_change" %}request to change your email{% else %}create a PostHog account{% endif %}, you can ignore this email.
+</p>
+{% endblock %} {% block preheader %}{{preheader}}{% endblock %}{% block heading %}Verify your email address.{% endblock %}
diff --git a/posthog/test/test_rate_limit.py b/posthog/test/test_rate_limit.py
index 02446eab83a4..0c9080b05660 100644
--- a/posthog/test/test_rate_limit.py
+++ b/posthog/test/test_rate_limit.py
@@ -860,6 +860,39 @@ class TestPersonalOrProjectSecretApiKeyRateThrottle(APIBaseTest):
self.assertTrue(_PSAKThrottleForTest().get_cache_key(self._psak_request(key_id=42), Mock()).endswith("psak:42"))
+class TestUserVerifyEmailThrottle(SimpleTestCase):
+ CANONICAL_UUID = "12345678-1234-5678-1234-567812345678"
+
+ def _request(self, uuid_value):
+ return Mock(data={"uuid": uuid_value}, user=None)
+
+ @parameterized.expand(
+ [
+ ("uppercase", "12345678-1234-5678-1234-567812345678".upper()),
+ ("hyphen_free", "12345678123456781234567812345678"),
+ ("brace_wrapped", "{12345678-1234-5678-1234-567812345678}"),
+ ("urn_prefixed", "urn:uuid:12345678-1234-5678-1234-567812345678"),
+ ]
+ )
+ def test_alternate_uuid_spellings_share_one_bucket(self, _name, variant):
+ throttle = rate_limit.UserVerifyEmailThrottle()
+ self.assertEqual(
+ throttle.get_cache_key(self._request(self.CANONICAL_UUID), Mock()),
+ throttle.get_cache_key(self._request(variant), Mock()),
+ )
+
+ def test_distinct_uuids_use_distinct_buckets(self):
+ throttle = rate_limit.UserVerifyEmailThrottle()
+ self.assertNotEqual(
+ throttle.get_cache_key(self._request(self.CANONICAL_UUID), Mock()),
+ throttle.get_cache_key(self._request("87654321-4321-8765-4321-876543218765"), Mock()),
+ )
+
+ def test_unparseable_uuid_falls_back_without_raising(self):
+ throttle = rate_limit.UserVerifyEmailThrottle()
+ self.assertIsNotNone(throttle.get_cache_key(self._request("not-a-uuid"), Mock()))
+
+
class TestAIObservabilitySummarizationRateThrottle(SimpleTestCase):
def setUp(self) -> None:
cache.clear()
diff --git a/pytest.ini b/pytest.ini
index aa49b53e045a..6807b49d9a84 100644
--- a/pytest.ini
+++ b/pytest.ini
@@ -28,6 +28,7 @@ markers =
requires_secrets: test needs internal secrets or infra and is skipped on external PRs
quarantine: applied automatically to tests quarantined via .test_quarantine.json (hogli test:quarantine)
persons_db_direct: test exercises the persons DB directly and must not have the personhog fake / ORM block active
+ disable_mock_email_code_verification: let email verification (signup and email change) send the real 6-digit code flow instead of the mocked-off link flow
asyncio_mode = auto
asyncio_default_fixture_loop_scope = module
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 7b0f6bd9d162..eeb1d294b9e8 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -84762,6 +84762,18 @@ export namespace Schemas {
notes: string[];
}
+ /**
+ * Request body for POST /api/users/verify_email/. Exactly one of token or code is required.
+ */
+ export interface VerifyEmailRequest {
+ /** UUID of the user whose email is being verified. */
+ uuid: string;
+ /** Verification token from the emailed link. Required unless a code is provided. */
+ token?: string;
+ /** The 6-digit verification code emailed at signup. Whitespace, invisible characters, and grouping hyphens are removed and compatibility digits are folded to ASCII before checking. */
+ code?: string;
+ }
+
export interface ViewLinkValidation {
/**
* Name of the table or view being joined onto the source table.