: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): measure the login funnel (#92064)
posthog[bot]2a609d1cee50
diff --git a/frontend/src/scenes/authentication/login-2fa/Login2FA.tsx b/frontend/src/scenes/authentication/login-2fa/Login2FA.tsxindex 68f79502d7c0..30a2699dbf63 100644--- a/frontend/src/scenes/authentication/login-2fa/Login2FA.tsx+++ b/frontend/src/scenes/authentication/login-2fa/Login2FA.tsx@@ -1,4 +1,4 @@-import { useActions, useValues } from 'kea'+import { useActions, useMountedLogic, useValues } from 'kea'import { Form } from 'kea-forms'import { LemonButton, LemonDivider, LemonInput } from '@posthog/lemon-ui'@@ -9,6 +9,7 @@ import { supportLogic } from 'lib/components/Support/supportLogic'import { LemonBanner } from 'lib/lemon-ui/LemonBanner'import { LemonField } from 'lib/lemon-ui/LemonField'import { Link } from 'lib/lemon-ui/Link'+import { loginTelemetryLogic } from 'scenes/authentication/shared/loginTelemetryLogic'import { preflightLogic } from 'scenes/PreflightCheck/preflightLogic'import { SceneExport } from 'scenes/sceneTypes'@@ -18,6 +19,8 @@ import { login2FALogic } from './login2FALogic'// elements, so inserting the conditional support link beside a bare text node crashes React// (insertBefore / removeChild NotFoundError, see react#11538).export function Login2FA(): JSX.Element {+ // Mounted here so the login funnel is only reported from the auth scenes+ useMountedLogic(loginTelemetryLogic)const { isTwofactortokenSubmitting, generalError, passkey2FALoading, passkeysAvailable, totpAvailable } =useValues(login2FALogic)const { beginPasskey2FA } = useActions(login2FALogic)diff --git a/frontend/src/scenes/authentication/login/Login.tsx b/frontend/src/scenes/authentication/login/Login.tsxindex 4b3bb152069e..32c0ae443294 100644--- a/frontend/src/scenes/authentication/login/Login.tsx+++ b/frontend/src/scenes/authentication/login/Login.tsx@@ -1,6 +1,7 @@-import { useActions } from 'kea'+import { useActions, useMountedLogic } from 'kea'import { useEffect } from 'react'+import { loginTelemetryLogic } from 'scenes/authentication/shared/loginTelemetryLogic'import { passkeyLogic } from 'scenes/authentication/shared/passkeyLogic'import { SceneExport } from 'scenes/sceneTypes'@@ -13,6 +14,8 @@ export const scene: SceneExport = {}export function Login(): JSX.Element {+ // Mounted here so the login funnel is only reported from the auth scenes+ useMountedLogic(loginTelemetryLogic)const { startConditionalPasskeyLogin } = useActions(passkeyLogic)// WebKit (Safari/iOS) can't open the passkey modal without a user gesture, so we showdiff --git a/frontend/src/scenes/authentication/login/LoginForm.tsx b/frontend/src/scenes/authentication/login/LoginForm.tsxindex 47accec997a4..09f392c3fc59 100644--- a/frontend/src/scenes/authentication/login/LoginForm.tsx+++ b/frontend/src/scenes/authentication/login/LoginForm.tsx@@ -371,7 +371,9 @@ export function LoginForm(): JSX.Element {<span>No sign-in method is set up for this account. Use</span>{' '}<Linkto={[urls.passwordReset(), { email: login.email }]}- data-attr="forgot-password"+ // Autocapture reports the click. Each reset entry point has its+ // own `data-attr`, so one funnel can tell them apart.+ data-attr="login-no-method-reset-password"className="font-semibold no-underline cursor-pointer hover:underline hover:underline-offset-2 text-warning">Forgot password?diff --git a/frontend/src/scenes/authentication/password-reset/PasswordReset.tsx b/frontend/src/scenes/authentication/password-reset/PasswordReset.tsxindex 443dbd28189a..048d5eee058c 100644--- a/frontend/src/scenes/authentication/password-reset/PasswordReset.tsx+++ b/frontend/src/scenes/authentication/password-reset/PasswordReset.tsx@@ -1,7 +1,7 @@/*Scene to request a password reset email.*/-import { useActions, useValues } from 'kea'+import { useActions, useMountedLogic, useValues } from 'kea'import { Form } from 'kea-forms'import { router } from 'kea-router'import { useEffect } from 'react'@@ -14,6 +14,7 @@ import { CodeSnippet, Language } from 'lib/components/CodeSnippet'import { IconErrorOutline } from 'lib/lemon-ui/icons'import { LemonField } from 'lib/lemon-ui/LemonField'import { Spinner } from 'lib/lemon-ui/Spinner/Spinner'+import { loginTelemetryLogic } from 'scenes/authentication/shared/loginTelemetryLogic'import { SupportModalButton } from 'scenes/authentication/shared/SupportModalButton'import { preflightLogic } from 'scenes/PreflightCheck/preflightLogic'import { SceneExport } from 'scenes/sceneTypes'@@ -26,6 +27,8 @@ export const scene: SceneExport = {}export function PasswordReset(): JSX.Element {+ // Mounted here so the login funnel is only reported from the auth scenes+ useMountedLogic(loginTelemetryLogic)const { preflight, preflightLoading } = useValues(preflightLogic)const { requestPasswordResetSucceeded, requestPasswordResetManualErrors } = useValues(passwordResetLogic)const { resetRequestPasswordReset } = useActions(passwordResetLogic)diff --git a/frontend/src/scenes/authentication/shared/loginTelemetryLogic.test.ts b/frontend/src/scenes/authentication/shared/loginTelemetryLogic.test.tsnew file mode 100644index 000000000000..19f9dc09c5d2--- /dev/null+++ b/frontend/src/scenes/authentication/shared/loginTelemetryLogic.test.ts@@ -0,0 +1,198 @@+import { router } from 'kea-router'+import { expectLogic } from 'kea-test-utils'+import posthog from 'posthog-js'++import { login2FALogic } from 'scenes/authentication/login-2fa/login2FALogic'+import { loginLogic } from 'scenes/authentication/login/loginLogic'+import { passwordResetLogic } from 'scenes/authentication/password-reset/passwordResetLogic'+import { loginTelemetryLogic } from 'scenes/authentication/shared/loginTelemetryLogic'++import { useMocks } from '~/mocks/jest'+import { initKeaTests } from '~/test/init'++jest.mock('posthog-js')++// isWebKitBrowser() reads navigator.vendor: "Apple Computer, Inc." on WebKit, "Google Inc." on Chromium.+const WEBKIT_VENDOR = 'Apple Computer, Inc.'+const originalVendor = window.navigator.vendor++function capturedProperties(event: string): Record<string, any> | undefined {+ return (posthog.capture as jest.Mock).mock.calls.find(([name]) => name === event)?.[1]+}++function captureCount(event: string): number {+ return (posthog.capture as jest.Mock).mock.calls.filter(([name]) => name === event).length+}++describe('loginTelemetryLogic', () => {+ let logic: ReturnType<typeof loginTelemetryLogic.build>+ let login: ReturnType<typeof loginLogic.build>+ let precheckHandler: jest.Mock++ beforeEach(() => {+ // Skip the passkey auto-trigger, which is irrelevant to what these cases assert+ Object.defineProperty(window.navigator, 'vendor', { value: WEBKIT_VENDOR, configurable: true })+ precheckHandler = jest.fn(() => [200, { saml_available: false }])+ useMocks({+ get: {+ '/api/users/@me/': () => [200, {}],+ '/api/login/2fa/passkey/methods/': () => [200, { has_totp: true, has_passkeys: false }],+ },+ post: {+ '/api/login/precheck': precheckHandler,+ '/api/login': () => [401, { code: 'invalid_credentials', detail: 'Invalid email or password.' }],+ '/api/reset/': () => [200, { success: true }],+ '/api/login/code-based-verification': () => [+ 429,+ { code: 'throttled', detail: 'Request was throttled.' },+ ],+ },+ })+ initKeaTests()+ router.actions.push('/login')+ login = loginLogic()+ login.mount()+ logic = loginTelemetryLogic()+ logic.mount()+ })++ afterEach(() => {+ logic.unmount()+ login.unmount()+ Object.defineProperty(window.navigator, 'vendor', { value: originalVendor, configurable: true })+ jest.clearAllMocks()+ })++ it('reports an attempt and its failure for a rejected password', async () => {+ login.actions.setLoginValues({ email: '[email protected]', password: 'wrong-password' })+ login.actions.submitLogin()+ await expectLogic(login).toDispatchActions(['setGeneralError'])++ expect(capturedProperties('login attempted')).toMatchObject({ method: 'password' })+ expect(capturedProperties('login failed')).toMatchObject({+ step: 'login',+ error_code: 'invalid_credentials',+ })+ })++ // A throttle and an expired code are different failures. Reporting the rejected response, not the+ // banner text, is what keeps them apart.+ it('reports the reason the verification code was rejected', async () => {+ login.actions.setCodeVerificationValue('code', '123456')+ login.actions.submitCodeVerification()+ await expectLogic(login).toDispatchActions(['submitCodeVerificationFailure']).toFinishAllListeners()++ expect(capturedProperties('login failed')).toMatchObject({ step: 'code', error_code: 'throttled' })+ })++ // Editing the code clears the manual error, which must not read as a second failure.+ it('does not report the clearing of a code error', () => {+ login.actions.setCodeVerificationManualErrors({})++ expect(captureCount('login failed')).toBe(0)+ })++ it('reports the step that rejected a second factor', async () => {+ const twoFA = login2FALogic()+ twoFA.mount()+ twoFA.actions.setGeneralError('2fa_invalid', 'Invalid token')+ await expectLogic(twoFA).toFinishAllListeners()+ twoFA.unmount()++ expect(capturedProperties('login failed')).toMatchObject({ step: '2fa', error_code: '2fa_invalid' })+ })++ it('reports a requested reset email', async () => {+ const reset = passwordResetLogic()+ reset.mount()+ reset.actions.setRequestPasswordResetValue('email', '[email protected]')+ reset.actions.submitRequestPasswordReset()+ await expectLogic(reset).toDispatchActions(['submitRequestPasswordResetSuccess']).toFinishAllListeners()+ reset.unmount()++ expect(captureCount('password reset requested')).toBe(1)+ })++ // The server redirects a failed SSO sign-in back to /login?error_code=..., and kea-router replays+ // that URL while loginLogic mounts, before this logic exists. That is the case where the person+ // is most stuck, so it must not fall through the gap.+ it('reports an error that loginLogic already held when it mounted', () => {+ logic.unmount()+ login.unmount()+ router.actions.push('/login?error_code=improperly_configured_sso&error_detail=Check+your+SSO+setup')+ login = loginLogic()+ login.mount()+ logic = loginTelemetryLogic()+ logic.mount()++ expect(capturedProperties('login failed')).toMatchObject({+ step: 'login',+ error_code: 'improperly_configured_sso',+ })+ expect(captureCount('login failed')).toBe(1)+ })++ // The passkey prompt opens on its own after the precheck, so its failures are not attempts the+ // person made. A funnel that counts driven attempts has to be able to drop them.+ it('gives a passkey failure its own step', () => {+ login.actions.setGeneralError('passkey_error', 'Passkey login failed')++ expect(capturedProperties('login failed')).toMatchObject({ step: 'passkey' })+ })++ // An error raised while the auth scenes are gone — a failed passkey re-authentication inside the+ // app — must not land in the login funnel.+ it('reports nothing once the auth scene unmounts', () => {+ logic.unmount()+ login.actions.setGeneralError('passkey_error', 'Passkey login failed')+ logic.mount()++ expect(captureCount('login failed')).toBe(0)+ })++ // precheck_failed must distinguish "the precheck ran and failed" from "no current precheck+ // exists" — a pending or stale-email result would otherwise be misattributed to this attempt.+ it.each([+ [+ 'no precheck has run',+ async (): Promise<void> => {+ login.actions.setLoginValues({ email: '[email protected]', password: 'wrong' })+ },+ undefined,+ ],+ [+ 'the precheck completed for a different email',+ async (): Promise<void> => {+ login.actions.precheck({ email: '[email protected]' })+ await expectLogic(login).toDispatchActions(['precheckSuccess']).toFinishAllListeners()+ login.actions.setLoginValues({ email: '[email protected]', password: 'wrong' })+ },+ undefined,+ ],+ [+ 'the precheck failed for the current email',+ async (): Promise<void> => {+ precheckHandler.mockImplementationOnce(() => [429, { detail: 'Request was throttled.' }])+ login.actions.setLoginValues({ email: '[email protected]', password: 'wrong' })+ login.actions.precheck({ email: '[email protected]' })+ await expectLogic(login).toDispatchActions(['precheckSuccess']).toFinishAllListeners()+ },+ true,+ ],+ [+ 'the precheck succeeded for the current email',+ async (): Promise<void> => {+ login.actions.setLoginValues({ email: '[email protected]', password: 'wrong' })+ login.actions.precheck({ email: '[email protected]' })+ await expectLogic(login).toDispatchActions(['precheckSuccess']).toFinishAllListeners()+ },+ false,+ ],+ ])('reports precheck_failed only for a current precheck: %s', async (_name, setup, expected) => {+ await setup()+ login.actions.setGeneralError('invalid_credentials', 'Invalid email or password.')+ await expectLogic(login).toDispatchActions(['setGeneralError']).toFinishAllListeners()++ expect(capturedProperties('login failed')?.precheck_failed).toBe(expected)+ })+})diff --git a/frontend/src/scenes/authentication/shared/loginTelemetryLogic.ts b/frontend/src/scenes/authentication/shared/loginTelemetryLogic.tsnew file mode 100644index 000000000000..278b9f6c9084--- /dev/null+++ b/frontend/src/scenes/authentication/shared/loginTelemetryLogic.ts@@ -0,0 +1,134 @@+import { MakeLogicType, afterMount, connect, kea, listeners, path } from 'kea'+import posthog from 'posthog-js'++import { login2FALogic } from 'scenes/authentication/login-2fa/login2FALogic'+import { loginLogic } from 'scenes/authentication/login/loginLogic'+import { passwordResetLogic } from 'scenes/authentication/password-reset/passwordResetLogic'+import { preflightLogic } from 'scenes/PreflightCheck/preflightLogic'++import { PreflightStatus } from '~/types'++/** The point in the sign-in sequence that rejected the person. */+export type LoginFailureStep = 'login' | 'passkey' | 'code' | '2fa'++/**+ * The error already reported, held by identity.+ *+ * `loginLogic` mounts as the scene logic and replays the URL before this logic exists, so a+ * server-redirect error is already set when the listener attaches. `afterMount` reports that error+ * instead, and this guard stops a remount of the scene from counting it twice. The reducer keeps the+ * action payload, so one error keeps one identity.+ */+let reportedError: { code: string; detail: string } | null = null++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface loginTelemetryLogicValues {+ preflight: PreflightStatus | null // preflightLogic+}++export type loginTelemetryLogicType = MakeLogicType<loginTelemetryLogicValues, {}>++/**+ * Every event that sizes the login funnel is emitted here, and nowhere else.+ *+ * The auth scenes mount this logic, so it observes the login logics instead of the login logics+ * reporting on themselves. Two things follow from that. Login code stays free of analytics, and an+ * error raised outside the auth scenes — a failed passkey re-authentication inside the app, which+ * shares `loginLogic` — reports nothing, because this logic is not mounted there.+ *+ * Recovery clicks are not captured here. Each recovery link carries a `data-attr`, which autocapture+ * already records.+ */+export const loginTelemetryLogic = kea<loginTelemetryLogicType>([+ path(['scenes', 'authentication', 'shared', 'loginTelemetryLogic']),+ connect(() => ({+ values: [preflightLogic, ['preflight']],+ })),+ afterMount(({ values }) => {+ // A sign-in that fails on the server redirects back to /login?error_code=..., and kea-router+ // replays that URL while `loginLogic` mounts, which happens before this logic exists. Report+ // the error it already holds, because an SSO or configuration failure is the case where the+ // person is most stuck.+ // A passkey error is the one code that `loginLogic` can hold from outside the auth scenes,+ // because the in-app re-authentication modal raises it. The listener already sees the ones+ // raised on this page, so the catch-up can skip them and stay closed to that leak.+ const error = loginLogic.findMounted()?.values.generalError+ if (error && error.code !== 'passkey_error' && error !== reportedError) {+ reportedError = error+ captureFailure(stepForCode(error.code), error.code, values.preflight)+ }+ }),+ listeners(({ values }) => ({+ [loginLogic.actionTypes.submitLoginRequest]: () => {+ // Only the password form dispatches this. An SSO sign-in leaves the page, and a passkey+ // prompt opens on its own, so `method` says which failures this denominator pairs with.+ posthog.capture('login attempted', { method: 'password', region: values.preflight?.region })+ },+ // Every terminal error of the password, SSO and passkey steps passes through+ // `setGeneralError`, so a submit failure and a redirect failure are both counted once.+ [loginLogic.actionTypes.setGeneralError]: (payload: { code: string; detail: string }) => {+ if (payload === reportedError) {+ return+ }+ reportedError = payload+ captureFailure(stepForCode(payload.code), payload.code, values.preflight)+ },+ // kea-forms carries the rejected response here, so the real reason survives. The manual-error+ // action cannot serve instead: it holds the message rather than the code, and it fires again+ // with an empty object when the person edits the code.+ [loginLogic.actionTypes.submitCodeVerificationFailure]: ({ error }: { error: Error }) => {+ captureFailure('code', (error as unknown as { code?: string })?.code || 'invalid_code', values.preflight)+ },+ [login2FALogic.actionTypes.setGeneralError]: ({ code }: { code: string }) => {+ captureFailure('2fa', code, values.preflight)+ },+ [passwordResetLogic.actionTypes.submitRequestPasswordResetSuccess]: () => {+ posthog.capture('password reset requested', { region: values.preflight?.region })+ },+ })),+])++/**+ * The passkey prompt opens on its own after the precheck, so its failures are not attempts the+ * person made. They take their own step, which lets a funnel count only the steps a person drives.+ */+function stepForCode(code: string): LoginFailureStep {+ return code === 'passkey_error' ? 'passkey' : 'login'+}++function captureFailure(step: LoginFailureStep, code: string, preflight: PreflightStatus | null): void {+ posthog.capture('login failed', {+ step,+ error_code: code || 'unknown',+ region: preflight?.region,+ ...precheckProperties(),+ })+}++/**+ * What the precheck knows about the account that failed to sign in.+ *+ * The precheck describes this attempt only when it completed for the email now in the form. A+ * pending result (no precheck ran, e.g. a server-redirect error on page load) or one left over from+ * a different email must not be reported as this attempt's state.+ */+function precheckProperties(): Record<string, any> {+ const login = loginLogic.findMounted()+ if (!login) {+ return {}+ }+ const { precheckResponse, availableLoginMethods, codeVerificationRequired } = login.values+ const precheckIsCurrent =+ precheckResponse.status === 'completed' && precheckResponse.email === login.values.login.email+ // Trust the account facts only when the precheck also succeeded — a failed precheck reports+ // permissive defaults, which would mislabel the failure.+ const precheckTrusted = precheckIsCurrent && !precheckResponse.precheckFailed+ return {+ code_verification_pending: codeVerificationRequired,+ // undefined (omitted) when no current precheck exists, so "precheck succeeded" stays+ // distinct from "no precheck ran" instead of both reading as false.+ precheck_failed: precheckIsCurrent ? (precheckResponse.precheckFailed ?? false) : undefined,+ sso_enforcement: precheckTrusted ? (precheckResponse.sso_enforcement ?? null) : undefined,+ login_methods_available: precheckTrusted ? availableLoginMethods : undefined,+ }+}diff --git a/frontend/src/scenes/authentication/signup/Signup.tsx b/frontend/src/scenes/authentication/signup/Signup.tsxindex ff6cef56b16b..df9a045b82db 100644--- a/frontend/src/scenes/authentication/signup/Signup.tsx+++ b/frontend/src/scenes/authentication/signup/Signup.tsx@@ -384,7 +384,9 @@ function SignupProfilePanel(): JSX.Element {<>{' '}<Link- data-attr="login-error-contact-support"+ // The login banner uses `login-error-contact-support`. A shared+ // attribute would mix both pages into one autocapture funnel arm.+ data-attr="signup-error-contact-support"onClick={(e) => {e.preventDefault()openSupportForm({