: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
feat(auth): replace login-verification link with a typed 6-digit code (#69740)
Yasend707c8023d9b
diff --git a/ee/api/test/test_admin_oauth2_middleware.py b/ee/api/test/test_admin_oauth2_middleware.pyindex 10caddcc5a02..f7123ae85c31 100644--- a/ee/api/test/test_admin_oauth2_middleware.py+++ b/ee/api/test/test_admin_oauth2_middleware.py@@ -410,7 +410,7 @@ class TestMiddlewareVerification(BaseTest):@parameterized.expand([("radar_bypass", "/admin/api/radar-bypass/"),- ("email_mfa_bypass", "/admin/api/email-mfa-bypass/"),+ ("code_based_verification_bypass", "/admin/api/code-based-verification-bypass/"),])@override_settings(@@ -431,7 +431,7 @@ class TestMiddlewareVerification(BaseTest):@parameterized.expand([("radar_bypass", "/admin/api/radar-bypass/"),- ("email_mfa_bypass", "/admin/api/email-mfa-bypass/"),+ ("code_based_verification_bypass", "/admin/api/code-based-verification-bypass/"),])@override_settings(diff --git a/ee/urls.py b/ee/urls.pyindex fac83e2dea07..252a4ef8858e 100644--- a/ee/urls.py+++ b/ee/urls.py@@ -104,12 +104,12 @@ if settings.ADMIN_PORTAL_ENABLED:from posthog.admin.admins.backfill_precalculated_person_properties_admin import (backfill_precalculated_person_properties_view,)- from posthog.admin.admins.distinct_id_usage_admin import distinct_id_usage_view- from posthog.admin.admins.email_mfa_bypass_admin import (- EmailMFABypassViewSet,- EmailMFAGlobalDisableViewSet,- email_mfa_bypass_view,+ from posthog.admin.admins.code_based_verification_bypass_admin import (+ CodeBasedVerificationBypassViewSet,+ CodeBasedVerificationGlobalDisableViewSet,+ code_based_verification_bypass_view,)+ from posthog.admin.admins.distinct_id_usage_admin import distinct_id_usage_viewfrom posthog.admin.admins.health_check_admin import (health_check_list_view,health_check_runs_fragment_view,@@ -155,24 +155,24 @@ if settings.ADMIN_PORTAL_ENABLED:name="radar-bypass-api-detail",),path(- "admin/email-mfa-bypass/",- admin.site.admin_view(email_mfa_bypass_view),- name="email-mfa-bypass",+ "admin/code-based-verification-bypass/",+ admin.site.admin_view(code_based_verification_bypass_view),+ name="code-based-verification-bypass",),path(- "admin/api/email-mfa-bypass/",- EmailMFABypassViewSet.as_view({"get": "list", "post": "create"}),- name="email-mfa-bypass-api-list",+ "admin/api/code-based-verification-bypass/",+ CodeBasedVerificationBypassViewSet.as_view({"get": "list", "post": "create"}),+ name="code-based-verification-bypass-api-list",),path(- "admin/api/email-mfa-bypass/<str:email>/",- EmailMFABypassViewSet.as_view({"delete": "destroy"}),- name="email-mfa-bypass-api-detail",+ "admin/api/code-based-verification-bypass/<str:email>/",+ CodeBasedVerificationBypassViewSet.as_view({"delete": "destroy"}),+ name="code-based-verification-bypass-api-detail",),path(- "admin/api/email-mfa-global-disable/",- EmailMFAGlobalDisableViewSet.as_view({"get": "list", "post": "create", "delete": "destroy"}),- name="email-mfa-global-disable-api",+ "admin/api/code-based-verification-global-disable/",+ CodeBasedVerificationGlobalDisableViewSet.as_view({"get": "list", "post": "create", "delete": "destroy"}),+ name="code-based-verification-global-disable-api",),path("admin/resave-cohorts/",diff --git a/frontend/src/scenes/appScenes.ts b/frontend/src/scenes/appScenes.tsindex 9f1c2b032304..e2c040a257cb 100644--- a/frontend/src/scenes/appScenes.ts+++ b/frontend/src/scenes/appScenes.ts@@ -65,7 +65,6 @@ export const appScenes: Record<Scene | string, () => any> = {[Scene.Coupons]: () => import('./coupons/Coupons'),[Scene.LiveEvents]: () => import('./activity/live/LiveEventsTable'),[Scene.Login2FA]: () => import('./authentication/login-2fa/Login2FA'),- [Scene.EmailMFAVerify]: () => import('./authentication/email-mfa-verify/EmailMFAVerify'),[Scene.Login]: () => import('./authentication/login/Login'),[Scene.MarketingAnalytics]: () => import('./marketing-analytics/MarketingAnalyticsScene'),[Scene.Max]: () => import('./max/Max'),diff --git a/frontend/src/scenes/authentication/email-mfa-verify/EmailMFAVerify.tsx b/frontend/src/scenes/authentication/email-mfa-verify/EmailMFAVerify.tsxdeleted file mode 100644index eb79df6306fe..000000000000--- a/frontend/src/scenes/authentication/email-mfa-verify/EmailMFAVerify.tsx+++ /dev/null@@ -1,54 +0,0 @@-import { useActions, useValues } from 'kea'--import * as shockedPng from '@posthog/brand/hoggies/png/shocked'-import { LemonButton } from '@posthog/lemon-ui'--import { pngHoggie } from 'lib/brand/hoggies'-import { BridgePage } from 'lib/components/BridgePage/BridgePage'-import { HeartHog } from 'lib/components/hedgehogs'--import { emailMFAVerifyLogic } from './emailMFAVerifyLogic'--const HedgehogShocked = pngHoggie(shockedPng)--export function EmailMFAVerify(): JSX.Element {- const { view, verifyResponseLoading } = useValues(emailMFAVerifyLogic)- const { verifyAndLogin } = useActions(emailMFAVerifyLogic)-- return (- <BridgePage view="login" fixedWidth={false}>- <div className="px-12 py-8 text-center flex flex-col items-center max-w-320 w-full">- {view === 'ready' ? (- <>- <h1 className="text-3xl font-bold">Almost in - just click below!</h1>- <div className="max-w-60 mb-12">- <HeartHog className="w-full h-full" />- </div>- <p className="mb-6">Click below to verify your email address.</p>- <LemonButton- type="primary"- size="large"- fullWidth- center- onClick={verifyAndLogin}- loading={verifyResponseLoading}- >- Login to PostHog- </LemonButton>- <p className="text-muted text-sm mt-6">This device will be remembered for 30 days</p>- </>- ) : view === 'invalid' ? (- <>- <h1 className="text-3xl font-bold">Whoops!</h1>- <div className="max-w-60 mb-12">- <HedgehogShocked className="w-full h-full" />- </div>- <LemonButton type="primary" to="/login" fullWidth center>- Back to login- </LemonButton>- </>- ) : null}- </div>- </BridgePage>- )-}diff --git a/frontend/src/scenes/authentication/email-mfa-verify/emailMFAVerifyLogic.ts b/frontend/src/scenes/authentication/email-mfa-verify/emailMFAVerifyLogic.tsdeleted file mode 100644index d65c21852cf3..000000000000--- a/frontend/src/scenes/authentication/email-mfa-verify/emailMFAVerifyLogic.ts+++ /dev/null@@ -1,90 +0,0 @@-import { actions, connect, kea, path, reducers } from 'kea'-import { loaders } from 'kea-loaders'-import { urlToAction } from 'kea-router'--import api from 'lib/api'-import { featureFlagLogic } from 'lib/logic/featureFlagLogic'-import { handleLoginRedirect } from 'scenes/authentication/login/loginLogic'-import { preflightLogic } from 'scenes/PreflightCheck/preflightLogic'--import type { emailMFAVerifyLogicType } from './emailMFAVerifyLogicType'--export const emailMFAVerifyLogic = kea<emailMFAVerifyLogicType>([- path(['scenes', 'authentication', 'email-mfa-verify', 'emailMFAVerifyLogic']),- connect(() => ({- values: [preflightLogic, ['preflight'], featureFlagLogic, ['featureFlags']],- })),- actions({- setGeneralError: (code, detail) => ({ code, detail }),- clearGeneralError: true,- setEmailAndToken: (email: string, token: string) => ({ email, token }),- setView: (view: 'ready' | 'invalid') => ({ view }),- verifyAndLogin: true,- }),- reducers({- generalError: [- null as { code: string; detail: string } | null,- {- setGeneralError: (_, error) => error,- clearGeneralError: () => null,- },- ],- view: [- 'ready' as 'ready' | 'invalid',- {- setView: (_, { view }) => view,- },- ],- email: [- '' as string,- {- setEmailAndToken: (_, { email }) => email,- },- ],- token: [- '' as string,- {- setEmailAndToken: (_, { token }) => token,- },- ],- }),- loaders(({ actions, values }) => ({- verifyResponse: [- null as { success: boolean } | null,- {- verifyAndLogin: async () => {- try {- // Validate token AND log in (single endpoint)- const response = await api.create<any>('api/login/email-mfa', {- email: values.email,- token: values.token,- })-- // Login successful - redirect to app- handleLoginRedirect()- window.location.reload()-- return response- } catch (e) {- const { code, detail } = e as Record<string, any>- actions.setGeneralError(code, detail)- actions.setView('invalid')- throw e- }- },- },- ],- })),- urlToAction(({ actions }) => ({- '/login/verify': (_, { email, token }) => {- if (email && token) {- // Store email and token, show ready view (no API call yet)- actions.setEmailAndToken(email, token)- actions.setView('ready')- } else {- actions.setGeneralError('invalid_link', 'Invalid verification link. Please try logging in again.')- actions.setView('invalid')- }- },- })),-])diff --git a/frontend/src/scenes/authentication/login/PaperDeskLogin.stories.tsx b/frontend/src/scenes/authentication/login/PaperDeskLogin.stories.tsxindex efbea2ba5b4d..6ca40d24854c 100644--- a/frontend/src/scenes/authentication/login/PaperDeskLogin.stories.tsx+++ b/frontend/src/scenes/authentication/login/PaperDeskLogin.stories.tsx@@ -17,7 +17,7 @@ type StoryArgs = {gitlab: booleansamlAvailable: booleanssoEnforcement: 'none' | 'google-oauth2' | 'github' | 'gitlab' | 'saml'- generalError: 'none' | 'invalid_credentials' | 'email_verification_sent'+ generalError: 'none' | 'invalid_credentials' | 'code_based_verification_sent'}const meta: Meta<StoryArgs> = {@@ -43,7 +43,7 @@ const meta: Meta<StoryArgs> = {generalError: {control: 'select',name: 'General error',- options: ['none', 'invalid_credentials', 'email_verification_sent'],+ options: ['none', 'invalid_credentials', 'code_based_verification_sent'],},},args: {@@ -104,7 +104,7 @@ const Template: StoryFn<StoryArgs> = ({if (generalError !== 'none') {const messages: Record<string, string> = {invalid_credentials: 'Invalid email or password.',- email_verification_sent: 'Check your email to verify your account.',+ code_based_verification_sent: 'Check your email to verify your account.',}loginLogic.actions.setGeneralError(generalError, messages[generalError] ?? '')} else {@@ -133,4 +133,4 @@ export const LoginError: StoryFn<StoryArgs> = Template.bind({})LoginError.args = { generalError: 'invalid_credentials' }export const EmailVerification: StoryFn<StoryArgs> = Template.bind({})-EmailVerification.args = { generalError: 'email_verification_sent' }+EmailVerification.args = { generalError: 'code_based_verification_sent' }diff --git a/frontend/src/scenes/authentication/login/loginLogic.test.ts b/frontend/src/scenes/authentication/login/loginLogic.test.tsindex 715371124d32..393a005489a8 100644--- a/frontend/src/scenes/authentication/login/loginLogic.test.ts+++ b/frontend/src/scenes/authentication/login/loginLogic.test.ts@@ -161,6 +161,46 @@ describe('loginLogic', () => {})})+ describe('code-based verification', () => {+ let logic: ReturnType<typeof loginLogic.build>+ const originalVendor = window.navigator.vendor++ beforeEach(() => {+ setVendor(WEBKIT_VENDOR) // skip passkey auto-trigger+ useMocks({+ get: { '/api/users/@me/': () => [200, {}] },+ post: {+ '/api/login/precheck': () => [200, { saml_available: false }],+ '/api/login': () => [401, { code: 'code_based_verification_required', detail: '[email protected]' }],+ '/api/login/code-based-verification': () => [200, { success: true }],+ },+ })+ initKeaTests()+ router.actions.push('/login')+ logic = loginLogic()+ logic.mount()+ })++ afterEach(() => {+ logic.unmount()+ setVendor(originalVendor)+ jest.clearAllMocks()+ })++ it('enters code-entry mode when login requires a code, and exits on demand', async () => {+ logic.actions.setLoginValues({ email: '[email protected]', password: 'a-password' })+ logic.actions.submitLogin()+ await expectLogic(logic).toDispatchActions(['setCodeVerificationRequired', 'submitLoginFailure'])++ expect(logic.values.codeVerificationRequired).toBe(true)+ expect(logic.values.generalError?.code).toBe('code_based_verification_sent')++ logic.actions.exitCodeVerification()+ expect(logic.values.codeVerificationRequired).toBe(false)+ expect(logic.values.generalError).toBe(null)+ })+ })+describe('precheck dedupe', () => {let logic: ReturnType<typeof loginLogic.build>let precheckHandler: jest.Mockdiff --git a/frontend/src/scenes/authentication/login/loginLogic.ts b/frontend/src/scenes/authentication/login/loginLogic.tsindex 7a47d6238541..3d25d95b58c9 100644--- a/frontend/src/scenes/authentication/login/loginLogic.ts+++ b/frontend/src/scenes/authentication/login/loginLogic.ts@@ -76,6 +76,10 @@ export interface TwoFactorForm {token: number | null}+export interface CodeVerificationForm {+ code: string+}+export const loginLogic = kea<loginLogicType>([path(['scenes', 'authentication', 'login', 'loginLogic']),connect(() => ({@@ -92,6 +96,8 @@ export const loginLogic = kea<loginLogicType>([actions({setGeneralError: (code: string, detail: string) => ({ code, detail }),clearGeneralError: true,+ setCodeVerificationRequired: true,+ exitCodeVerification: true,}),reducers({// This is separate from the login form, so that the form can be submitted even if a general error is present@@ -100,6 +106,16 @@ export const loginLogic = kea<loginLogicType>([{setGeneralError: (_, error) => error,clearGeneralError: () => null,+ exitCodeVerification: () => null,+ },+ ],+ // Whether login is waiting on the emailed 6-digit code. Kept separate from `generalError` so a+ // wrong-code error can be surfaced without dropping the user back to the password form.+ codeVerificationRequired: [+ false,+ {+ setCodeVerificationRequired: () => true,+ exitCodeVerification: () => false,},],}),@@ -135,10 +151,10 @@ export const loginLogic = kea<loginLogicType>([resendResponse: [null as { success: boolean; message: string } | null,{- resendEmailMFA: async (_, breakpoint) => {+ resendCodeBasedVerification: async (_, breakpoint) => {breakpoint()try {- const response = await api.create<any>('api/login/email-mfa/resend')+ const response = await api.create<any>('api/login/code-based-verification/resend')lemonToast.success('Verification email resent')return response} catch (e) {@@ -167,7 +183,7 @@ export const loginLogic = kea<loginLogicType>([(searchParams: Record<string, string>): boolean => searchParams['reason'] === 'session_risk',],})),- forms(({ actions }) => ({+ forms(({ actions, values }) => ({login: {defaults: { email: '', password: '' } as LoginForm,errors: ({ email, password }) => ({@@ -198,12 +214,12 @@ export const loginLogic = kea<loginLogicType>([}throw e}- if (code === 'email_mfa_required') {+ if (code === 'code_based_verification_required') {const emailAddress = detail?.email || email+ actions.setCodeVerificationRequired()actions.setGeneralError(- 'email_verification_sent',- `For your security, we've sent a verification link to ${emailAddress}. Please check your inbox and click the link to complete- your login.`+ 'code_based_verification_sent',+ `For your security, we've emailed a 6-digit verification code to ${emailAddress}. Enter it below to finish logging in.`)throw e}@@ -212,13 +228,43 @@ export const loginLogic = kea<loginLogicType>([}},},+ codeVerification: {+ defaults: { code: '' } as CodeVerificationForm,+ errors: ({ code }) => ({+ code: !code ? 'Please enter the code from your email' : undefined,+ }),+ submit: async ({ code }, breakpoint) => {+ breakpoint()+ actions.clearGeneralError()+ try {+ return await api.create<any>('api/login/code-based-verification', {+ code,+ email: values.login.email,+ })+ } catch (e) {+ const { detail } = e as Record<string, any>+ const message =+ typeof detail === 'string' ? detail : 'That code is invalid or has expired. Please try again.'+ actions.setGeneralError('invalid_code', message)+ throw e+ }+ },+ },})),- listeners(({ values }) => ({+ listeners(({ values, actions }) => ({submitLoginSuccess: () => {handleLoginRedirect()// Reload the page after login to ensure POSTHOG_APP_CONTEXT is set correctly.window.location.reload()},+ submitCodeVerificationSuccess: () => {+ handleLoginRedirect()+ // Reload the page after login to ensure POSTHOG_APP_CONTEXT is set correctly.+ window.location.reload()+ },+ exitCodeVerification: () => {+ actions.resetCodeVerification()+ },precheckSuccess: async (_, breakpoint) => {const { precheckResponse } = values// Auto-trigger the modal passkey prompt if the user has passkeys and SSO isn't enforced.diff --git a/frontend/src/scenes/authentication/login/variants/legacy/LegacyLogin.tsx b/frontend/src/scenes/authentication/login/variants/legacy/LegacyLogin.tsxindex d2cf2404b952..49cbcc1eb819 100644--- a/frontend/src/scenes/authentication/login/variants/legacy/LegacyLogin.tsx+++ b/frontend/src/scenes/authentication/login/variants/legacy/LegacyLogin.tsx@@ -34,7 +34,8 @@ import { SessionRiskBanner } from '../../SessionRiskBanner'const LAST_LOGIN_METHOD_COOKIE = 'ph_last_login_method'function Login(): JSX.Element {- const { precheck, resendEmailMFA, clearGeneralError, resetLogin, devLogin, loadDevUsers } = useActions(loginLogic)+ const { precheck, resendCodeBasedVerification, exitCodeVerification, resetLogin, devLogin, loadDevUsers } =+ useActions(loginLogic)const { openSupportForm } = useActions(supportLogic)const {precheckResponse,@@ -44,6 +45,8 @@ function Login(): JSX.Element {generalError,signupUrl,resendResponseLoading,+ codeVerificationRequired,+ isCodeVerificationSubmitting,devUsers,devUsersLoading,devLoginTimeSavedLabel,@@ -60,8 +63,8 @@ function Login(): JSX.Element {const passwordInputRef = useRef<HTMLInputElement>(null)const preventPasswordError = useRef(false)const isPasswordHidden = precheckResponse.status === 'pending' || precheckResponse.sso_enforcement- const isEmailVerificationSent = generalError?.code === 'email_verification_sent'- const loginTitle = isEmailVerificationSent ? 'Check your email' : 'Log in'+ const isCodeSent = codeVerificationRequired+ const loginTitle = isCodeSent ? 'Enter your login code' : 'Log in'const wasPasswordHiddenRef = useRef(isPasswordHidden)const lastLoginMethod = getCookie(LAST_LOGIN_METHOD_COOKIE) as LoginMethod@@ -96,7 +99,7 @@ function Login(): JSX.Element {<h2>{loginTitle}</h2><SessionRiskBanner />{generalError && (- <LemonBanner type={generalError.code === 'email_verification_sent' ? 'warning' : 'error'}>+ <LemonBanner type={generalError.code === 'code_based_verification_sent' ? 'warning' : 'error'}><>{generalError.detail || ERROR_MESSAGES[generalError.code] || (<>@@ -127,24 +130,51 @@ function Login(): JSX.Element {</LemonBanner>)}{generalError?.code === 'invalid_credentials' && <OtherRegionHint />}- {isEmailVerificationSent ? (- <div className="deprecated-space-y-4">+ {isCodeSent ? (+ <Form+ logic={loginLogic}+ formKey="codeVerification"+ enableFormOnSubmit+ className="deprecated-space-y-4"+ >+ <LemonField name="code" label="Verification code">+ <LemonInput+ className="ph-ignore-input"+ autoFocus+ data-attr="code-verification"+ placeholder="123456"+ inputMode="numeric"+ autoComplete="one-time-code"+ />+ </LemonField>+ <LemonButton+ type="primary"+ status="alt"+ htmlType="submit"+ data-attr="code-verification-submit"+ fullWidth+ center+ size="large"+ loading={isCodeVerificationSubmitting}+ >+ Verify and log in+ </LemonButton><div className="flex justify-center"><LemonButtontype="tertiary"size="small"loading={resendResponseLoading}- onClick={() => resendEmailMFA(null)}+ onClick={() => resendCodeBasedVerification(null)}>- Resend verification email+ Resend code</LemonButton></div><div className="text-center">- <Link onClick={() => clearGeneralError()} className="text-muted">+ <Link onClick={() => exitCodeVerification()} className="text-muted">Back to login</Link></div>- </div>+ </Form>) : (<Formlogic={loginLogic}@@ -248,7 +278,7 @@ function Login(): JSX.Element {)}</Form>)}- {!isEmailVerificationSent && preflight?.cloud && (+ {!isCodeSent && preflight?.cloud && (<div className="text-center mt-4">Don't have an account?{' '}<Link to={[signupUrl, { email: login.email }]} data-attr="signup" className="font-bold">@@ -256,7 +286,7 @@ function Login(): JSX.Element {</Link></div>)}- {!isEmailVerificationSent && !precheckResponse.saml_available && !precheckResponse.sso_enforcement && (+ {!isCodeSent && !precheckResponse.saml_available && !precheckResponse.sso_enforcement && (<SocialLoginButtonscaption="Or log in with"topDividerdiff --git a/frontend/src/scenes/authentication/login/variants/paper-desk/PaperDeskLogin.tsx b/frontend/src/scenes/authentication/login/variants/paper-desk/PaperDeskLogin.tsxindex 6c27c8104392..4f3a4cebcff3 100644--- a/frontend/src/scenes/authentication/login/variants/paper-desk/PaperDeskLogin.tsx+++ b/frontend/src/scenes/authentication/login/variants/paper-desk/PaperDeskLogin.tsx@@ -32,7 +32,7 @@ import { SessionRiskBanner } from '../../SessionRiskBanner'const LAST_LOGIN_METHOD_COOKIE = 'ph_last_login_method'function Login(): JSX.Element {- const { precheck, clearGeneralError, resendEmailMFA } = useActions(loginLogic)+ const { precheck, exitCodeVerification, resendCodeBasedVerification } = useActions(loginLogic)const { openSupportForm } = useActions(supportLogic)const {precheckResponse,@@ -43,11 +43,13 @@ function Login(): JSX.Element {signupUrl,resendResponseLoading,resendResponse,+ codeVerificationRequired,+ isCodeVerificationSubmitting,} = useValues(loginLogic)const { preflight } = useValues(preflightLogic)const isPasswordHidden = !!precheckResponse.sso_enforcement- const isEmailVerificationSent = generalError?.code === 'email_verification_sent'+ const isCodeSent = codeVerificationRequiredconst lastLoginMethod = getCookie(LAST_LOGIN_METHOD_COOKIE) as LoginMethodconst prevEmail = usePrevious(login.email)@@ -78,17 +80,15 @@ function Login(): JSX.Element {{preflight?.cloud && <RedirectIfLoggedInOtherInstance />}<PaperDeskCard footer={footer}><CardTitle- title={isEmailVerificationSent ? 'Check your email' : 'Log in to PostHog'}- sub={isEmailVerificationSent ? undefined : "Welcome back. Let's go ship something."}+ title={isCodeSent ? 'Enter your login code' : 'Log in to PostHog'}+ sub={isCodeSent ? undefined : "Welcome back. Let's go ship something."}/><SessionRiskBanner className="mb-4" />{generalError && (<divclassName={twMerge('mb-4 py-2.5 px-3 text-sm leading-normal text-primary text-left bg-danger-highlight border border-danger rounded',- isEmailVerificationSent- ? 'bg-success-highlight border-success'- : 'bg-danger-highlight border-danger'+ isCodeSent ? 'bg-success-highlight border-success' : 'bg-danger-highlight border-danger')}>{generalError.detail ||@@ -120,32 +120,59 @@ function Login(): JSX.Element {<OtherRegionHint /></div>)}- {isEmailVerificationSent ? (- <div className="flex flex-col items-center gap-3">+ {isCodeSent ? (+ <Form+ logic={loginLogic}+ formKey="codeVerification"+ enableFormOnSubmit+ className="flex flex-col gap-4"+ >+ <LemonField name="code" label="Verification code">+ <LemonInput+ className="ph-ignore-input"+ autoFocus+ data-attr="code-verification"+ placeholder="123456"+ inputMode="numeric"+ autoComplete="one-time-code"+ />+ </LemonField><LemonButton- size="large"- type="secondary"- center+ type="primary"+ status="alt"+ htmlType="submit"+ data-attr="code-verification-submit"fullWidth- disabled={resendResponseLoading}- loading={resendResponseLoading}- onClick={() => resendEmailMFA(null)}+ center+ size="large"+ loading={isCodeVerificationSubmitting}>- Resend verification email+ Verify and log in</LemonButton>- {resendResponse?.success && (- <p className="flex items-center gap-1 text-success mb-0" role="status">- <IconCheckCircle />- Verification email sent — check your inbox.- </p>- )}- <Link- onClick={() => clearGeneralError()}- className="font-semibold no-underline cursor-pointer hover:underline hover:underline-offset-2 text-secondary"- >- Back to login- </Link>- </div>+ <div className="flex flex-col items-center gap-3">+ <LemonButton+ size="small"+ type="tertiary"+ disabled={resendResponseLoading}+ loading={resendResponseLoading}+ onClick={() => resendCodeBasedVerification(null)}+ >+ Resend code+ </LemonButton>+ {resendResponse?.success && (+ <p className="flex items-center gap-1 text-success mb-0" role="status">+ <IconCheckCircle />+ Code sent — check your inbox.+ </p>+ )}+ <Link+ onClick={() => exitCodeVerification()}+ className="font-semibold no-underline cursor-pointer hover:underline hover:underline-offset-2 text-secondary"+ >+ Back to login+ </Link>+ </div>+ </Form>) : (<Form logic={loginLogic} formKey="login" enableFormOnSubmit className="flex flex-col gap-4"><RegionField />@@ -231,7 +258,7 @@ function Login(): JSX.Element {)}</Form>)}- {!isEmailVerificationSent && !precheckResponse.saml_available && !precheckResponse.sso_enforcement && (+ {!isCodeSent && !precheckResponse.saml_available && !precheckResponse.sso_enforcement && (<SocialLoginButtonstopDividercaption="Or log in with"diff --git a/frontend/src/scenes/sceneTypes.ts b/frontend/src/scenes/sceneTypes.tsindex e99e89517284..2410539bdb08 100644--- a/frontend/src/scenes/sceneTypes.ts+++ b/frontend/src/scenes/sceneTypes.ts@@ -97,7 +97,6 @@ export enum Scene {LiveEvents = 'LiveEvents',Login = 'Login',Login2FA = 'Login2FA',- EmailMFAVerify = 'EmailMFAVerify',MaterializedColumns = 'MaterializedColumns',Max = 'Max',Models = 'Models',diff --git a/frontend/src/scenes/scenes.ts b/frontend/src/scenes/scenes.tsindex 38160009e688..df2b940b973e 100644--- a/frontend/src/scenes/scenes.ts+++ b/frontend/src/scenes/scenes.ts@@ -297,7 +297,6 @@ export const sceneConfigurations: Record<Scene | string, SceneConfig> = {},[Scene.LiveDebugger]: { projectBased: true, name: 'Live debugger' },[Scene.Login2FA]: { onlyUnauthenticated: true, name: 'Login 2FA', layout: 'plain' },- [Scene.EmailMFAVerify]: { onlyUnauthenticated: true, layout: 'plain' },[Scene.Login]: { onlyUnauthenticated: true, layout: 'plain' },[Scene.Max]: { projectBased: true, name: 'Max', layout: 'app-raw-no-header', hideProjectNotice: true },[Scene.Models]: {@@ -888,7 +887,6 @@ export const routes: Record<string, [Scene | string, string]> = {[urls.credentialReview()]: [Scene.CredentialReview, 'credentialReview'],[urls.cliAuthorize()]: [Scene.CLIAuthorize, 'cliAuthorize'],[urls.cliLive()]: [Scene.CLILive, 'cliLive'],- [urls.emailMFAVerify()]: [Scene.EmailMFAVerify, 'emailMFAVerify'],[urls.preflight()]: [Scene.PreflightCheck, 'preflight'],[urls.signup()]: [Scene.Signup, 'signup'],[urls.inviteSignup(':id')]: [Scene.InviteSignup, 'inviteSignup'],diff --git a/frontend/src/scenes/urls.ts b/frontend/src/scenes/urls.tsindex ff7540503f14..497d2220b154 100644--- a/frontend/src/scenes/urls.ts+++ b/frontend/src/scenes/urls.ts@@ -167,7 +167,6 @@ export const urls = {credentialReview: (): string => '/account/credential-review',cliAuthorize: (): string => '/cli/authorize',cliLive: (): string => '/cli/live',- emailMFAVerify: (): string => '/login/verify',liveDebugger: (): string => '/live-debugger',passwordReset: (): string => '/reset',passwordResetComplete: (userUuid: string, token: string): string => `/reset/${userUuid}/${token}`,diff --git a/posthog/admin/admins/email_mfa_bypass_admin.py b/posthog/admin/admins/code_based_verification_bypass_admin.pysimilarity index 53%rename from posthog/admin/admins/email_mfa_bypass_admin.pyrename to posthog/admin/admins/code_based_verification_bypass_admin.pyindex 9fd566bdfc2f..6ca1677b8e88 100644--- a/posthog/admin/admins/email_mfa_bypass_admin.py+++ b/posthog/admin/admins/code_based_verification_bypass_admin.py@@ -9,92 +9,96 @@ from rest_framework.request import Requestfrom rest_framework.response import Responsefrom posthog.helpers.two_factor_session import (- EMAIL_MFA_BYPASS_REDIS_KEY,- MAX_EMAIL_MFA_GLOBAL_DISABLE_TTL_SECONDS,- add_email_mfa_bypass,- clear_email_mfa_global_disable,- get_email_mfa_global_disable,- remove_email_mfa_bypass,- set_email_mfa_global_disable,+ CODE_BASED_VERIFICATION_BYPASS_REDIS_KEY,+ MAX_CODE_BASED_VERIFICATION_GLOBAL_DISABLE_TTL_SECONDS,+ add_code_based_verification_bypass,+ clear_code_based_verification_global_disable,+ get_code_based_verification_global_disable,+ remove_code_based_verification_bypass,+ set_code_based_verification_global_disable,)from posthog.models.user import Userfrom posthog.redis import get_client-class EmailMFABypassEmailSerializer(serializers.Serializer):- email = serializers.EmailField(help_text="Email address to bypass email MFA verification")+class CodeBasedVerificationBypassEmailSerializer(serializers.Serializer):+ email = serializers.EmailField(help_text="Email address to bypass code-based verification")-class EmailMFAGlobalDisableSerializer(serializers.Serializer):- reason = serializers.CharField(allow_blank=False, help_text="Why email MFA is being disabled globally")+class CodeBasedVerificationGlobalDisableSerializer(serializers.Serializer):+ reason = serializers.CharField(+ allow_blank=False, help_text="Why code-based verification is being disabled globally"+ )ttl_seconds = serializers.IntegerField(min_value=1,- max_value=MAX_EMAIL_MFA_GLOBAL_DISABLE_TTL_SECONDS,+ max_value=MAX_CODE_BASED_VERIFICATION_GLOBAL_DISABLE_TTL_SECONDS,help_text="How long the disable lasts, in seconds (max 7 days)",)-class EmailMFAGlobalDisableViewSet(viewsets.ViewSet):- """Completely disable email MFA verification for all users, with a required reason and TTL."""+class CodeBasedVerificationGlobalDisableViewSet(viewsets.ViewSet):+ """Completely disable code-based verification for all users, with a required reason and TTL."""permission_classes = [IsAdminUser]def list(self, request: Request) -> Response:- state = get_email_mfa_global_disable()+ state = get_code_based_verification_global_disable()return Response({"disabled": state is not None, "state": state})def create(self, request: Request) -> Response:- serializer = EmailMFAGlobalDisableSerializer(data=request.data)+ serializer = CodeBasedVerificationGlobalDisableSerializer(data=request.data)serializer.is_valid(raise_exception=True)- set_email_mfa_global_disable(+ set_code_based_verification_global_disable(reason=serializer.validated_data["reason"],ttl_seconds=serializer.validated_data["ttl_seconds"],disabled_by=cast(User, request.user).email,)- return Response({"disabled": True, "state": get_email_mfa_global_disable()}, status=status.HTTP_201_CREATED)+ return Response(+ {"disabled": True, "state": get_code_based_verification_global_disable()}, status=status.HTTP_201_CREATED+ )def destroy(self, request: Request) -> Response:- clear_email_mfa_global_disable()+ clear_code_based_verification_global_disable()return Response(status=status.HTTP_204_NO_CONTENT)-class EmailMFABypassViewSet(viewsets.ViewSet):+class CodeBasedVerificationBypassViewSet(viewsets.ViewSet):permission_classes = [IsAdminUser]def list(self, request: Request) -> Response:bypass_emails = sorted(member.decode() if isinstance(member, bytes) else member- for member in get_client().smembers(EMAIL_MFA_BYPASS_REDIS_KEY)+ for member in get_client().smembers(CODE_BASED_VERIFICATION_BYPASS_REDIS_KEY))return Response(bypass_emails)def create(self, request: Request) -> Response:- serializer = EmailMFABypassEmailSerializer(data=request.data)+ serializer = CodeBasedVerificationBypassEmailSerializer(data=request.data)serializer.is_valid(raise_exception=True)email = serializer.validated_data["email"]- add_email_mfa_bypass(email)+ add_code_based_verification_bypass(email)return Response({"email": email}, status=status.HTTP_201_CREATED)def destroy(self, request: Request, email: str) -> Response:- remove_email_mfa_bypass(email)+ remove_code_based_verification_bypass(email)return Response(status=status.HTTP_204_NO_CONTENT)-def email_mfa_bypass_view(request):+def code_based_verification_bypass_view(request):"""Admin template view — thin wrapper that renders the HTML admin page."""bypass_emails = sorted(member.decode() if isinstance(member, bytes) else member- for member in get_client().smembers(EMAIL_MFA_BYPASS_REDIS_KEY)+ for member in get_client().smembers(CODE_BASED_VERIFICATION_BYPASS_REDIS_KEY))context = {"bypass_emails": bypass_emails,- "global_disable": get_email_mfa_global_disable(),- "title": "Email MFA bypass",+ "global_disable": get_code_based_verification_global_disable(),+ "title": "Code-based verification bypass","has_view_permission": True,"site_title": admin.site.site_title,"site_header": admin.site.site_header,"site_url": admin.site.site_url,"has_permission": True,}- return render(request, "admin/email_mfa_bypass.html", context)+ return render(request, "admin/code_based_verification_bypass.html", context)diff --git a/posthog/admin/test_code_based_verification_global_disable_admin.py b/posthog/admin/test_code_based_verification_global_disable_admin.pynew file mode 100644index 000000000000..1226330e55f5--- /dev/null+++ b/posthog/admin/test_code_based_verification_global_disable_admin.py@@ -0,0 +1,81 @@+from posthog.test.base import APIBaseTest++from rest_framework import status+from rest_framework.test import APIRequestFactory, force_authenticate++from posthog.admin.admins.code_based_verification_bypass_admin import CodeBasedVerificationGlobalDisableViewSet+from posthog.helpers.two_factor_session import (+ MAX_CODE_BASED_VERIFICATION_GLOBAL_DISABLE_TTL_SECONDS,+ clear_code_based_verification_global_disable,+ is_code_based_verification_globally_disabled,+)+++class TestCodeBasedVerificationGlobalDisableAdmin(APIBaseTest):+ def setUp(self):+ super().setUp()+ clear_code_based_verification_global_disable()+ self.factory = APIRequestFactory()++ def tearDown(self):+ clear_code_based_verification_global_disable()+ super().tearDown()++ def _make_staff(self):+ self.user.is_staff = True+ self.user.save()++ def test_non_staff_is_forbidden(self):+ request = self.factory.get("/admin/api/code-based-verification-global-disable/")+ force_authenticate(request, user=self.user)+ response = CodeBasedVerificationGlobalDisableViewSet.as_view({"get": "list"})(request)+ self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)++ def test_staff_can_disable_list_and_clear(self):+ self._make_staff()++ request = self.factory.post(+ "/admin/api/code-based-verification-global-disable/",+ {"reason": "email outage", "ttl_seconds": 3600},+ format="json",+ )+ force_authenticate(request, user=self.user)+ response = CodeBasedVerificationGlobalDisableViewSet.as_view({"post": "create"})(request)+ self.assertEqual(response.status_code, status.HTTP_201_CREATED)+ self.assertTrue(is_code_based_verification_globally_disabled())+ self.assertEqual(response.data["state"]["disabled_by"], self.user.email)+ self.assertEqual(response.data["state"]["reason"], "email outage")++ request = self.factory.get("/admin/api/code-based-verification-global-disable/")+ force_authenticate(request, user=self.user)+ response = CodeBasedVerificationGlobalDisableViewSet.as_view({"get": "list"})(request)+ self.assertEqual(response.status_code, status.HTTP_200_OK)+ self.assertTrue(response.data["disabled"])++ request = self.factory.delete("/admin/api/code-based-verification-global-disable/")+ force_authenticate(request, user=self.user)+ response = CodeBasedVerificationGlobalDisableViewSet.as_view({"delete": "destroy"})(request)+ self.assertEqual(response.status_code, status.HTTP_204_NO_CONTENT)+ self.assertFalse(is_code_based_verification_globally_disabled())++ def test_reason_is_required(self):+ self._make_staff()+ request = self.factory.post(+ "/admin/api/code-based-verification-global-disable/", {"reason": "", "ttl_seconds": 3600}, format="json"+ )+ force_authenticate(request, user=self.user)+ response = CodeBasedVerificationGlobalDisableViewSet.as_view({"post": "create"})(request)+ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)+ self.assertFalse(is_code_based_verification_globally_disabled())++ def test_ttl_cap_is_enforced(self):+ self._make_staff()+ request = self.factory.post(+ "/admin/api/code-based-verification-global-disable/",+ {"reason": "too long", "ttl_seconds": MAX_CODE_BASED_VERIFICATION_GLOBAL_DISABLE_TTL_SECONDS + 1},+ format="json",+ )+ force_authenticate(request, user=self.user)+ response = CodeBasedVerificationGlobalDisableViewSet.as_view({"post": "create"})(request)+ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)+ self.assertFalse(is_code_based_verification_globally_disabled())diff --git a/posthog/admin/test_email_mfa_global_disable_admin.py b/posthog/admin/test_email_mfa_global_disable_admin.pydeleted file mode 100644index ce28e6dc370b..000000000000--- a/posthog/admin/test_email_mfa_global_disable_admin.py+++ /dev/null@@ -1,79 +0,0 @@-from posthog.test.base import APIBaseTest--from rest_framework import status-from rest_framework.test import APIRequestFactory, force_authenticate--from posthog.admin.admins.email_mfa_bypass_admin import EmailMFAGlobalDisableViewSet-from posthog.helpers.two_factor_session import (- MAX_EMAIL_MFA_GLOBAL_DISABLE_TTL_SECONDS,- clear_email_mfa_global_disable,- is_email_mfa_globally_disabled,-)---class TestEmailMFAGlobalDisableAdmin(APIBaseTest):- def setUp(self):- super().setUp()- clear_email_mfa_global_disable()- self.factory = APIRequestFactory()-- def tearDown(self):- clear_email_mfa_global_disable()- super().tearDown()-- def _make_staff(self):- self.user.is_staff = True- self.user.save()-- def test_non_staff_is_forbidden(self):- request = self.factory.get("/admin/api/email-mfa-global-disable/")- force_authenticate(request, user=self.user)- response = EmailMFAGlobalDisableViewSet.as_view({"get": "list"})(request)- self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)-- def test_staff_can_disable_list_and_clear(self):- self._make_staff()-- request = self.factory.post(- "/admin/api/email-mfa-global-disable/", {"reason": "email outage", "ttl_seconds": 3600}, format="json"- )- force_authenticate(request, user=self.user)- response = EmailMFAGlobalDisableViewSet.as_view({"post": "create"})(request)- self.assertEqual(response.status_code, status.HTTP_201_CREATED)- self.assertTrue(is_email_mfa_globally_disabled())- self.assertEqual(response.data["state"]["disabled_by"], self.user.email)- self.assertEqual(response.data["state"]["reason"], "email outage")-- request = self.factory.get("/admin/api/email-mfa-global-disable/")- force_authenticate(request, user=self.user)- response = EmailMFAGlobalDisableViewSet.as_view({"get": "list"})(request)- self.assertEqual(response.status_code, status.HTTP_200_OK)- self.assertTrue(response.data["disabled"])-- request = self.factory.delete("/admin/api/email-mfa-global-disable/")- force_authenticate(request, user=self.user)- response = EmailMFAGlobalDisableViewSet.as_view({"delete": "destroy"})(request)- self.assertEqual(response.status_code, status.HTTP_204_NO_CONTENT)- self.assertFalse(is_email_mfa_globally_disabled())-- def test_reason_is_required(self):- self._make_staff()- request = self.factory.post(- "/admin/api/email-mfa-global-disable/", {"reason": "", "ttl_seconds": 3600}, format="json"- )- force_authenticate(request, user=self.user)- response = EmailMFAGlobalDisableViewSet.as_view({"post": "create"})(request)- self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)- self.assertFalse(is_email_mfa_globally_disabled())-- def test_ttl_cap_is_enforced(self):- self._make_staff()- request = self.factory.post(- "/admin/api/email-mfa-global-disable/",- {"reason": "too long", "ttl_seconds": MAX_EMAIL_MFA_GLOBAL_DISABLE_TTL_SECONDS + 1},- format="json",- )- force_authenticate(request, user=self.user)- response = EmailMFAGlobalDisableViewSet.as_view({"post": "create"})(request)- self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)- self.assertFalse(is_email_mfa_globally_disabled())diff --git a/posthog/api/authentication.py b/posthog/api/authentication.pyindex 247dbab2c72e..821ca0b9cf68 100644--- a/posthog/api/authentication.py+++ b/posthog/api/authentication.py@@ -51,10 +51,10 @@ from posthog.exceptions_capture import capture_exceptionfrom posthog.geoip import get_geoip_propertiesfrom posthog.helpers.dev_login import is_dev_login_allowedfrom posthog.helpers.two_factor_session import (- _obfuscate_token,+ CODE_MAX_ATTEMPTS,+ LOGIN_CODE_VERIFICATION_COUNTER,clear_two_factor_session_flags,- email_mfa_token_generator,- email_mfa_verifier,+ code_based_verifier,has_passkeys,set_two_factor_verified_in_session,)@@ -63,7 +63,12 @@ from posthog.models import OrganizationDomain, Userfrom posthog.models.activity_logging import signal_handlers # noqa: F401from posthog.models.webauthn_credential import WebauthnCredentialfrom posthog.passkey import generate_passkey_authentication_options, verify_passkey_authentication_response-from posthog.rate_limit import EmailMFAResendThrottle, EmailMFAThrottle, TwoFactorThrottle, UserPasswordResetThrottle+from posthog.rate_limit import (+ CodeBasedVerificationResendThrottle,+ CodeBasedVerificationThrottle,+ TwoFactorThrottle,+ UserPasswordResetThrottle,+)from posthog.session.activity import revoke_other_sessionsfrom posthog.tasks.email import (login_from_new_device_notification,@@ -156,10 +161,10 @@ class TwoFactorRequired(APIException):default_code = "2fa_required"-class EmailMFARequired(APIException):+class CodeBasedVerificationRequired(APIException):status_code = 401- default_detail = "Email MFA is required."- default_code = "email_mfa_required"+ default_detail = "Code-based verification is required."+ default_code = "code_based_verification_required"def __init__(self, email: str | None = None):detail = email if email else self.default_detail@@ -225,12 +230,12 @@ class LoginSerializer(serializers.Serializer):user_has_passkeys = has_passkeys(user)passkeys_enabled_for_2fa = user_has_passkeys and user.passkeys_enabled_for_2fa- # If user has neither TOTP nor passkeys enabled for 2FA, check for email MFA remember cookie+ # If user has neither TOTP nor passkeys enabled for 2FA, check for code-based verification remember cookieif not device and not passkeys_enabled_for_2fa:for key, value in self.context["request"].COOKIES.items():if key.startswith(REMEMBER_COOKIE_PREFIX) and value:try:- if validate_remember_device_cookie(value, user=user, otp_device_id="email_mfa"):+ if validate_remember_device_cookie(value, user=user, otp_device_id="code_based_verification"):return Falseexcept BadSignature:pass@@ -259,7 +264,7 @@ class LoginSerializer(serializers.Serializer):except BadSignature:pass- # No device and no passkeys enabled for 2FA - should have been handled above, but fallback to email MFA+ # No device and no passkeys enabled for 2FA - should have been handled above, but fallback to code-based verificationreturn Truedef create(self, validated_data: dict[str, str]) -> Any:@@ -338,18 +343,18 @@ class LoginSerializer(serializers.Serializer):# TOTP or passkey flowraise TwoFactorRequired()else:- # Email MFA flow - skip if this is a reauth (user already authenticated)+ # Code-based verification - skip if this is a reauth (user already authenticated)if not was_authenticated_before_login_attempt:- email_mfa_sent = email_mfa_verifier.create_token_and_send_email_mfa_verification(- request, user, next_url+ code_based_verification_sent = code_based_verifier.create_and_send_code_based_verification(+ request, user)- if email_mfa_sent:+ if code_based_verification_sent:# Increment the resend throttle counter so the initial send counts towards the limit- resend_throttle = EmailMFAResendThrottle()+ resend_throttle = CodeBasedVerificationResendThrottle()resend_throttle.allow_request(request, None) # type: ignore[arg-type]- raise EmailMFARequired(user.email)+ raise CodeBasedVerificationRequired(user.email)else:- # if we failed to send the email, we should fall through to allow login without MFA+ # if we failed to send the email, we should fall through to allow login without code-based verificationpasslogin(request, user, backend="django.contrib.auth.backends.ModelBackend")@@ -802,54 +807,74 @@ class TwoFactorPasskeyViewSet(NonCreatingViewSetMixin, viewsets.GenericViewSet):return Response(json.loads(options_to_json(options)))-class EmailMFASerializer(serializers.Serializer):- email = serializers.EmailField()- token = serializers.CharField()+class CodeBasedVerificationSerializer(serializers.Serializer):+ code = serializers.CharField(help_text="The 6-digit verification code emailed to the user.")+ email = serializers.EmailField(+ required=False,+ help_text="Email the code was sent to. Informational; the pending login session identifies the user.",+ )-class EmailMFAViewSet(NonCreatingViewSetMixin, viewsets.GenericViewSet):- """Handle email MFA link verification"""+class CodeBasedVerificationViewSet(NonCreatingViewSetMixin, viewsets.GenericViewSet):+ """Verify the emailed login code against the pending login session and complete login."""- serializer_class = EmailMFASerializer+ serializer_class = CodeBasedVerificationSerializerqueryset = User.objects.none()permission_classes = (permissions.AllowAny,)- throttle_classes = [EmailMFAThrottle]+ throttle_classes = [CodeBasedVerificationThrottle]def create(self, request: Request, *args: Any, **kwargs: Any) -> Response:- """Verify email MFA token from link and log user in"""- email = request.data.get("email")- token = request.data.get("token")- validation_error = serializers.ValidationError(- {"token": ["This verification link is invalid or has expired."]}, code="invalid_token"+ """Verify the 6-digit code against the pending login session and log the user in."""+ invalid_error = serializers.ValidationError(+ {"code": ["This code is invalid or has expired."]}, code="invalid_code")- mfa_logger.info("Email MFA verification attempt", token=_obfuscate_token(token))+ if not code_based_verifier.has_pending_code_based_verification(request):+ raise serializers.ValidationError(+ {"detail": "No pending verification. Please log in again."},+ code="no_pending_verification",+ )- try:- user = User.objects.filter(is_active=True, email=email).get()- except User.DoesNotExist:+ # Reserve this attempt atomically before doing anything else, so concurrent guesses can't all+ # observe the same count and exceed the cap. `attempts` includes the current attempt.+ attempts = code_based_verifier.reserve_attempt(request)+ if attempts > CODE_MAX_ATTEMPTS:mfa_logger.warning(- "Email MFA verification failed: user not found or inactive",- token=_obfuscate_token(token),+ "Code-based verification locked out",+ user_id=code_based_verifier.get_pending_code_based_verification_user_id(request),+ attempts=attempts,+ )+ LOGIN_CODE_VERIFICATION_COUNTER.labels(result="locked_out").inc()+ code_based_verifier.clear_pending(request)+ raise serializers.ValidationError(+ {"detail": "Too many incorrect attempts. Please log in again."},+ code="too_many_attempts",)- raise validation_error- if not email_mfa_token_generator.check_token(user, token):- raise validation_error+ code = request.data.get("code")+ user_id = code_based_verifier.get_pending_code_based_verification_user_id(request)+ try:+ user = User.objects.get(pk=user_id, is_active=True)+ except User.DoesNotExist:+ code_based_verifier.clear_pending(request)+ raise invalid_error++ if not code or not code_based_verifier.check_code(request, user, code):+ mfa_logger.warning("Code-based verification attempt failed", user_id=user.pk, attempt=attempts)+ LOGIN_CODE_VERIFICATION_COUNTER.labels(result="invalid").inc()+ raise invalid_error- # Token valid - complete login+ # Code valid - invalidate the pending state and complete login.+ code_based_verifier.clear_pending(request)login(request, user, backend="django.contrib.auth.backends.ModelBackend")set_two_factor_verified_in_session(request)report_user_logged_in(user, social_provider="")- mfa_logger.info(- "Email MFA login successful",- user_id=user.pk,- token=_obfuscate_token(token),- )+ mfa_logger.info("Code-based verification successful", user_id=user.pk)+ LOGIN_CODE_VERIFICATION_COUNTER.labels(result="success").inc()# Always set remember device cookie (30 days), same as TOTP 2FAcookie_key = REMEMBER_COOKIE_PREFIX + str(uuid4())- cookie_value = get_remember_device_cookie(user=user, otp_device_id="email_mfa")+ cookie_value = get_remember_device_cookie(user=user, otp_device_id="code_based_verification")response = Response({"success": True})response.set_cookie(cookie_key,@@ -872,28 +897,26 @@ class EmailMFAViewSet(NonCreatingViewSetMixin, viewsets.GenericViewSet):return response- @action(detail=False, methods=["post"], throttle_classes=[EmailMFAResendThrottle])+ @action(detail=False, methods=["post"], throttle_classes=[CodeBasedVerificationResendThrottle])def resend(self, request: Request) -> Response:- """Resend email MFA link"""- if not email_mfa_verifier.has_pending_email_mfa_verification(request):+ """Resend a fresh verification code, invalidating the previous one."""+ if not code_based_verifier.has_pending_code_based_verification(request):raise serializers.ValidationError(- {"detail": "No pending email MFA verification found."}, code="no_pending_verification"+ {"detail": "No pending verification found."}, code="no_pending_verification")try:- user = User.objects.get(pk=email_mfa_verifier.get_pending_email_mfa_verification_user_id(request))+ user = User.objects.get(pk=code_based_verifier.get_pending_code_based_verification_user_id(request))except User.DoesNotExist:raise serializers.ValidationError({"detail": "User not found."}, code="user_not_found")- email_mfa_sent = email_mfa_verifier.create_token_and_send_email_mfa_verification(- request, user, request.session.get("email_mfa_next")- )- if not email_mfa_sent:+ if not code_based_verifier.create_and_send_code_based_verification(request, user, is_resend=True):raise serializers.ValidationError(- {"detail": "Could not send email MFA verification email."}, code="email_mfa_verification_email_failed"+ {"detail": "Could not send verification code."},+ code="code_based_verification_email_failed",)- return Response({"success": True, "message": "Verification email sent"})+ return Response({"success": True, "message": "Verification code sent"})class LoginPrecheckViewSet(NonCreatingViewSetMixin, viewsets.GenericViewSet):diff --git a/posthog/api/rest_router.py b/posthog/api/rest_router.pyindex fe65b49db14b..00e5724a55a3 100644--- a/posthog/api/rest_router.py+++ b/posthog/api/rest_router.py@@ -405,7 +405,9 @@ router.register(r"login", authentication.LoginViewSet, "login")router.register(r"login/dev", authentication.DevLoginViewSet, "login_dev")router.register(r"login/token", authentication.TwoFactorViewSet, "login_token")router.register(r"login/precheck", authentication.LoginPrecheckViewSet, "login_precheck")-router.register(r"login/email-mfa", authentication.EmailMFAViewSet, "login_email_mfa")+router.register(+ r"login/code-based-verification", authentication.CodeBasedVerificationViewSet, "login_code_based_verification"+)router.register(r"login/2fa/passkey", authentication.TwoFactorPasskeyViewSet, "login_2fa_passkey")router.register(r"webauthn/register", webauthn.WebAuthnRegistrationViewSet, "webauthn_register")router.register(r"webauthn/signup-register", webauthn.WebAuthnSignupRegistrationViewSet, "webauthn_signup_register")diff --git a/posthog/api/test/test_code_based_verification.py b/posthog/api/test/test_code_based_verification.pynew file mode 100644index 000000000000..3fef17685d71--- /dev/null+++ b/posthog/api/test/test_code_based_verification.py@@ -0,0 +1,156 @@+from contextlib import contextmanager++import pytest+from freezegun import freeze_time+from posthog.test.base import APIBaseTest+from unittest.mock import patch++from django_otp.plugins.otp_totp.models import TOTPDevice+from rest_framework import status++from posthog.helpers.email_utils import ESPSuppressionResult+from posthog.helpers.two_factor_session import CODE_MAX_ATTEMPTS++VERIFY_URL = "/api/login/code-based-verification/"+RESEND_URL = "/api/login/code-based-verification/resend/"+++def mock_esp_not_suppressed(*args, **kwargs):+ return ESPSuppressionResult(is_suppressed=False, from_cache=False)+++@contextmanager+def enable_code_sending():+ """Force the code path on (bypass the dev/ESP/email-availability short-circuits) and capture the sent code."""+ with (+ patch("posthog.helpers.two_factor_session.check_esp_suppression", side_effect=mock_esp_not_suppressed),+ patch("posthog.helpers.two_factor_session.is_email_available", return_value=True),+ patch("posthog.helpers.two_factor_session.is_http_email_service_available", return_value=True),+ patch("posthog.tasks.email.send_code_based_verification") as mock_send,+ ):+ yield mock_send+++class TestCodeBasedVerificationAPI(APIBaseTest):+ CONFIG_AUTO_LOGIN = False++ def _trigger(self, mock_send) -> str:+ """Log in with password to trigger the code, returning the 6-digit code that was emailed."""+ 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"], "code_based_verification_required")+ return mock_send.call_args[0][1]++ @pytest.mark.disable_mock_code_based_verifier+ def test_login_without_totp_emails_a_six_digit_code_and_does_not_log_in(self):+ with enable_code_sending() as mock_send:+ code = self._trigger(mock_send)++ self.assertEqual(mock_send.call_args[0][0], self.user.id)+ self.assertRegex(code, r"^\d{6}$")+ # Not logged in until the code is verified.+ self.assertEqual(self.client.get("/api/users/@me/").status_code, status.HTTP_401_UNAUTHORIZED)++ @pytest.mark.disable_mock_code_based_verifier+ def test_correct_code_logs_in_and_remembers_device(self):+ with enable_code_sending() as mock_send:+ code = self._trigger(mock_send)+ response = self.client.post(VERIFY_URL, {"code": code})+ self.assertEqual(response.status_code, status.HTTP_200_OK)+ self.assertEqual(response.json(), {"success": True})+ self.assertTrue(any(name.startswith("remember-cookie_") for name in response.cookies))++ self.assertEqual(self.client.get("/api/users/@me/").status_code, status.HTTP_200_OK)++ # Remembered device skips the code on the next login.+ self.client.post("/logout")+ response = self.client.post("/api/login", {"email": self.CONFIG_EMAIL, "password": self.CONFIG_PASSWORD})+ self.assertEqual(response.status_code, status.HTTP_200_OK)++ @pytest.mark.disable_mock_code_based_verifier+ def test_wrong_code_is_rejected_but_correct_code_still_works(self):+ with enable_code_sending() as mock_send:+ code = self._trigger(mock_send)+ wrong = "000000" if code != "000000" else "111111"++ response = self.client.post(VERIFY_URL, {"code": wrong})+ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)+ self.assertEqual(response.json()["code"], "invalid_code")+ self.assertEqual(self.client.get("/api/users/@me/").status_code, status.HTTP_401_UNAUTHORIZED)++ # A subsequent correct code (still under the attempt cap) succeeds.+ self.assertEqual(self.client.post(VERIFY_URL, {"code": code}).status_code, status.HTTP_200_OK)++ @pytest.mark.disable_mock_code_based_verifier+ def test_locks_out_after_max_attempts_even_with_correct_code(self):+ with enable_code_sending() as mock_send:+ code = self._trigger(mock_send)+ wrong = "000000" if code != "000000" else "111111"++ for _ in range(CODE_MAX_ATTEMPTS):+ self.assertEqual(self.client.post(VERIFY_URL, {"code": wrong}).status_code, status.HTTP_400_BAD_REQUEST)++ # The cap is now hit: even the correct code is refused and the pending state is cleared.+ response = self.client.post(VERIFY_URL, {"code": code})+ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)+ self.assertEqual(response.json()["code"], "too_many_attempts")++ @pytest.mark.disable_mock_code_based_verifier+ def test_expired_code_is_rejected(self):+ with freeze_time("2024-01-01T10:00:00") as frozen, enable_code_sending() as mock_send:+ code = self._trigger(mock_send)+ frozen.move_to("2024-01-01T10:10:01") # > 10 minute TTL+ response = self.client.post(VERIFY_URL, {"code": code})+ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)+ self.assertEqual(response.json()["code"], "invalid_code")++ @pytest.mark.disable_mock_code_based_verifier+ def test_verify_without_pending_login_is_rejected(self):+ response = self.client.post(VERIFY_URL, {"code": "123456"})+ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)+ self.assertEqual(response.json()["code"], "no_pending_verification")++ @pytest.mark.disable_mock_code_based_verifier+ def test_totp_user_gets_2fa_not_code_based_verification(self):+ TOTPDevice.objects.create(user=self.user, name="default")+ with enable_code_sending() as mock_send:+ 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"], "2fa_required")+ mock_send.assert_not_called()++ @pytest.mark.disable_mock_code_based_verifier+ def test_resend_issues_a_fresh_code_and_invalidates_the_previous_one(self):+ with freeze_time("2024-01-01T10:00:00") as frozen, enable_code_sending() as mock_send:+ first_code = self._trigger(mock_send)+ frozen.move_to("2024-01-01T10:01:01") # past the 1/min resend throttle+ self.assertEqual(self.client.post(RESEND_URL).status_code, status.HTTP_200_OK)+ second_code = mock_send.call_args[0][1]++ self.assertNotEqual(first_code, second_code)+ # The superseded code no longer works; the fresh one does.+ self.assertEqual(+ self.client.post(VERIFY_URL, {"code": first_code}).status_code, status.HTTP_400_BAD_REQUEST+ )+ self.assertEqual(self.client.post(VERIFY_URL, {"code": second_code}).status_code, status.HTTP_200_OK)++ @pytest.mark.disable_mock_code_based_verifier+ def test_resend_does_not_reset_the_failed_attempt_cap(self):+ with freeze_time("2024-01-01T10:00:00") as frozen, enable_code_sending() as mock_send:+ code = self._trigger(mock_send)+ wrong = "000000" if code != "000000" else "111111"++ # Use up all but one of the attempt budget, then resend to try to reset the counter.+ for _ in range(CODE_MAX_ATTEMPTS - 1):+ self.assertEqual(self.client.post(VERIFY_URL, {"code": wrong}).status_code, status.HTTP_400_BAD_REQUEST)++ frozen.move_to("2024-01-01T10:01:01") # past the 1/min resend throttle+ self.assertEqual(self.client.post(RESEND_URL).status_code, status.HTTP_200_OK)+ fresh_code = mock_send.call_args[0][1]++ # The resend must not have reset the budget: one more wrong guess hits the cap, and even+ # the freshly-issued correct code is then refused - so the cap can't be replayed in batches.+ self.assertEqual(self.client.post(VERIFY_URL, {"code": wrong}).status_code, status.HTTP_400_BAD_REQUEST)+ response = self.client.post(VERIFY_URL, {"code": fresh_code})+ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)+ self.assertEqual(response.json()["code"], "too_many_attempts")diff --git a/posthog/api/test/test_email_mfa.py b/posthog/api/test/test_email_mfa.pydeleted file mode 100644index e71945b43734..000000000000--- a/posthog/api/test/test_email_mfa.py+++ /dev/null@@ -1,438 +0,0 @@-import pytest-from freezegun import freeze_time-from posthog.test.base import APIBaseTest-from unittest.mock import patch--from django_otp.plugins.otp_totp.models import TOTPDevice-from parameterized import parameterized-from rest_framework import status--from posthog.helpers.email_utils import ESPSuppressionResult-from posthog.models.user import User--VALID_TEST_PASSWORD = "mighty-strong-secure-1337!!"---def mock_esp_not_suppressed(*args, **kwargs):- return ESPSuppressionResult(is_suppressed=False, from_cache=False)---class TestEmailMFAAPI(APIBaseTest):- CONFIG_AUTO_LOGIN = False-- @pytest.mark.disable_mock_email_mfa_verifier- @patch("posthog.helpers.two_factor_session.check_esp_suppression", side_effect=mock_esp_not_suppressed)- @patch("posthog.tasks.email.send_email_mfa_link")- @patch("posthog.helpers.two_factor_session.is_email_available", return_value=True)- @patch("posthog.helpers.two_factor_session.is_http_email_service_available", return_value=True)- def test_login_without_totp_triggers_email_mfa(- self,- mock_is_http_email_available,- mock_is_email_available,- mock_send_email,- mock_esp_suppression,- ):- response = self.client.post("/api/login", {"email": self.CONFIG_EMAIL, "password": self.CONFIG_PASSWORD})- self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)- response_data = response.json()- self.assertEqual(response_data["code"], "email_mfa_required")- self.assertEqual(response_data["detail"], self.user.email)-- # Assert user is not logged in yet- response = self.client.get("/api/users/@me/")- self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)-- # Assert email task was called- mock_send_email.assert_called_once()- call_args = mock_send_email.call_args- self.assertEqual(call_args[0][0], self.user.id)- self.assertIsNotNone(call_args[0][1]) # Token should be present-- @parameterized.expand(- [- # A relative `next` (e.g. an /oauth/authorize continuation) is forwarded into the link- # so the emailed login-verification link resumes the flow even in a different browser.- ("safe_relative_next", "/oauth/authorize/?client_id=x", "/oauth/authorize/?client_id=x"),- # An off-origin `next` must be dropped, never embedded into the emailed link.- ("unsafe_off_origin_next", "//evil.example.com/steal", None),- ]- )- @pytest.mark.disable_mock_email_mfa_verifier- @patch("posthog.helpers.two_factor_session.check_esp_suppression", side_effect=mock_esp_not_suppressed)- @patch("posthog.tasks.email.send_email_mfa_link")- @patch("posthog.helpers.two_factor_session.is_email_available", return_value=True)- @patch("posthog.helpers.two_factor_session.is_http_email_service_available", return_value=True)- def test_email_mfa_link_carries_safe_next(- self,- _name,- next_input,- expected,- mock_is_http_email_available,- mock_is_email_available,- mock_send_email,- mock_esp_suppression,- ):- self.client.post(- "/api/login",- {"email": self.CONFIG_EMAIL, "password": self.CONFIG_PASSWORD, "next": next_input},- )- self.assertEqual(mock_send_email.call_args[0][2], expected)-- @pytest.mark.disable_mock_email_mfa_verifier- @patch("posthog.helpers.two_factor_session.check_esp_suppression", side_effect=mock_esp_not_suppressed)- @patch("posthog.tasks.email.send_email_mfa_link")- @patch("posthog.helpers.two_factor_session.is_email_available", return_value=True)- @patch("posthog.helpers.two_factor_session.is_http_email_service_available", return_value=True)- def test_email_mfa_resend_reuses_next(- self,- mock_is_http_email_available,- mock_is_email_available,- mock_send_email,- mock_esp_suppression,- ):- with freeze_time("2023-01-01T10:00:00"):- self.client.post(- "/api/login",- {"email": self.CONFIG_EMAIL, "password": self.CONFIG_PASSWORD, "next": "/oauth/authorize/?client_id=x"},- )- self.assertEqual(mock_send_email.call_args[0][2], "/oauth/authorize/?client_id=x")-- # A resent link must resume the same destination, recovered from the session.- with freeze_time("2023-01-01T10:01:01"):- mock_send_email.reset_mock()- response = self.client.post("/api/login/email-mfa/resend/")- self.assertEqual(response.status_code, status.HTTP_200_OK)- self.assertEqual(mock_send_email.call_args[0][2], "/oauth/authorize/?client_id=x")-- @pytest.mark.disable_mock_email_mfa_verifier- @patch("posthog.helpers.two_factor_session.check_esp_suppression", side_effect=mock_esp_not_suppressed)- @patch("posthog.tasks.email.send_email_mfa_link")- @patch("posthog.helpers.two_factor_session.is_email_available", return_value=True)- @patch("posthog.helpers.two_factor_session.is_http_email_service_available", return_value=True)- def test_email_mfa_verification_success_and_always_remembers_device(- self,- mock_is_http_email_available,- mock_is_email_available,- mock_send_email,- mock_esp_suppression,- ):- # Trigger email MFA- self.client.post("/api/login", {"email": self.CONFIG_EMAIL, "password": self.CONFIG_PASSWORD})-- # Get the token that was generated- token = mock_send_email.call_args[0][1]-- # Verify the token- response = self.client.post(- "/api/login/email-mfa/",- {"email": self.user.email, "token": token},- )- self.assertEqual(response.status_code, status.HTTP_200_OK)- self.assertEqual(response.json(), {"success": True})-- # Check that remember cookie was ALWAYS set (same as TOTP 2FA behavior)- cookies = response.cookies- remember_cookie_found = False- for cookie_name in cookies.keys():- if cookie_name.startswith("remember-cookie_"):- remember_cookie_found = True- break- self.assertTrue(remember_cookie_found, "Remember device cookie should always be set")-- # Assert user is now logged in- response = self.client.get("/api/users/@me/")- self.assertEqual(response.status_code, status.HTTP_200_OK)- self.assertEqual(response.json()["email"], self.user.email)-- # Logout and try to login again - should NOT require email MFA (remembered for 30 days)- self.client.post("/logout", follow=True)- response = self.client.post("/api/login", {"email": self.CONFIG_EMAIL, "password": self.CONFIG_PASSWORD})- self.assertEqual(response.status_code, status.HTTP_200_OK)- self.assertEqual(response.json(), {"success": True})-- @pytest.mark.disable_mock_email_mfa_verifier- @patch("posthog.helpers.two_factor_session.check_esp_suppression", side_effect=mock_esp_not_suppressed)- @patch("posthog.tasks.email.send_email_mfa_link")- @patch("posthog.helpers.two_factor_session.is_email_available", return_value=True)- @patch("posthog.helpers.two_factor_session.is_http_email_service_available", return_value=True)- def test_email_mfa_verification_with_invalid_token(- self,- mock_is_http_email_available,- mock_is_email_available,- mock_send_email,- mock_esp_suppression,- ):- # Trigger email MFA- self.client.post("/api/login", {"email": self.CONFIG_EMAIL, "password": self.CONFIG_PASSWORD})-- # Try to verify with invalid token- response = self.client.post(- "/api/login/email-mfa/",- {"email": self.user.email, "token": "invalid_token_123"},- )- self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)- response_data = response.json()- if isinstance(response_data.get("detail"), dict):- self.assertIn("invalid or has expired", response_data["detail"]["token"][0])- else:- self.assertIn("invalid or has expired", response_data["detail"])-- # Assert user is still not logged in- response = self.client.get("/api/users/@me/")- self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)-- @pytest.mark.disable_mock_email_mfa_verifier- @patch("posthog.helpers.two_factor_session.check_esp_suppression", side_effect=mock_esp_not_suppressed)- @patch("posthog.tasks.email.send_email_mfa_link")- @patch("posthog.helpers.two_factor_session.is_email_available", return_value=True)- @patch("posthog.helpers.two_factor_session.is_http_email_service_available", return_value=True)- def test_email_mfa_token_expires_after_10_minutes(- self,- mock_is_http_email_available,- mock_is_email_available,- mock_send_email,- mock_esp_suppression,- ):- with freeze_time("2023-01-01T10:00:00"):- # Trigger email MFA- self.client.post("/api/login", {"email": self.CONFIG_EMAIL, "password": self.CONFIG_PASSWORD})- token = mock_send_email.call_args[0][1]-- # Try to verify after 11 minutes- with freeze_time("2023-01-01T10:11:00"):- response = self.client.post(- "/api/login/email-mfa/",- {"email": self.user.email, "token": token},- )- self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)- response_data = response.json()- # Check either nested format or flat format- if isinstance(response_data.get("detail"), dict):- self.assertIn("invalid or has expired", response_data["detail"]["token"][0])- else:- self.assertIn("invalid or has expired", response_data["detail"])-- @pytest.mark.disable_mock_email_mfa_verifier- @patch("posthog.helpers.two_factor_session.check_esp_suppression", side_effect=mock_esp_not_suppressed)- @patch("posthog.tasks.email.send_email_mfa_link")- @patch("posthog.helpers.two_factor_session.is_email_available", return_value=True)- @patch("posthog.helpers.two_factor_session.is_http_email_service_available", return_value=True)- def test_email_mfa_token_invalidated_after_use(- self,- mock_is_http_email_available,- mock_is_email_available,- mock_send_email,- mock_esp_suppression,- ):- # Trigger email MFA- self.client.post("/api/login", {"email": self.CONFIG_EMAIL, "password": self.CONFIG_PASSWORD})- token = mock_send_email.call_args[0][1]-- # Verify the token- response = self.client.post(- "/api/login/email-mfa/",- {"email": self.user.email, "token": token},- )- self.assertEqual(response.status_code, status.HTTP_200_OK)-- # Logout- self.client.post("/logout", follow=True)-- # Try to reuse the same token (but should be blocked by remember cookie first)- # Clear cookies to test token invalidation- self.client.cookies.clear()- response = self.client.post(- "/api/login/email-mfa/",- {"email": self.user.email, "token": token},- )- self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)- response_data = response.json()- if isinstance(response_data.get("detail"), dict):- self.assertIn("invalid or has expired", response_data["detail"]["token"][0])- else:- self.assertIn("invalid or has expired", response_data["detail"])-- @pytest.mark.disable_mock_email_mfa_verifier- @patch("posthog.tasks.email.send_email_mfa_link")- def test_email_mfa_with_nonexistent_user(self, mock_send_email):- # Try to verify with non-existent user- response = self.client.post(- "/api/login/email-mfa/",- {"email": "[email protected]", "token": "some_token"},- )- self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)- response_data = response.json()- if isinstance(response_data.get("detail"), dict):- self.assertIn("invalid or has expired", response_data["detail"]["token"][0])- else:- self.assertIn("invalid or has expired", response_data["detail"])-- @pytest.mark.disable_mock_email_mfa_verifier- @patch("posthog.helpers.two_factor_session.check_esp_suppression", side_effect=mock_esp_not_suppressed)- @patch("posthog.tasks.email.send_email_mfa_link")- @patch("posthog.helpers.two_factor_session.is_email_available", return_value=True)- @patch("posthog.helpers.two_factor_session.is_http_email_service_available", return_value=True)- def test_login_with_totp_does_not_trigger_email_mfa(- self,- mock_is_http_email_available,- mock_is_email_available,- mock_send_email,- mock_esp_suppression,- ):- # Create TOTP device for user- TOTPDevice.objects.create(user=self.user, name="default")-- response = self.client.post("/api/login", {"email": self.CONFIG_EMAIL, "password": self.CONFIG_PASSWORD})-- # Should trigger TOTP 2FA, not email MFA- self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)- self.assertEqual(response.json()["code"], "2fa_required")-- # Email task should not have been called- mock_send_email.assert_not_called()-- @pytest.mark.disable_mock_email_mfa_verifier- @patch("posthog.helpers.two_factor_session.check_esp_suppression", side_effect=mock_esp_not_suppressed)- @patch("posthog.tasks.email.send_email_mfa_link")- @patch("posthog.helpers.two_factor_session.is_email_available", return_value=True)- @patch("posthog.helpers.two_factor_session.is_http_email_service_available", return_value=True)- def test_email_mfa_resend_success(- self,- mock_is_http_email_available,- mock_is_email_available,- mock_send_email,- mock_esp_suppression,- ):- with freeze_time("2023-01-01T10:00:00"):- # Trigger email MFA- self.client.post("/api/login", {"email": self.CONFIG_EMAIL, "password": self.CONFIG_PASSWORD})- self.assertEqual(mock_send_email.call_count, 1)-- # Resend after 61 seconds- with freeze_time("2023-01-01T10:01:01"):- response = self.client.post("/api/login/email-mfa/resend/")- self.assertEqual(response.status_code, status.HTTP_200_OK)- self.assertEqual(response.json(), {"success": True, "message": "Verification email sent"})-- # Assert email task was called again- self.assertEqual(mock_send_email.call_count, 2)-- @pytest.mark.disable_mock_email_mfa_verifier- @patch("posthog.helpers.two_factor_session.check_esp_suppression", side_effect=mock_esp_not_suppressed)- @patch("posthog.tasks.email.send_email_mfa_link")- @patch("posthog.helpers.two_factor_session.is_email_available", return_value=True)- @patch("posthog.helpers.two_factor_session.is_http_email_service_available", return_value=True)- def test_email_mfa_resend_throttle(- self,- mock_is_http_email_available,- mock_is_email_available,- mock_send_email,- mock_esp_suppression,- ):- with freeze_time("2023-01-01T10:00:00"):- # Trigger email MFA - this counts towards the resend throttle- self.client.post("/api/login", {"email": self.CONFIG_EMAIL, "password": self.CONFIG_PASSWORD})- self.assertEqual(mock_send_email.call_count, 1)-- # First resend immediately after should be throttled (initial send already used the 1/minute limit)- response = self.client.post("/api/login/email-mfa/resend/")- self.assertEqual(response.status_code, status.HTTP_429_TOO_MANY_REQUESTS)- self.assertIn("Request was throttled", response.json()["detail"])-- # Email task should still only have been called once (resend was blocked)- self.assertEqual(mock_send_email.call_count, 1)-- # After 61 seconds, resend should succeed- with freeze_time("2023-01-01T10:01:01"):- response = self.client.post("/api/login/email-mfa/resend/")- self.assertEqual(response.status_code, status.HTTP_200_OK)- self.assertEqual(mock_send_email.call_count, 2)-- @pytest.mark.disable_mock_email_mfa_verifier- @patch("posthog.tasks.email.send_email_mfa_link")- def test_email_mfa_resend_without_pending_verification(self, mock_send_email):- # Try to resend without triggering MFA first- response = self.client.post("/api/login/email-mfa/resend/")- self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)- self.assertIn("No pending email MFA verification found", response.json()["detail"])-- # Email task should not have been called- mock_send_email.assert_not_called()-- @pytest.mark.disable_mock_email_mfa_verifier- @patch("posthog.helpers.two_factor_session.check_esp_suppression", side_effect=mock_esp_not_suppressed)- @patch("posthog.tasks.email.send_email_mfa_link")- @patch("posthog.helpers.two_factor_session.is_email_available", return_value=True)- @patch("posthog.helpers.two_factor_session.is_http_email_service_available", return_value=True)- def test_email_mfa_skipped_during_reauth(- self,- mock_is_http_email_available,- mock_is_email_available,- mock_send_email,- mock_esp_suppression,- ):- # First, log in normally (triggers email MFA)- response = self.client.post("/api/login", {"email": self.CONFIG_EMAIL, "password": self.CONFIG_PASSWORD})- self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)- response_data = response.json()- self.assertEqual(response_data["code"], "email_mfa_required")-- # Verify the first email was sent- self.assertEqual(mock_send_email.call_count, 1)- token = mock_send_email.call_args[0][1]-- # Complete the email MFA verification to log in- response = self.client.post("/api/login/email-mfa/", {"email": self.user.email, "token": token})- self.assertEqual(response.status_code, status.HTTP_200_OK)-- # User is now logged in - verify- response = self.client.get("/api/users/@me/")- self.assertEqual(response.status_code, status.HTTP_200_OK)-- # This covers the case where email MFA is enabled after users are already logged in- session = self.client.session- session.pop("two_factor_verified", None)- session.save()-- # Now try to reauth while already logged in (should skip email MFA)- response = self.client.post("/api/login", {"email": self.CONFIG_EMAIL, "password": self.CONFIG_PASSWORD})- self.assertEqual(response.status_code, status.HTTP_200_OK)-- # Email should still only have been sent once (not a second time for reauth)- self.assertEqual(mock_send_email.call_count, 1)-- @pytest.mark.disable_mock_email_mfa_verifier- @patch("posthog.helpers.two_factor_session.check_esp_suppression", side_effect=mock_esp_not_suppressed)- @patch("posthoganalytics.feature_enabled", return_value=True)- @patch("posthog.tasks.email.send_email_mfa_link")- @patch("posthog.helpers.two_factor_session.is_email_available", return_value=True)- @patch("posthog.helpers.two_factor_session.is_http_email_service_available", return_value=True)- def test_email_mfa_enforced_when_different_user_already_authenticated(- self,- mock_is_http_email_available,- mock_is_email_available,- mock_send_email,- mock_feature_enabled,- mock_esp_suppression,- ):- other_user = User.objects.create_and_join(- organization=self.organization,- email="[email protected]",- password="other-user-password-1337!!",- )-- # A different user is already authenticated in this session- self.client.force_login(other_user)- response = self.client.get("/api/users/@me/")- self.assertEqual(response.status_code, status.HTTP_200_OK)-- # Login as the original user with a different session identity- response = self.client.post(- "/api/login",- {"email": self.CONFIG_EMAIL, "password": self.CONFIG_PASSWORD},- )-- # Email MFA must still be enforced- self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)- self.assertEqual(response.json()["code"], "email_mfa_required")- mock_send_email.assert_called_once()diff --git a/posthog/conftest.py b/posthog/conftest.pyindex a4d52b82bb52..ff431c6cb196 100644--- a/posthog/conftest.py+++ b/posthog/conftest.py@@ -470,19 +470,19 @@ def mock_two_factor_sso_enforcement_check(request, mocker):@pytest.fixture(autouse=True)-def mock_email_mfa_verifier(request, mocker):+def mock_code_based_verifier(request, mocker):"""- Mock the EmailMFAVerifier.should_send_email_mfa_verification method to return False for all tests.- Can be disabled by using @pytest.mark.disable_mock_email_mfa_verifier decorator.+ Mock the CodeBasedVerifier.should_send_code_based_verification method to return False for all tests.+ Can be disabled by using @pytest.mark.disable_mock_code_based_verifier decorator."""- from posthog.helpers.two_factor_session import EmailMFACheckResult+ from posthog.helpers.two_factor_session import CodeBasedVerificationCheckResult- if "disable_mock_email_mfa_verifier" in request.keywords:+ if "disable_mock_code_based_verifier" in request.keywords:returnmocker.patch(- "posthog.helpers.two_factor_session.EmailMFAVerifier.should_send_email_mfa_verification",- return_value=EmailMFACheckResult(should_send=False),+ "posthog.helpers.two_factor_session.CodeBasedVerifier.should_send_code_based_verification",+ return_value=CodeBasedVerificationCheckResult(should_send=False),)diff --git a/posthog/email.py b/posthog/email.pyindex 062b77c0af31..39b6b79b8079 100644--- a/posthog/email.py+++ b/posthog/email.py@@ -128,7 +128,7 @@ CUSTOMER_IO_TEMPLATE_ID_MAP = {"password_changed": "42","login_notification": "44","personal_api_key_exposed": "45",- "email_mfa_link": "48",+ "code_based_verification": "75","project_secret_api_key_exposed": "49","oauth_token_exposed": "50","passkey_added": "51",diff --git a/posthog/helpers/email_utils.py b/posthog/helpers/email_utils.pyindex 35cb4d8d8d85..a2ea1d788f9c 100644--- a/posthog/helpers/email_utils.py+++ b/posthog/helpers/email_utils.py@@ -393,11 +393,11 @@ def _hash_email(email: str) -> str:def _get_esp_suppression_cache_key(email: str) -> str:- return f"email_mfa_suppressed:{_hash_email(email)}"+ return f"code_based_verification_suppressed:{_hash_email(email)}"def _get_esp_suppression_error_cache_key(email: str) -> str:- return f"email_mfa_suppressed_error:{_hash_email(email)}"+ return f"code_based_verification_suppressed_error:{_hash_email(email)}"def _capture_esp_suppression_analytics(diff --git a/posthog/helpers/tests/test_email_utils.py b/posthog/helpers/tests/test_email_utils.pyindex 890a767dacf3..d295d6cdbada 100644--- a/posthog/helpers/tests/test_email_utils.py+++ b/posthog/helpers/tests/test_email_utils.py@@ -188,7 +188,7 @@ class TestESPSuppressionCheck(SimpleTestCase):key_upper = _get_esp_suppression_cache_key("[email protected]")key_other = _get_esp_suppression_cache_key("[email protected]")- self.assertTrue(key_lower.startswith("email_mfa_suppressed:"))+ self.assertTrue(key_lower.startswith("code_based_verification_suppressed:"))self.assertEqual(key_lower, key_upper)self.assertNotEqual(key_lower, key_other)self.assertNotIn("@", key_lower)diff --git a/posthog/helpers/tests/test_two_factor_session.py b/posthog/helpers/tests/test_two_factor_session.pyindex a98c94e79083..ee39e857eb85 100644--- a/posthog/helpers/tests/test_two_factor_session.py+++ b/posthog/helpers/tests/test_two_factor_session.py@@ -9,18 +9,18 @@ from parameterized import parameterizedfrom posthog.helpers.email_utils import ESPSuppressionReason, ESPSuppressionResultfrom posthog.helpers.two_factor_session import (- MAX_EMAIL_MFA_GLOBAL_DISABLE_TTL_SECONDS,- EmailMFACheckResult,- EmailMFAVerifier,- clear_email_mfa_global_disable,- get_email_mfa_global_disable,- is_email_mfa_globally_disabled,- set_email_mfa_global_disable,+ MAX_CODE_BASED_VERIFICATION_GLOBAL_DISABLE_TTL_SECONDS,+ CodeBasedVerificationCheckResult,+ CodeBasedVerifier,+ clear_code_based_verification_global_disable,+ get_code_based_verification_global_disable,+ is_code_based_verification_globally_disabled,+ set_code_based_verification_global_disable,)[email protected]_mock_email_mfa_verifier-class TestEmailMFAVerifierSuppressionIntegration(SimpleTestCase):[email protected]_mock_code_based_verifier+class TestCodeBasedVerifierSuppressionIntegration(SimpleTestCase):def setUp(self):self.mock_user = MagicMock()self.mock_user.pk = 123@@ -34,7 +34,7 @@ class TestEmailMFAVerifierSuppressionIntegration(SimpleTestCase):@patch("posthog.helpers.two_factor_session.is_http_email_service_available")@patch("posthog.helpers.two_factor_session.posthoganalytics.feature_enabled")@patch("posthog.helpers.two_factor_session.check_esp_suppression")- def test_suppressed_user_skips_email_mfa(+ def test_suppressed_user_skips_code_based_verification(self, mock_check_suppression, mock_feature_enabled, mock_http_available, mock_email_available, mock_dev_mode):mock_dev_mode.return_value = False@@ -45,8 +45,8 @@ class TestEmailMFAVerifierSuppressionIntegration(SimpleTestCase):is_suppressed=True, from_cache=False, reason=ESPSuppressionReason.SUPPRESSED)- verifier = EmailMFAVerifier()- result = verifier.should_send_email_mfa_verification(self.mock_user)+ verifier = CodeBasedVerifier()+ result = verifier.should_send_code_based_verification(self.mock_user)self.assertFalse(result.should_send)self.assertTrue(result.suppression_bypassed)@@ -57,7 +57,7 @@ class TestEmailMFAVerifierSuppressionIntegration(SimpleTestCase):@patch("posthog.helpers.two_factor_session.is_http_email_service_available")@patch("posthog.helpers.two_factor_session.posthoganalytics.feature_enabled")@patch("posthog.helpers.two_factor_session.check_esp_suppression")- def test_non_suppressed_user_proceeds_with_email_mfa(+ def test_non_suppressed_user_proceeds_with_code_based_verification(self, mock_check_suppression, mock_feature_enabled, mock_http_available, mock_email_available, mock_dev_mode):mock_dev_mode.return_value = False@@ -66,8 +66,8 @@ class TestEmailMFAVerifierSuppressionIntegration(SimpleTestCase):mock_feature_enabled.return_value = Truemock_check_suppression.return_value = ESPSuppressionResult(is_suppressed=False, from_cache=False, reason=None)- verifier = EmailMFAVerifier()- result = verifier.should_send_email_mfa_verification(self.mock_user)+ verifier = CodeBasedVerifier()+ result = verifier.should_send_code_based_verification(self.mock_user)self.assertTrue(result.should_send)self.assertFalse(result.suppression_bypassed)@@ -95,12 +95,12 @@ class TestEmailMFAVerifierSuppressionIntegration(SimpleTestCase):is_suppressed=True, from_cache=False, reason=ESPSuppressionReason.SUPPRESSED)- verifier = EmailMFAVerifier()- verifier.should_send_email_mfa_verification(self.mock_user)+ verifier = CodeBasedVerifier()+ verifier.should_send_code_based_verification(self.mock_user)mock_capture.assert_called_once()call_kwargs = mock_capture.call_args[1]- self.assertEqual(call_kwargs["event"], "email_mfa_bypassed_due_to_suppression")+ self.assertEqual(call_kwargs["event"], "code_based_verification_bypassed_due_to_suppression")self.assertEqual(call_kwargs["distinct_id"], str(self.mock_user.distinct_id))@patch("posthog.helpers.two_factor_session.is_dev_mode")@@ -126,8 +126,8 @@ class TestEmailMFAVerifierSuppressionIntegration(SimpleTestCase):is_suppressed=True, from_cache=True, reason=ESPSuppressionReason.SUPPRESSED)- verifier = EmailMFAVerifier()- verifier.should_send_email_mfa_verification(self.mock_user)+ verifier = CodeBasedVerifier()+ verifier.should_send_code_based_verification(self.mock_user)call_kwargs = mock_capture.call_args[1]self.assertEqual(call_kwargs["properties"]["reason"], ESPSuppressionReason.SUPPRESSED)@@ -156,8 +156,8 @@ class TestEmailMFAVerifierSuppressionIntegration(SimpleTestCase):is_suppressed=True, from_cache=False, reason=ESPSuppressionReason.API_FAILURE_FALLBACK)- verifier = EmailMFAVerifier()- result = verifier.should_send_email_mfa_verification(self.mock_user)+ verifier = CodeBasedVerifier()+ result = verifier.should_send_code_based_verification(self.mock_user)self.assertFalse(result.should_send)self.assertTrue(result.suppression_bypassed)@@ -172,7 +172,7 @@ class TestEmailMFAVerifierSuppressionIntegration(SimpleTestCase):@patch("posthog.helpers.two_factor_session.is_http_email_service_available")@patch("posthog.helpers.two_factor_session.posthoganalytics.feature_enabled")@patch("posthog.helpers.two_factor_session.check_esp_suppression")- def test_returns_email_mfa_check_result(+ def test_returns_code_based_verification_check_result(self, mock_check_suppression, mock_feature_enabled, mock_http_available, mock_email_available, mock_dev_mode):mock_dev_mode.return_value = False@@ -183,10 +183,10 @@ class TestEmailMFAVerifierSuppressionIntegration(SimpleTestCase):is_suppressed=True, from_cache=False, reason=ESPSuppressionReason.SUPPRESSED)- verifier = EmailMFAVerifier()- result = verifier.should_send_email_mfa_verification(self.mock_user)+ verifier = CodeBasedVerifier()+ result = verifier.should_send_code_based_verification(self.mock_user)- self.assertIsInstance(result, EmailMFACheckResult)+ self.assertIsInstance(result, CodeBasedVerificationCheckResult)self.assertFalse(result.should_send)@patch("posthog.helpers.two_factor_session.is_dev_mode")@@ -198,8 +198,8 @@ class TestEmailMFAVerifierSuppressionIntegration(SimpleTestCase):mock_email_available.return_value = Truemock_http_available.return_value = False- verifier = EmailMFAVerifier()- result = verifier.should_send_email_mfa_verification(self.mock_user)+ verifier = CodeBasedVerifier()+ result = verifier.should_send_code_based_verification(self.mock_user)self.assertFalse(result.should_send)self.assertTrue(result.suppression_bypassed)@@ -207,72 +207,82 @@ class TestEmailMFAVerifierSuppressionIntegration(SimpleTestCase):mock_capture.assert_called_once()call_kwargs = mock_capture.call_args[1]- self.assertEqual(call_kwargs["event"], "email_mfa_bypassed_due_to_suppression")+ self.assertEqual(call_kwargs["event"], "code_based_verification_bypassed_due_to_suppression")self.assertEqual(call_kwargs["properties"]["reason"], ESPSuppressionReason.NO_EMAIL_HTTP_SERVICE)-class TestEmailMFAGlobalDisable(SimpleTestCase):+class TestCodeBasedVerificationGlobalDisable(SimpleTestCase):def setUp(self):- clear_email_mfa_global_disable()+ clear_code_based_verification_global_disable()def tearDown(self):- clear_email_mfa_global_disable()+ clear_code_based_verification_global_disable()def test_not_disabled_by_default(self):- self.assertFalse(is_email_mfa_globally_disabled())- self.assertIsNone(get_email_mfa_global_disable())+ self.assertFalse(is_code_based_verification_globally_disabled())+ self.assertIsNone(get_code_based_verification_global_disable())def test_set_get_clear_round_trip(self):- set_email_mfa_global_disable(reason="email pipeline down", ttl_seconds=3600, disabled_by="[email protected]")+ set_code_based_verification_global_disable(+ reason="email pipeline down", ttl_seconds=3600, disabled_by="[email protected]"+ )- self.assertTrue(is_email_mfa_globally_disabled())- state = get_email_mfa_global_disable()+ self.assertTrue(is_code_based_verification_globally_disabled())+ state = get_code_based_verification_global_disable()assert state is not Noneself.assertEqual(state["reason"], "email pipeline down")self.assertEqual(state["disabled_by"], "[email protected]")self.assertIn("disabled_at", state)self.assertTrue(0 < state["expires_in_seconds"] <= 3600)- clear_email_mfa_global_disable()- self.assertFalse(is_email_mfa_globally_disabled())- self.assertIsNone(get_email_mfa_global_disable())+ clear_code_based_verification_global_disable()+ self.assertFalse(is_code_based_verification_globally_disabled())+ self.assertIsNone(get_code_based_verification_global_disable())def test_reason_is_stripped_and_required(self):with self.assertRaises(ValueError):- set_email_mfa_global_disable(reason=" ", ttl_seconds=3600, disabled_by="[email protected]")- self.assertFalse(is_email_mfa_globally_disabled())+ set_code_based_verification_global_disable(+ reason=" ", ttl_seconds=3600, disabled_by="[email protected]"+ )+ self.assertFalse(is_code_based_verification_globally_disabled())@parameterized.expand([("zero", 0),("negative", -1),- ("over_max", MAX_EMAIL_MFA_GLOBAL_DISABLE_TTL_SECONDS + 1),+ ("over_max", MAX_CODE_BASED_VERIFICATION_GLOBAL_DISABLE_TTL_SECONDS + 1),])def test_invalid_ttl_rejected(self, _name, ttl_seconds):with self.assertRaises(ValueError):- set_email_mfa_global_disable(reason="reason", ttl_seconds=ttl_seconds, disabled_by="[email protected]")- self.assertFalse(is_email_mfa_globally_disabled())+ set_code_based_verification_global_disable(+ reason="reason", ttl_seconds=ttl_seconds, disabled_by="[email protected]"+ )+ self.assertFalse(is_code_based_verification_globally_disabled())def test_max_ttl_accepted(self):- set_email_mfa_global_disable(- reason="reason", ttl_seconds=MAX_EMAIL_MFA_GLOBAL_DISABLE_TTL_SECONDS, disabled_by="[email protected]"+ set_code_based_verification_global_disable(+ reason="reason",+ ttl_seconds=MAX_CODE_BASED_VERIFICATION_GLOBAL_DISABLE_TTL_SECONDS,+ disabled_by="[email protected]",)- self.assertTrue(is_email_mfa_globally_disabled())+ self.assertTrue(is_code_based_verification_globally_disabled())- @pytest.mark.disable_mock_email_mfa_verifier- def test_global_disable_skips_email_mfa(self):+ @pytest.mark.disable_mock_code_based_verifier+ def test_global_disable_skips_code_based_verification(self):user = MagicMock()user.pk = 1user.email = "[email protected]"- set_email_mfa_global_disable(reason="email pipeline down", ttl_seconds=3600, disabled_by="[email protected]")- result = EmailMFAVerifier().should_send_email_mfa_verification(user)- self.assertEqual(result, EmailMFACheckResult(should_send=False))+ set_code_based_verification_global_disable(+ reason="email pipeline down", ttl_seconds=3600, disabled_by="[email protected]"+ )+ result = CodeBasedVerifier().should_send_code_based_verification(user)+ self.assertEqual(result, CodeBasedVerificationCheckResult(should_send=False))@patch("posthog.helpers.two_factor_session.get_client")def test_fails_closed_when_redis_unavailable(self, mock_get_client):mock_get_client.side_effect = Exception("redis unreachable")# Reads must not raise, and must default to "not disabled" so email MFA stays enforced.- self.assertFalse(is_email_mfa_globally_disabled())- self.assertIsNone(get_email_mfa_global_disable())+ self.assertFalse(is_code_based_verification_globally_disabled())+ self.assertIsNone(get_code_based_verification_global_disable())diff --git a/posthog/helpers/two_factor_session.py b/posthog/helpers/two_factor_session.pyindex ef3aff9426af..810ad8c099d7 100644--- a/posthog/helpers/two_factor_session.py+++ b/posthog/helpers/two_factor_session.py@@ -8,13 +8,13 @@ from django.conf import settingsfrom django.contrib.auth.models import AbstractBaseUserfrom django.contrib.auth.tokens import PasswordResetTokenGeneratorfrom django.http import HttpRequest-from django.utils.crypto import constant_time_compare-from django.utils.http import base36_to_int+from django.utils.crypto import constant_time_compare, salted_hmacimport structlogimport posthoganalyticsfrom loginas.utils import is_impersonated_sessionfrom posthoganalytics import capture_exception+from prometheus_client import Counterfrom rest_framework.exceptions import PermissionDeniedfrom two_factor.utils import default_device@@ -26,61 +26,63 @@ from posthog.models.webauthn_credential import WebauthnCredentialfrom posthog.redis import get_clientfrom posthog.settings.web import AUTHENTICATION_BACKENDS-EMAIL_MFA_BYPASS_REDIS_KEY = "email_mfa_bypass_emails"+CODE_BASED_VERIFICATION_BYPASS_REDIS_KEY = "code_based_verification_bypass_emails"-def is_email_mfa_bypass(email: str) -> bool:- return bool(get_client().sismember(EMAIL_MFA_BYPASS_REDIS_KEY, email.lower()))+def is_code_based_verification_bypass(email: str) -> bool:+ return bool(get_client().sismember(CODE_BASED_VERIFICATION_BYPASS_REDIS_KEY, email.lower()))-def add_email_mfa_bypass(email: str) -> None:- get_client().sadd(EMAIL_MFA_BYPASS_REDIS_KEY, email.lower())+def add_code_based_verification_bypass(email: str) -> None:+ get_client().sadd(CODE_BASED_VERIFICATION_BYPASS_REDIS_KEY, email.lower())-def remove_email_mfa_bypass(email: str) -> None:- get_client().srem(EMAIL_MFA_BYPASS_REDIS_KEY, email.lower())+def remove_code_based_verification_bypass(email: str) -> None:+ get_client().srem(CODE_BASED_VERIFICATION_BYPASS_REDIS_KEY, email.lower())-# Global kill-switch: when this Redis key is present, email MFA verification is skipped for every+# Global kill-switch: when this Redis key is present, code-based verification is skipped for every# user (e.g. while transactional email delivery is down and the verification link can't be# delivered). The key carries the reason/actor/timestamp and a mandatory TTL so it auto-re-enables.# Only the email factor is affected — TOTP and passkey 2FA are gated earlier in the login flow.-EMAIL_MFA_GLOBAL_DISABLE_REDIS_KEY = "email_mfa_global_disable"-MAX_EMAIL_MFA_GLOBAL_DISABLE_TTL_SECONDS = 7 * 24 * 60 * 60 # 7 days+CODE_BASED_VERIFICATION_GLOBAL_DISABLE_REDIS_KEY = "code_based_verification_global_disable"+MAX_CODE_BASED_VERIFICATION_GLOBAL_DISABLE_TTL_SECONDS = 7 * 24 * 60 * 60 # 7 days-def is_email_mfa_globally_disabled() -> bool:- # Fail closed: if Redis is unreachable, keep email MFA enforced (the secure default) rather than+def is_code_based_verification_globally_disabled() -> bool:+ # Fail closed: if Redis is unreachable, keep code-based verification enforced (the secure default) rather than# silently dropping the second factor — and never let a Redis hiccup break the login flow.try:- return bool(get_client().exists(EMAIL_MFA_GLOBAL_DISABLE_REDIS_KEY))+ return bool(get_client().exists(CODE_BASED_VERIFICATION_GLOBAL_DISABLE_REDIS_KEY))except Exception:- mfa_logger.exception("Failed to read email MFA global disable flag; keeping email MFA enforced")+ mfa_logger.exception(+ "Failed to read code-based verification global disable flag; keeping code-based verification enforced"+ )return False-def get_email_mfa_global_disable() -> Optional[dict]:+def get_code_based_verification_global_disable() -> Optional[dict]:try:client = get_client()- raw = client.get(EMAIL_MFA_GLOBAL_DISABLE_REDIS_KEY)+ raw = client.get(CODE_BASED_VERIFICATION_GLOBAL_DISABLE_REDIS_KEY)if not raw:return Nonedata = json.loads(raw)- ttl = client.ttl(EMAIL_MFA_GLOBAL_DISABLE_REDIS_KEY)+ ttl = client.ttl(CODE_BASED_VERIFICATION_GLOBAL_DISABLE_REDIS_KEY)data["expires_in_seconds"] = ttl if isinstance(ttl, int) and ttl > 0 else Nonereturn dataexcept Exception:- mfa_logger.exception("Failed to read email MFA global disable state")+ mfa_logger.exception("Failed to read code-based verification global disable state")return None-def set_email_mfa_global_disable(reason: str, ttl_seconds: int, disabled_by: str) -> None:+def set_code_based_verification_global_disable(reason: str, ttl_seconds: int, disabled_by: str) -> None:reason = (reason or "").strip()if not reason:- raise ValueError("A reason is required to disable email MFA.")- if not 0 < ttl_seconds <= MAX_EMAIL_MFA_GLOBAL_DISABLE_TTL_SECONDS:+ raise ValueError("A reason is required to disable code-based verification.")+ if not 0 < ttl_seconds <= MAX_CODE_BASED_VERIFICATION_GLOBAL_DISABLE_TTL_SECONDS:raise ValueError(- f"TTL must be between 1 second and {MAX_EMAIL_MFA_GLOBAL_DISABLE_TTL_SECONDS} seconds (7 days)."+ f"TTL must be between 1 second and {MAX_CODE_BASED_VERIFICATION_GLOBAL_DISABLE_TTL_SECONDS} seconds (7 days).")payload = json.dumps({@@ -89,11 +91,11 @@ def set_email_mfa_global_disable(reason: str, ttl_seconds: int, disabled_by: str"disabled_at": datetime.datetime.now(datetime.UTC).isoformat(),})- get_client().set(EMAIL_MFA_GLOBAL_DISABLE_REDIS_KEY, payload, ex=ttl_seconds)+ get_client().set(CODE_BASED_VERIFICATION_GLOBAL_DISABLE_REDIS_KEY, payload, ex=ttl_seconds)-def clear_email_mfa_global_disable() -> None:- get_client().delete(EMAIL_MFA_GLOBAL_DISABLE_REDIS_KEY)+def clear_code_based_verification_global_disable() -> None:+ get_client().delete(CODE_BASED_VERIFICATION_GLOBAL_DISABLE_REDIS_KEY)def has_passkeys(user: User) -> bool:@@ -114,14 +116,14 @@ def has_passkeys(user: User) -> bool:mfa_logger = structlog.get_logger("posthog.auth.mfa")--def _obfuscate_token(token: str | None) -> str:- """Return first 5 and last 5 chars of token, with middle obfuscated."""- if not token:- return ""- if len(token) <= 10:- return "*" * len(token)- return f"{token[:5]}...{token[-5:]}"+# One counter for the whole code-based login-verification flow, sliced by transition. Lets Grafana+# derive send volume, delivery failures, completion rate (success / sent), invalid-code rate and+# lockout rate, and alert on any of them.+LOGIN_CODE_VERIFICATION_COUNTER = Counter(+ "login_code_verification_total",+ "Transitions in the code-based login-verification flow.",+ labelnames=["result"], # sent | resent | send_failed | success | invalid | locked_out+)# Enforce Two-Factor Authentication only on sessions created after this date@@ -139,7 +141,7 @@ WHITELISTED_PATHS = ["/api/logout/","/api/login/","/api/login/token/",- "/api/login/email-mfa/",+ "/api/login/code-based-verification/","/api/users/@me/","/_health/",]@@ -285,66 +287,42 @@ def is_sso_authentication_backend(request: HttpRequest):return request.session.get("_auth_user_backend") in SSO_AUTHENTICATION_BACKENDS-class EmailMFATokenGenerator(PasswordResetTokenGenerator):- """- Token generator for email-based MFA login verification.- Tokens are valid for 10 minutes and become invalid after use or expiration.- """-- def check_token(self, user, token):- """Override to use 10-minute timeout instead of PASSWORD_RESET_TIMEOUT (1 hour)."""- if not (user and token):- mfa_logger.warning(- "Email MFA token check failed: missing user or token",- user_id=getattr(user, "pk", None),- has_token=bool(token),- token=_obfuscate_token(token),- )- return False-- try:- ts_b36, _ = token.split("-")- ts = base36_to_int(ts_b36)- except ValueError:- mfa_logger.warning(- "Email MFA token check failed: malformed token",- user_id=user.pk,- token=_obfuscate_token(token),- )- return False-- # Validate token signature- for secret in [self.secret, *self.secret_fallbacks]:- if constant_time_compare(self._make_token_with_timestamp(user, ts, secret), token):- break- else:- mfa_logger.warning(- "Email MFA token check failed: signature mismatch (token may have been invalidated by login, password change, email change, or account deactivation)",- user_id=user.pk,- user_last_login=str(user.last_login) if user.last_login else None,- token=_obfuscate_token(token),- )+CODE_LENGTH = 6+CODE_TTL_SECONDS = 600 # 10 minutes+CODE_MAX_ATTEMPTS = 5+# 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"+++class CodeBasedVerificationTokenGenerator(PasswordResetTokenGenerator):+ """Derive a short numeric login-verification code from the same secret-keyed,+ per-user hash the framework uses for password-reset tokens. The code is pinned to+ the login attempt's issuance time, valid for CODE_TTL_SECONDS, and rotates+ automatically on login, password change, email change, or deactivation."""++ def make_code(self, user: AbstractBaseUser, issued_at: int) -> str:+ """Deterministic CODE_LENGTH-digit code for this user and issuance time."""+ digest = salted_hmac(+ self.key_salt,+ self._make_hash_value(user, issued_at),+ secret=self.secret,+ algorithm=self.algorithm,+ ).hexdigest()+ return f"{int(digest, 16) % (10**CODE_LENGTH):0{CODE_LENGTH}d}"++ def check_code(self, user: AbstractBaseUser, code: str, issued_at: int) -> bool:+ """Constant-time compare against the expected code, rejecting expired codes.++ Brute-force resistance does not come from the code's entropy (6 digits is+ guessable) but from the caller gating this behind a password-authenticated+ pending session plus a hard attempt cap.+ """+ if not (user and code and issued_at):return False-- # Check 10-minute timeout (600 seconds)- token_age_seconds = self._num_seconds(self._now()) - ts- if token_age_seconds > 600:- mfa_logger.warning(- "Email MFA token check failed: token expired",- user_id=user.pk,- token_age_seconds=token_age_seconds,- max_age_seconds=600,- token=_obfuscate_token(token),- )+ if int(time.time()) - issued_at > CODE_TTL_SECONDS:return False-- mfa_logger.info(- "Email MFA token check successful",- user_id=user.pk,- token_age_seconds=token_age_seconds,- token=_obfuscate_token(token),- )- return True+ return constant_time_compare(self.make_code(user, issued_at), code)def _make_hash_value(self, user: AbstractBaseUser, timestamp: int) -> str:"""Include last_login and is_active to invalidate tokens after use or deactivation."""@@ -355,23 +333,23 @@ class EmailMFATokenGenerator(PasswordResetTokenGenerator):return f"{usable_user.pk}{usable_user.email}{usable_user.password}{usable_user.is_active}{login_timestamp}{timestamp}"-email_mfa_token_generator = EmailMFATokenGenerator()+code_based_verification_token_generator = CodeBasedVerificationTokenGenerator()@dataclass-class EmailMFACheckResult:+class CodeBasedVerificationCheckResult:should_send: boolsuppression_bypassed: bool = Falsesuppression_reason: Optional[str] = Nonesuppression_cached: bool = False-class EmailMFAVerifier:+class CodeBasedVerifier:def _capture_suppression_bypass_event(self, user: User, reason: str, cached: bool) -> None:try:posthoganalytics.capture(distinct_id=str(user.distinct_id),- event="email_mfa_bypassed_due_to_suppression",+ event="code_based_verification_bypassed_due_to_suppression",properties={"reason": reason,"cached": cached,@@ -379,101 +357,154 @@ class EmailMFAVerifier:)except Exception as e:mfa_logger.warning(- "Failed to capture email MFA suppression bypass event",+ "Failed to capture code-based verification suppression bypass event",user_id=user.pk,error=str(e),)- def should_send_email_mfa_verification(self, user: User) -> EmailMFACheckResult:- if is_email_mfa_globally_disabled():- return EmailMFACheckResult(should_send=False)+ def should_send_code_based_verification(self, user: User) -> CodeBasedVerificationCheckResult:+ if is_code_based_verification_globally_disabled():+ return CodeBasedVerificationCheckResult(should_send=False)if is_dev_mode() and not settings.TEST:- return EmailMFACheckResult(should_send=False)+ return CodeBasedVerificationCheckResult(should_send=False)if not is_email_available(with_absolute_urls=True):- return EmailMFACheckResult(should_send=False)+ return CodeBasedVerificationCheckResult(should_send=False)if not is_http_email_service_available():mfa_logger.info(- "Email MFA bypassed - HTTP email service not configured",+ "Code-based verification bypassed - HTTP email service not configured",user_id=user.pk,)self._capture_suppression_bypass_event(user, ESPSuppressionReason.NO_EMAIL_HTTP_SERVICE, False)- return EmailMFACheckResult(+ return CodeBasedVerificationCheckResult(should_send=False,suppression_bypassed=True,suppression_reason=ESPSuppressionReason.NO_EMAIL_HTTP_SERVICE,suppression_cached=False,)- if is_email_mfa_bypass(user.email):- mfa_logger.info("Email MFA bypassed via admin bypass list", user_id=user.pk)- return EmailMFACheckResult(should_send=False)+ if is_code_based_verification_bypass(user.email):+ mfa_logger.info("Code-based verification bypassed via admin bypass list", user_id=user.pk)+ return CodeBasedVerificationCheckResult(should_send=False)suppression_result = check_esp_suppression(user.email)if suppression_result.is_suppressed:reason = suppression_result.reason or ""from_cache = suppression_result.from_cachemfa_logger.info(- "Email MFA bypassed due to ESP suppression",+ "Code-based verification bypassed due to ESP suppression",user_id=user.pk,reason=reason,cached=from_cache,)self._capture_suppression_bypass_event(user, reason, from_cache)- return EmailMFACheckResult(+ return CodeBasedVerificationCheckResult(should_send=False,suppression_bypassed=True,suppression_reason=reason,suppression_cached=from_cache,)- return EmailMFACheckResult(should_send=True)+ return CodeBasedVerificationCheckResult(should_send=True)- def create_token_and_send_email_mfa_verification(- self, request: HttpRequest, user: User, next_url: str | None = None+ def create_and_send_code_based_verification(+ self, request: HttpRequest, user: User, *, is_resend: bool = False) -> bool:from posthog.tasks import email- if not self.should_send_email_mfa_verification(user).should_send:+ if not self.should_send_code_based_verification(user).should_send:return Falsetry:- token = email_mfa_token_generator.make_token(user)- email.send_email_mfa_link(user.pk, token, next_url)- request.session["email_mfa_pending_user_id"] = user.pk- request.session["email_mfa_token_created_at"] = int(time.time())- # Stash so the resend endpoint can rebuild a link that resumes the same post-login destination.- request.session["email_mfa_next"] = next_url+ issued_at = int(time.time())+ code = code_based_verification_token_generator.make_code(user, issued_at)+ email.send_code_based_verification(user.pk, code)+ request.session["code_based_verification_pending_user_id"] = user.pk+ request.session["code_based_verification_issued_at"] = issued_at+ # Resends must not reset the failed-attempt counter, otherwise the attempt cap could be+ # sidestepped by guessing up to the limit, resending, and repeating - letting the 6-digit+ # code be brute-forced in batches. The attempt budget is per pending login, not per code,+ # so only a fresh initial send (not a resend) clears it.+ if not is_resend:+ self._reset_attempts(user.pk)+ LOGIN_CODE_VERIFICATION_COUNTER.labels(result="resent" if is_resend else "sent").inc()mfa_logger.info(- "Email MFA verification email sent",+ "Code-based verification email sent",user_id=user.pk,user_last_login=str(user.last_login) if user.last_login else None,- token=_obfuscate_token(token),)return Trueexcept Exception as e:+ LOGIN_CODE_VERIFICATION_COUNTER.labels(result="send_failed").inc()mfa_logger.exception(- "Email MFA verification email failed",+ "Code-based verification email failed",user_id=user.pk,error=str(e),)- capture_exception(Exception(f"Email MFA verification email failed: {e}"))+ capture_exception(Exception(f"Code-based verification email failed: {e}"))return False- def has_pending_email_mfa_verification(self, request: HttpRequest) -> bool:- return request.session.get("email_mfa_pending_user_id") is not None+ def has_pending_code_based_verification(self, request: HttpRequest) -> bool:+ return request.session.get("code_based_verification_pending_user_id") is not None- def get_pending_email_mfa_verification_user_id(self, request: HttpRequest) -> int | None:- user_id: int | None = request.session.get("email_mfa_pending_user_id")+ def get_pending_code_based_verification_user_id(self, request: HttpRequest) -> int | None:+ user_id: int | None = request.session.get("code_based_verification_pending_user_id")return user_id- def get_pending_email_mfa_verification_token_created_at(self, request: HttpRequest) -> int:- return request.session.get("email_mfa_token_created_at", int(time.time()))+ def get_pending_code_based_verification_issued_at(self, request: HttpRequest) -> int | None:+ return request.session.get("code_based_verification_issued_at")++ def check_code(self, request: HttpRequest, user: User, code: str) -> bool:+ issued_at = self.get_pending_code_based_verification_issued_at(request)+ if not issued_at:+ return False+ return code_based_verification_token_generator.check_code(user, code, issued_at)++ @staticmethod+ def _attempts_redis_key(user_id: int) -> str:+ return f"{CODE_ATTEMPTS_REDIS_KEY_PREFIX}:{user_id}"++ def _reset_attempts(self, user_id: int) -> None:+ try:+ get_client().delete(self._attempts_redis_key(user_id))+ except Exception:+ mfa_logger.exception("Failed to reset code-based verification attempt counter", user_id=user_id)++ def reserve_attempt(self, request: HttpRequest) -> int:+ """Atomically count this verification attempt against the pending login's budget.++ Returns the running attempt total (including this one) so the caller can reject once it+ exceeds CODE_MAX_ATTEMPTS. Backed by a Redis INCR keyed on the pending user id, so parallel+ guesses can't all read the same pre-increment value and slip past the cap. Fails open on a+ Redis error (returns 0) to keep login working - the per-user verify throttle is the backstop.+ """+ user_id = self.get_pending_code_based_verification_user_id(request)+ if not user_id:+ return 0+ try:+ client = get_client()+ count = int(client.incr(self._attempts_redis_key(user_id)))+ client.expire(self._attempts_redis_key(user_id), CODE_TTL_SECONDS)+ return count+ except Exception:+ mfa_logger.exception(+ "Failed to reserve code-based verification attempt; allowing (throttle still applies)",+ user_id=user_id,+ )+ return 0- def check_token(self, user: User, token: str) -> bool:- return email_mfa_token_generator.check_token(user, token)+ def clear_pending(self, request: HttpRequest) -> None:+ user_id = self.get_pending_code_based_verification_user_id(request)+ if user_id:+ self._reset_attempts(user_id)+ for key in (+ "code_based_verification_pending_user_id",+ "code_based_verification_issued_at",+ "code_based_verification_attempts",+ ):+ request.session.pop(key, None)-email_mfa_verifier = EmailMFAVerifier()+code_based_verifier = CodeBasedVerifier()diff --git a/posthog/rate_limit.py b/posthog/rate_limit.pyindex 289d23cddd35..6b27b7fdaa3f 100644--- a/posthog/rate_limit.py+++ b/posthog/rate_limit.py@@ -730,19 +730,33 @@ class UserPasswordResetThrottle(UserOrEmailRateThrottle):rate = "6/day"-class EmailMFAThrottle(UserOrEmailRateThrottle):- scope = "email_mfa"+class CodeBasedVerificationThrottle(UserOrEmailRateThrottle):+ scope = "code_based_verification"rate = "6/20minutes"+ def get_cache_key(self, request, view):+ # Key on the pending login's user id (from the session), not on request data. The base class+ # would fall back to a request-body "email" field, which the code-verification request never+ # legitimately carries - letting an attacker mint a fresh throttle bucket per guess by varying+ # it. The session is the source of truth for who is being verified.+ from posthog.helpers.two_factor_session import code_based_verifier++ user_id = code_based_verifier.get_pending_code_based_verification_user_id(request)+ if user_id:+ ident = hashlib.sha256(str(user_id).encode()).hexdigest()+ return self.cache_format % {"scope": self.scope, "ident": ident}++ return super().get_cache_key(request, view)+-class EmailMFAResendThrottle(UserOrEmailRateThrottle):- scope = "email_mfa_resend"+class CodeBasedVerificationResendThrottle(UserOrEmailRateThrottle):+ scope = "code_based_verification_resend"rate = "1/minute"def get_cache_key(self, request, view):- from posthog.helpers.two_factor_session import email_mfa_verifier+ from posthog.helpers.two_factor_session import code_based_verifier- user_id = email_mfa_verifier.get_pending_email_mfa_verification_user_id(request)+ user_id = code_based_verifier.get_pending_code_based_verification_user_id(request)if user_id:ident = hashlib.sha256(str(user_id).encode()).hexdigest()return self.cache_format % {"scope": self.scope, "ident": ident}diff --git a/posthog/tasks/email.py b/posthog/tasks/email.pyindex 8c6f44dd24da..5c024fc0b0cc 100644--- a/posthog/tasks/email.py+++ b/posthog/tasks/email.py@@ -471,21 +471,18 @@ def send_email_verification(user_id: int, token: str, next_url: str | None = Non@shared_task(**EMAIL_TASK_KWARGS)@skip_team_scope_audit-def send_email_mfa_link(user_id: int, token: str, next_url: str | None = None) -> None:- """Send email MFA verification link"""+def send_code_based_verification(user_id: int, code: str) -> None:+ """Send the 6-digit login verification code."""user: User = User.objects.get(pk=user_id)- next_query = f"&next={quote(next_url, safe='')}" if next_url else ""- verification_link = f"{settings.SITE_URL}/login/verify?email={quote(user.email)}&token={token}{next_query}"-message = EmailMessage(use_http=True,- campaign_key=f"email_mfa_{user.uuid}-{timezone.now().timestamp()}",- subject="Verify your PostHog login",- template_name="email_mfa_link",+ campaign_key=f"code_based_verification_{user.uuid}-{timezone.now().timestamp()}",+ subject="Your PostHog login code",+ template_name="code_based_verification",template_context={- "preheader": "Please follow the link inside to verify your login.",- "url": verification_link,+ "preheader": "Enter this code to verify your login.",+ "code": code,"expiration_minutes": 10,"site_url": settings.SITE_URL,},@@ -494,7 +491,7 @@ def send_email_mfa_link(user_id: int, token: str, next_url: str | None = None) -message.send(send_async=False)posthoganalytics.capture(distinct_id=str(user.distinct_id),- event="email mfa link sent",+ event="login verification code sent",groups={"organization": str(user.current_organization.id)}, # type: ignore)diff --git a/posthog/tasks/test/__snapshots__/test_task_registration.ambr b/posthog/tasks/test/__snapshots__/test_task_registration.ambrindex 8e2d69bba346..a0791316bdf0 100644--- a/posthog/tasks/test/__snapshots__/test_task_registration.ambr+++ b/posthog/tasks/test/__snapshots__/test_task_registration.ambr@@ -25,10 +25,10 @@'posthog.tasks.email.send_async_migration_complete_email','posthog.tasks.email.send_async_migration_errored_email','posthog.tasks.email.send_canary_email',+ 'posthog.tasks.email.send_code_based_verification','posthog.tasks.email.send_conversation_restore_email','posthog.tasks.email.send_discussions_mentioned','posthog.tasks.email.send_email_change_emails',- 'posthog.tasks.email.send_email_mfa_link','posthog.tasks.email.send_email_verification','posthog.tasks.email.send_error_tracking_issue_assigned','posthog.tasks.email.send_error_tracking_weekly_digest',diff --git a/posthog/templates/admin/email_mfa_bypass.html b/posthog/templates/admin/code_based_verification_bypass.htmlsimilarity index 98%rename from posthog/templates/admin/email_mfa_bypass.htmlrename to posthog/templates/admin/code_based_verification_bypass.htmlindex 1bdb07f54ed1..a0136ce486a3 100644--- a/posthog/templates/admin/email_mfa_bypass.html+++ b/posthog/templates/admin/code_based_verification_bypass.html@@ -109,7 +109,7 @@</form><script nonce="{{ request.csp_nonce }}">-const API_BASE = '/admin/api/email-mfa-bypass/';+const API_BASE = '/admin/api/code-based-verification-bypass/';function getCSRFToken() {return document.querySelector('[name=csrfmiddlewaretoken]').value;@@ -201,7 +201,7 @@ document.getElementById('email-list-body').addEventListener('click', function(e)});// --- Global email MFA disable ----const GLOBAL_API = '/admin/api/email-mfa-global-disable/';+const GLOBAL_API = '/admin/api/code-based-verification-global-disable/';const MAX_TTL_SECONDS = 7 * 24 * 60 * 60;const disableForm = document.getElementById('disable-form');diff --git a/posthog/templates/custom_tools/app.html b/posthog/templates/custom_tools/app.htmlindex e71034f364e2..032811ae9ce6 100644--- a/posthog/templates/custom_tools/app.html+++ b/posthog/templates/custom_tools/app.html@@ -31,9 +31,9 @@</td><td>Manage email addresses that bypass suspicious signup checks (WorkOS Radar)</td></tr>- <tr class="model-emailmfabypass">+ <tr class="model-codebasedverificationbypass"><td scope="row">- <a href="{% url 'email-mfa-bypass' %}">Email MFA bypass</a>+ <a href="{% url 'code-based-verification-bypass' %}">Email MFA bypass</a></td><td>Manage email addresses that bypass email MFA verification</td></tr>diff --git a/posthog/templates/email/email_mfa_link.html b/posthog/templates/email/code_based_verification.htmlsimilarity index 56%rename from posthog/templates/email/email_mfa_link.htmlrename to posthog/templates/email/code_based_verification.htmlindex 2ab8579aaf63..54f74bfa3be2 100644--- a/posthog/templates/email/email_mfa_link.html+++ b/posthog/templates/email/code_based_verification.html@@ -1,19 +1,12 @@{% extends "email/base.html" %} {% load posthog_assets %} {% load posthog_filters %}{% block section %}-<p>We received a login attempt to your PostHog account. To continue, please verify it's you by clicking the link below:</p>+<p>We received a login attempt to your PostHog account. To continue, enter this verification code:</p><div class="mb mt text-center">- <a class="button" href="{{url}}">Verify login</a>+ <p style="font-size: 32px; font-weight: 700; letter-spacing: 8px; margin: 0;">{{code}}</p></div>-<p>This link expires in {{expiration_minutes}} minutes.</p>--<div class="mt muted">- <p>- If the button above doesn't work, paste this link into your browser:<br />- <a href="{{url}}">{{url}}</a>- </p>-</div>+<p>This code expires in {{expiration_minutes}} minutes.</p><hr />@@ -21,4 +14,4 @@<strong>Didn't try to log in?</strong><br>If you didn't attempt this login, someone may be trying to access your account. Please secure your account immediately by changing your password.</p>-{% endblock %} {% block preheader %}{{preheader}}{% endblock %}{% block heading %}Verify your login{% endblock %}+{% endblock %} {% block preheader %}{{preheader}}{% endblock %}{% block heading %}Your login code{% endblock %}diff --git a/posthog/test/base.py b/posthog/test/base.pyindex c2ae72146182..470ddefeba2e 100644--- a/posthog/test/base.py+++ b/posthog/test/base.py@@ -77,7 +77,7 @@ from posthog.clickhouse.query_log_archive import (WRITABLE_QUERY_LOG_ARCHIVE_TABLE,)from posthog.cloud_utils import TEST_clear_instance_license_cache-from posthog.helpers.two_factor_session import email_mfa_token_generator+from posthog.helpers.two_factor_session import code_based_verification_token_generatorfrom posthog.hogql_queries.ai.ai_table_resolver import AI_EVENT_NAMES as _AI_EVENT_TYPESfrom posthog.hogql_queries.insights.paginators import HogQLHasMorePaginatorfrom posthog.models import Organization, Team, User@@ -1067,13 +1067,13 @@ class APIBaseTest(PostHogTestCase, ErrorResponsesMixin, DRFTestCase):)return key_value- def complete_email_mfa(self, email: str, user: Optional[Any] = None):+ def complete_code_based_verification(self, email: str, user: Optional[Any] = None):if user is None:user = User.objects.get(email=email)- token = email_mfa_token_generator.make_token(user)+ token = code_based_verification_token_generator.make_token(user)- response = self.client.post("/api/login/email-mfa/", {"email": email, "token": token})+ response = self.client.post("/api/login/code-based-verification/", {"email": email, "token": token})return responsediff --git a/services/mcp/src/tools/links/app-url-manifest.json b/services/mcp/src/tools/links/app-url-manifest.jsonindex 69e04254d39f..48e190cb9bc7 100644--- a/services/mcp/src/tools/links/app-url-manifest.json+++ b/services/mcp/src/tools/links/app-url-manifest.json@@ -469,11 +469,6 @@"params": [],"scope": "project"},- "emailMFAVerify": {- "template": "/login/verify",- "params": [],- "scope": "global"- },"embedded": {"template": "/embedded/{token}","params": ["token"],diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/generate-app-url.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/generate-app-url.jsonindex 0845c05c925b..82d3ce51d255 100644--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/generate-app-url.json+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/generate-app-url.json@@ -13,7 +13,7 @@"type": "object"},"url": {- "description": "A path template copied verbatim from the catalog below (e.g. `/persons/{uuid}`). Its `{placeholders}` are filled from `params`. These slugs come from PostHog's canonical route table, so they are always correct — never pass a path that is not in this list.\n\n/account-connected/{kind}\n/account/credential-review\n/account/social-connected\n/activity-logs\n/activity/{tab}\n/agentic/account-mismatch\n/agentic/authorize\n/ai\n/ai-evals/datasets\n/ai-evals/datasets/{id}\n/ai-evals/evaluations\n/ai-evals/evaluations/offline/experiments\n/ai-evals/evaluations/offline/experiments/{experimentId}\n/ai-evals/evaluations/templates\n/ai-evals/evaluations/{id}\n/ai-evals/taggers\n/ai-evals/taggers/{id}\n/ai-observability/clusters\n/ai-observability/clusters/{runId}/{clusterId}\n/ai-observability/dashboard\n/ai-observability/errors\n/ai-observability/generations\n/ai-observability/playground\n/ai-observability/reviews\n/ai-observability/sentiment\n/ai-observability/sessions\n/ai-observability/sessions/{id}\n/ai-observability/tools\n/ai-observability/traces\n/ai-observability/traces/{id}\n/ai-observability/users\n/ai/history\n/approvals/{id}\n/billing/authorization_status\n/business-knowledge\n/canvas\n/cli/authorize\n/cli/live\n/cohorts\n/cohorts/{id}\n/cohorts/{id}/calculation-history\n/connect/vercel/link\n/coupons/{campaign}\n/create-organization\n/customer_analytics\n/customer_analytics/accounts\n/customer_analytics/configuration\n/customer_analytics/dashboard\n/customer_analytics/journeys\n/customer_analytics/journeys/new\n/customer_analytics/journeys/templates\n/customer_analytics/journeys/{id}/edit\n/dashboard\n/dashboard/templates/{templateId}/copy-to-project\n/dashboard/{id}\n/dashboard/{id}/button-tiles/{buttonTileId}\n/dashboard/{id}/sharing\n/dashboard/{id}/subscriptions\n/dashboard/{id}/subscriptions/{subscriptionId}\n/dashboard/{id}/text-tiles/{textTileId}\n/data-management/actions\n/data-management/actions/new\n/data-management/actions/new/\n/data-management/actions/{id}\n/data-management/annotations\n/data-management/annotations/{id}\n/data-management/comments\n/data-management/comments/{id}\n/data-management/core-events\n/data-management/database\n/data-management/destinations\n/data-management/event-filtering\n/data-management/events\n/data-management/events/{id}\n/data-management/events/{id}/edit\n/data-management/history\n/data-management/ingestion-warnings\n/data-management/managed-viewsets\n/data-management/materialized-columns\n/data-management/properties\n/data-management/properties/{id}\n/data-management/properties/{id}/edit\n/data-management/revenue\n/data-management/schema\n/data-management/sources\n/data-management/sources/{id}/schemas\n/data-management/sources/{sourceId}/schemas/{schemaId}\n/data-management/transformations\n/data-management/variables\n/data-management/variables/{id}\n/data-management/variables/{id}/edit\n/data-ops\n/data-warehouse/new-source\n/debug\n/debug/hog\n/early_access_features\n/early_access_features/{id}\n/embedded/{token}\n/endpoints\n/endpoints/{name}\n/error_tracking\n/error_tracking/alerts/new/{templateId}\n/error_tracking/alerts/{id}\n/error_tracking/{id}\n/error_tracking/{id}/fingerprints\n/events/{id}/{timestamp}\n/experiments\n/experiments/shared-metrics\n/experiments/shared-metrics/{id}\n/experiments/{id}\n/exports\n/feature_flags\n/feature_flags/new\n/feature_flags/templates\n/feature_flags/{id}\n/functions/new/{templateId}\n/functions/{id}\n/games/368hedgehogs\n/games/flappyhog\n/groups/{groupTypeIndex}\n/groups/{groupTypeIndex}/new\n/groups/{groupTypeIndex}/{groupKey}\n/health\n/health/alerts\n/health/pipeline-status\n/health/sdk-health\n/health/{category}\n/heatmaps\n/heatmaps/new\n/heatmaps/recording\n/heatmaps/{id}\n/home\n/inbox\n/insights\n/insights/new\n/insights/quick-start\n/insights/{id}\n/insights/{id}/edit\n/insights/{id}/sharing\n/insights/{id}/subscriptions\n/insights/{id}/subscriptions/{subscriptionId}\n/insights/{insightShortId}/alerts\n/instance/async_migrations\n/instance/async_migrations/future\n/instance/async_migrations/settings\n/instance/dead_letter_queue\n/instance/kafka_inspector\n/instance/metrics\n/instance/query_performance\n/instance/settings\n/instance/staff_users\n/instance/status\n/integrations/stripe/confirm-install\n/integrations/vercel/link-error\n/integrations/{kind}/callback\n/legal\n/legal/new/{type}\n/link/{id}\n/links\n/live-debugger\n/login\n/login/2fa\n/login/2fa_setup\n/login/verify\n/logs\n/logs/alerts/{alertId}/notifications/{hogFunctionId}\n/logs/alerts/{id}\n/logs/drop-rules/new\n/logs/drop-rules/{id}\n/managed_migrations\n/managed_migrations/new\n/marketing\n/mcp-analytics/dashboard\n/mcp-analytics/intent-clustering\n/mcp-analytics/sessions\n/mcp-analytics/tool-quality\n/mcp-analytics/tool-quality/{toolName}\n/metrics\n/models\n/models/{id}\n/move-to-cloud\n/notebooks\n/notebooks/{shortId}\n/oauth/authorize\n/onboarding\n/organization-deactivated\n/organization-pending-deletion\n/organization/billing\n/organization/billing/overview\n/organization/confirm-creation\n/organization/create-project\n/person/{id}\n/persons\n/persons/{uuid}\n/pipeline/batch-exports/new/{service}\n/pipeline/batch-exports/{id}\n/pipeline/new/\n/pipeline/plugins/{id}\n/preflight\n/product_tours\n/product_tours/{id}\n/prompt-management/prompts\n/prompt-management/prompts/{name}\n/prompt-management/skills\n/prompt-management/skills/{name}\n/replay-vision\n/replay-vision/observations/{observationId}\n/replay-vision/templates\n/replay-vision/{id}/configure\n/replay-vision/{id}/triggers\n/replay/file-playback\n/replay/home\n/replay/kiosk\n/replay/playlists/{id}\n/replay/settings\n/replay/{id}\n/reset\n/reset/{userUuid}/{token}\n/reset_2fa/{userUuid}/{token}\n/resource-transfer/{resourceKind}/{resourceId}\n/revenue_analytics\n/session-summaries\n/session-summaries/{sessionGroupId}\n/sessions/{id}\n/settings/environment-approvals\n/settings/project\n/shared/{token}\n/shared_dashboard/{shareToken}\n/signup\n/signup/{id}\n/site/{url}\n/slack-task-context\n/sql\n/startups\n/subscriptions\n/subscriptions/new\n/subscriptions/{id}\n/subscriptions/{id}/edit\n/support\n/support/settings\n/support/tickets\n/support/tickets/{ticketId}\n/surveys\n/surveys/form/new\n/surveys/guided/new\n/surveys/{id}\n/tasks\n/tasks/{taskId}\n/themes/custom-css\n/toolbar\n/tracing\n/unsubscribe\n/user_research\n/user_research/{id}\n/user_research/{topicId}/response/{responseId}\n/verify_email\n/visual_review\n/visual_review/repos/{repoId}/runs\n/visual_review/repos/{repoId}/snapshots\n/visual_review/repos/{repoId}/{runType}/snapshots/{identifier}\n/visual_review/runs/{runId}\n/visual_review/settings\n/web\n/web-scripts\n/web-scripts/new\n/web/bots\n/web/health\n/web/live\n/web/marketing\n/web/page-reports\n/web/session-attribution-explorer\n/web/web-vitals\n/wizard\n/workflows\n/workflows/library/messages/{id}\n/workflows/library/templates/new\n/workflows/library/templates/{id}\n/workflows/new/workflow\n/workflows/{id}/{tab}",+ "description": "A path template copied verbatim from the catalog below (e.g. `/persons/{uuid}`). Its `{placeholders}` are filled from `params`. These slugs come from PostHog's canonical route table, so they are always correct — never pass a path that is not in this list.\n\n/account-connected/{kind}\n/account/credential-review\n/account/social-connected\n/activity-logs\n/activity/{tab}\n/agentic/account-mismatch\n/agentic/authorize\n/ai\n/ai-evals/datasets\n/ai-evals/datasets/{id}\n/ai-evals/evaluations\n/ai-evals/evaluations/offline/experiments\n/ai-evals/evaluations/offline/experiments/{experimentId}\n/ai-evals/evaluations/templates\n/ai-evals/evaluations/{id}\n/ai-evals/taggers\n/ai-evals/taggers/{id}\n/ai-observability/clusters\n/ai-observability/clusters/{runId}/{clusterId}\n/ai-observability/dashboard\n/ai-observability/errors\n/ai-observability/generations\n/ai-observability/playground\n/ai-observability/reviews\n/ai-observability/sentiment\n/ai-observability/sessions\n/ai-observability/sessions/{id}\n/ai-observability/tools\n/ai-observability/traces\n/ai-observability/traces/{id}\n/ai-observability/users\n/ai/history\n/approvals/{id}\n/billing/authorization_status\n/business-knowledge\n/canvas\n/cli/authorize\n/cli/live\n/cohorts\n/cohorts/{id}\n/cohorts/{id}/calculation-history\n/connect/vercel/link\n/coupons/{campaign}\n/create-organization\n/customer_analytics\n/customer_analytics/accounts\n/customer_analytics/configuration\n/customer_analytics/dashboard\n/customer_analytics/journeys\n/customer_analytics/journeys/new\n/customer_analytics/journeys/templates\n/customer_analytics/journeys/{id}/edit\n/dashboard\n/dashboard/templates/{templateId}/copy-to-project\n/dashboard/{id}\n/dashboard/{id}/button-tiles/{buttonTileId}\n/dashboard/{id}/sharing\n/dashboard/{id}/subscriptions\n/dashboard/{id}/subscriptions/{subscriptionId}\n/dashboard/{id}/text-tiles/{textTileId}\n/data-management/actions\n/data-management/actions/new\n/data-management/actions/new/\n/data-management/actions/{id}\n/data-management/annotations\n/data-management/annotations/{id}\n/data-management/comments\n/data-management/comments/{id}\n/data-management/core-events\n/data-management/database\n/data-management/destinations\n/data-management/event-filtering\n/data-management/events\n/data-management/events/{id}\n/data-management/events/{id}/edit\n/data-management/history\n/data-management/ingestion-warnings\n/data-management/managed-viewsets\n/data-management/materialized-columns\n/data-management/properties\n/data-management/properties/{id}\n/data-management/properties/{id}/edit\n/data-management/revenue\n/data-management/schema\n/data-management/sources\n/data-management/sources/{id}/schemas\n/data-management/sources/{sourceId}/schemas/{schemaId}\n/data-management/transformations\n/data-management/variables\n/data-management/variables/{id}\n/data-management/variables/{id}/edit\n/data-ops\n/data-warehouse/new-source\n/debug\n/debug/hog\n/early_access_features\n/early_access_features/{id}\n/embedded/{token}\n/endpoints\n/endpoints/{name}\n/error_tracking\n/error_tracking/alerts/new/{templateId}\n/error_tracking/alerts/{id}\n/error_tracking/{id}\n/error_tracking/{id}/fingerprints\n/events/{id}/{timestamp}\n/experiments\n/experiments/shared-metrics\n/experiments/shared-metrics/{id}\n/experiments/{id}\n/exports\n/feature_flags\n/feature_flags/new\n/feature_flags/templates\n/feature_flags/{id}\n/functions/new/{templateId}\n/functions/{id}\n/games/368hedgehogs\n/games/flappyhog\n/groups/{groupTypeIndex}\n/groups/{groupTypeIndex}/new\n/groups/{groupTypeIndex}/{groupKey}\n/health\n/health/alerts\n/health/pipeline-status\n/health/sdk-health\n/health/{category}\n/heatmaps\n/heatmaps/new\n/heatmaps/recording\n/heatmaps/{id}\n/home\n/inbox\n/insights\n/insights/new\n/insights/quick-start\n/insights/{id}\n/insights/{id}/edit\n/insights/{id}/sharing\n/insights/{id}/subscriptions\n/insights/{id}/subscriptions/{subscriptionId}\n/insights/{insightShortId}/alerts\n/instance/async_migrations\n/instance/async_migrations/future\n/instance/async_migrations/settings\n/instance/dead_letter_queue\n/instance/kafka_inspector\n/instance/metrics\n/instance/query_performance\n/instance/settings\n/instance/staff_users\n/instance/status\n/integrations/stripe/confirm-install\n/integrations/vercel/link-error\n/integrations/{kind}/callback\n/legal\n/legal/new/{type}\n/link/{id}\n/links\n/live-debugger\n/login\n/login/2fa\n/login/2fa_setup\n/logs\n/logs/alerts/{alertId}/notifications/{hogFunctionId}\n/logs/alerts/{id}\n/logs/drop-rules/new\n/logs/drop-rules/{id}\n/managed_migrations\n/managed_migrations/new\n/marketing\n/mcp-analytics/dashboard\n/mcp-analytics/intent-clustering\n/mcp-analytics/sessions\n/mcp-analytics/tool-quality\n/mcp-analytics/tool-quality/{toolName}\n/metrics\n/models\n/models/{id}\n/move-to-cloud\n/notebooks\n/notebooks/{shortId}\n/oauth/authorize\n/onboarding\n/organization-deactivated\n/organization-pending-deletion\n/organization/billing\n/organization/billing/overview\n/organization/confirm-creation\n/organization/create-project\n/person/{id}\n/persons\n/persons/{uuid}\n/pipeline/batch-exports/new/{service}\n/pipeline/batch-exports/{id}\n/pipeline/new/\n/pipeline/plugins/{id}\n/preflight\n/product_tours\n/product_tours/{id}\n/prompt-management/prompts\n/prompt-management/prompts/{name}\n/prompt-management/skills\n/prompt-management/skills/{name}\n/replay-vision\n/replay-vision/observations/{observationId}\n/replay-vision/templates\n/replay-vision/{id}/configure\n/replay-vision/{id}/triggers\n/replay/file-playback\n/replay/home\n/replay/kiosk\n/replay/playlists/{id}\n/replay/settings\n/replay/{id}\n/reset\n/reset/{userUuid}/{token}\n/reset_2fa/{userUuid}/{token}\n/resource-transfer/{resourceKind}/{resourceId}\n/revenue_analytics\n/session-summaries\n/session-summaries/{sessionGroupId}\n/sessions/{id}\n/settings/environment-approvals\n/settings/project\n/shared/{token}\n/shared_dashboard/{shareToken}\n/signup\n/signup/{id}\n/site/{url}\n/slack-task-context\n/sql\n/startups\n/subscriptions\n/subscriptions/new\n/subscriptions/{id}\n/subscriptions/{id}/edit\n/support\n/support/settings\n/support/tickets\n/support/tickets/{ticketId}\n/surveys\n/surveys/form/new\n/surveys/guided/new\n/surveys/{id}\n/tasks\n/tasks/{taskId}\n/themes/custom-css\n/toolbar\n/tracing\n/unsubscribe\n/user_research\n/user_research/{id}\n/user_research/{topicId}/response/{responseId}\n/verify_email\n/visual_review\n/visual_review/repos/{repoId}/runs\n/visual_review/repos/{repoId}/snapshots\n/visual_review/repos/{repoId}/{runType}/snapshots/{identifier}\n/visual_review/runs/{runId}\n/visual_review/settings\n/web\n/web-scripts\n/web-scripts/new\n/web/bots\n/web/health\n/web/live\n/web/marketing\n/web/page-reports\n/web/session-attribution-explorer\n/web/web-vitals\n/wizard\n/workflows\n/workflows/library/messages/{id}\n/workflows/library/templates/new\n/workflows/library/templates/{id}\n/workflows/new/workflow\n/workflows/{id}/{tab}","type": "string"}},