Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

9.3 KB
Raw Blame
import { MakeLogicType, afterMount, connect, kea, listeners, path } from 'kea'
import posthog from 'posthog-js'

import { preflightLogic } from 'lib/logic/preflightLogic'
import { loginLogic } from 'scenes/authentication/auth/loginLogic'

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

let reportedNoMethodEmail: string | null = null

/**
 * The actions this logic listens to, named by their kea action type strings.
 *
 * Reading another logic's `actionTypes` while kea builds this logic makes kea connect that logic, and
 * a connected logic stays mounted for as long as this one is. The auth pages mount this logic, so a
 * connection would hold `loginLogic`, `login2FALogic` and `passwordResetLogic` mounted on pages that
 * do not use them, and their state would carry over from one visit to the next. String keys let this
 * logic hear the actions without the connection. A kea action type is `<action name as words>
 * (<logic path>)`, so renaming an action or changing its logic's path changes the string.
 * `loginTelemetryLogic.test.ts` reads each type off the real logic and fails when a string no longer
 * matches, when an action is renamed, or when a logic's module moves.
 */
export const LISTENED_ACTIONS = {
    submitLoginRequest: 'submit login request (scenes.authentication.auth.loginLogic)',
    loginError: 'set general error (scenes.authentication.auth.loginLogic)',
    codeVerificationFailure: 'submit code verification failure (scenes.authentication.auth.loginLogic)',
    twoFactorError: 'set general error (scenes.authentication.login-2fa.login2FALogic)',
    resetRequested: 'submit request password reset success (scenes.authentication.password-reset.passwordResetLogic)',
    accountPathChosen: 'choose account path (scenes.authentication.auth.authLogic)',
    setPasswordLinkSent: 'send set password link success (scenes.authentication.auth.loginLogic)',
} as const

// 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 }) => ({
        [LISTENED_ACTIONS.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.
        [LISTENED_ACTIONS.loginError]: (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.
        [LISTENED_ACTIONS.codeVerificationFailure]: ({ error }: { error: Error }) => {
            captureFailure('code', (error as unknown as { code?: string })?.code || 'invalid_code', values.preflight)
        },
        [LISTENED_ACTIONS.twoFactorError]: ({ code }: { code: string }) => {
            captureFailure('2fa', code, values.preflight)
        },
        [LISTENED_ACTIONS.resetRequested]: () => {
            posthog.capture('password reset requested', { region: values.preflight?.region })
        },
        // The banner renders only on the login step, and an edit to the email returns the page to the
        // email step. So the login step, not the precheck, is when the person sees it. Report it once
        // per email, because "Back" and Continue reach the same login step again.
        [LISTENED_ACTIONS.accountPathChosen]: ({ accountPath }: { accountPath: string }) => {
            const login = loginLogic.findMounted()
            if (
                accountPath !== 'login' ||
                !login?.values.hasNoConfiguredLoginMethod ||
                login.values.login.email === reportedNoMethodEmail
            ) {
                return
            }
            reportedNoMethodEmail = login.values.login.email
            // pinned: analytics event name and property names
            posthog.capture('login no method shown', {
                region: values.preflight?.region,
                social_providers_offered: login.values.instanceSocialProviders,
            })
        },
        [LISTENED_ACTIONS.setPasswordLinkSent]: () => {
            // pinned: analytics event name and property names
            posthog.capture('password reset requested', { region: values.preflight?.region, source: 'login_no_method' })
        },
    })),
])

/**
 * 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,
    }
}