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.

22.5 KB
Raw Blame
import {
    type PublicKeyCredentialRequestOptionsJSON,
    type UserVerificationRequirement,
    startAuthentication,
} from '@simplewebauthn/browser'
import { MakeLogicType, actions, afterMount, connect, kea, listeners, path, reducers, selectors } from 'kea'
import { forms } from 'kea-forms'
import type { DeepPartial, DeepPartialMap, FieldName, ValidationErrorType } from 'kea-forms'
import { loaders } from 'kea-loaders'
import { router } from 'kea-router'
import { subscriptions } from 'kea-subscriptions'
import posthog from 'posthog-js'

import { lemonToast } from '@posthog/lemon-ui'

import api, { ApiError } from 'lib/api'
import { Dayjs, dayjs } from 'lib/dayjs'
import { apiStatusLogic } from 'lib/logic/apiStatusLogic'
import { uuid } from 'lib/utils/dom'
import { PrecheckResponseType } from 'scenes/authentication/auth/loginLogic'
import { ERROR_MESSAGES } from 'scenes/authentication/shared/loginErrorMessages'
import { userLogic } from 'scenes/userLogic'

import type { SSOProvider, UserType } from '../../../types'
import { getSocialLoginUrl } from '../SocialLoginButton/socialLoginUrl'
import { modalInterruptionTrackingLogic } from './modalInterruptionTrackingLogic'

export interface ReauthenticationForm {
    password: string
    token?: string
}

export interface TwoFAMethodsResponse {
    has_totp: boolean
    has_passkeys: boolean
}

export const LOOKAHEAD_EXPIRY_SECONDS = 60 * 5

// Must match `sso_reauth_complete` in posthog/api/authentication.py.
const SSO_REAUTH_COMPLETE_PATH = '/reauth/complete'
const SSO_REAUTH_CHANNEL = 'posthog-sso-reauth'

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface timeSensitiveAuthenticationLogicValues {
    timeSensitiveAuthenticationRequired: boolean | [onSuccess: () => void, onFailure: () => void] // apiStatusLogic
    interruptedForm: string | null // modalInterruptionTrackingLogic
    user: UserType | null // userLogic
    dismissedReauthentication: boolean
    isReauthenticationSubmitting: boolean
    isReauthenticationValid: boolean
    passkey2FA: null
    passkey2FALoading: boolean
    passkeysAvailable: boolean
    passkeysAvailableLoading: boolean
    precheckResponse: PrecheckResponseType | null
    precheckResponseLoading: boolean
    reauthentication: ReauthenticationForm
    reauthenticationAllErrors: Record<string, any>
    reauthenticationChanged: boolean
    reauthenticationErrors: DeepPartialMap<ReauthenticationForm, ValidationErrorType>
    reauthenticationHasErrors: boolean
    reauthenticationManualErrors: Record<string, any>
    reauthenticationTouched: boolean
    reauthenticationTouches: Record<string, boolean>
    reauthenticationValidationErrors: DeepPartialMap<ReauthenticationForm, ValidationErrorType>
    sensitiveSessionExpiresAt: Dayjs
    setPasswordLinkSentTo: string | null
    setPasswordLinkSentToLoading: boolean
    showAuthenticationModal: boolean
    showReauthenticationErrors: boolean
    totpAvailable: boolean
    twoFactorRequired: boolean
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface timeSensitiveAuthenticationLogicActions {
    resolveSensitiveAction: (outcome: 'failure' | 'success') => {
        outcome: 'failure' | 'success'
    } // apiStatusLogic
    setTimeSensitiveAuthenticationRequired: (required: boolean | [onSuccess: () => void, onFailure: () => void]) => {
        required: boolean | [onSuccess: () => void, onFailure: () => void]
    } // apiStatusLogic
    loadUser: (resetOnFailure?: boolean | undefined) => {
        resetOnFailure: boolean | undefined
    } // userLogic
    beginPasskey2FA: () => {
        value: true
    }
    beginPasskey2FAFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    beginPasskey2FASuccess: (
        passkey2FA: null,
        payload?: {
            value: true
        }
    ) => {
        passkey2FA: null
        payload?: {
            value: true
        }
    }
    beginSsoReauthentication: (provider: SSOProvider) => {
        provider: SSOProvider
    }
    checkPasskeysAvailable: () => {
        value: true
    }
    checkPasskeysAvailableFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    checkPasskeysAvailableSuccess: (
        passkeysAvailable: boolean,
        payload?: {
            value: true
        }
    ) => {
        passkeysAvailable: boolean
        payload?: {
            value: true
        }
    }
    checkReauthentication: () => {
        value: true
    }
    precheck: () => any
    precheckFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    precheckSuccess: (
        precheckResponse: PrecheckResponseType | null,
        payload?: any
    ) => {
        precheckResponse: PrecheckResponseType | null
        payload?: any
    }
    resetReauthentication: (values?: ReauthenticationForm) => {
        values?: ReauthenticationForm
    }
    sendSetPasswordLink: () => {
        value: true
    }
    sendSetPasswordLinkFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    sendSetPasswordLinkSuccess: (
        setPasswordLinkSentTo: string | null,
        payload?: {
            value: true
        }
    ) => {
        setPasswordLinkSentTo: string | null
        payload?: {
            value: true
        }
    }
    setDismissedReauthentication: (value: boolean) => {
        value: boolean
    }
    setReauthenticationManualErrors: (errors: Record<string, any>) => {
        errors: Record<string, any>
    }
    setReauthenticationValue: (
        key: FieldName,
        value: any
    ) => {
        name: FieldName
        value: any
    }
    setReauthenticationValues: (values: DeepPartial<ReauthenticationForm>) => {
        values: DeepPartial<ReauthenticationForm>
    }
    setRequiresTwoFactor: (value: boolean) => {
        value: boolean
    }
    setTotpAvailable: (available: boolean) => {
        available: boolean
    }
    showSsoReauthenticationError: () => {
        value: true
    }
    ssoReauthenticationFinished: (
        attempt: string,
        errorCode: string | null
    ) => {
        attempt: string
        errorCode: string | null
    }
    submitReauthentication: () => {
        value: boolean
    }
    submitReauthenticationFailure: (
        error: Error,
        errors: Record<string, any>
    ) => {
        error: Error
        errors: Record<string, any>
    }
    submitReauthenticationRequest: (reauthentication: ReauthenticationForm) => {
        reauthentication: ReauthenticationForm
    }
    submitReauthenticationSuccess: (reauthentication: ReauthenticationForm) => {
        reauthentication: ReauthenticationForm
    }
    touchReauthenticationField: (key: string) => {
        key: string
    }
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface timeSensitiveAuthenticationLogicMeta {
    __keaTypeGenInternalSelectorTypes: {
        showAuthenticationModal: (
            timeSensitiveAuthenticationRequired: boolean | [onSuccess: () => void, onFailure: () => void],
            dismissedReauthentication: boolean
        ) => boolean
        sensitiveSessionExpiresAt: (user: UserType | null) => Dayjs
    }
}

export type timeSensitiveAuthenticationLogicType = MakeLogicType<
    timeSensitiveAuthenticationLogicValues,
    timeSensitiveAuthenticationLogicActions,
    Record<string, any>,
    timeSensitiveAuthenticationLogicMeta
>

export const timeSensitiveAuthenticationLogic = kea<timeSensitiveAuthenticationLogicType>([
    path(['lib', 'components', 'timeSensitiveAuthenticationLogic']),
    connect(() => ({
        values: [
            apiStatusLogic,
            ['timeSensitiveAuthenticationRequired'],
            userLogic,
            ['user'],
            modalInterruptionTrackingLogic,
            ['interruptedForm'],
        ],
        actions: [
            apiStatusLogic,
            ['setTimeSensitiveAuthenticationRequired', 'resolveSensitiveAction'],
            userLogic,
            ['loadUser'],
        ],
        logic: [modalInterruptionTrackingLogic],
    })),
    actions({
        setDismissedReauthentication: (value: boolean) => ({ value }),
        setRequiresTwoFactor: (value: boolean) => ({ value }),
        checkReauthentication: true,
        showSsoReauthenticationError: true,
        beginSsoReauthentication: (provider: SSOProvider) => ({ provider }),
        ssoReauthenticationFinished: (attempt: string, errorCode: string | null) => ({ attempt, errorCode }),
        beginPasskey2FA: true,
        checkPasskeysAvailable: true,
        sendSetPasswordLink: true,
        setTotpAvailable: (available: boolean) => ({ available }),
    }),
    reducers({
        dismissedReauthentication: [
            false,
            {
                setDismissedReauthentication: (_, { value }) => value,
                setTimeSensitiveAuthenticationRequired: () => false,
            },
        ],

        twoFactorRequired: [
            false,
            {
                setRequiresTwoFactor: (_, { value }) => value,
            },
        ],
        totpAvailable: [
            true as boolean,
            {
                setTotpAvailable: (_, { available }) => available,
            },
        ],
    }),

    loaders(({ values, actions }) => ({
        precheckResponse: [
            null as PrecheckResponseType | null,
            {
                precheck: async () => {
                    // nosemgrep: prefer-codegen-api -- Legacy raw API call with a hand-written URL and an unchecked response type. No generated function covers this endpoint yet. Find out why the generated client skips it (no schema, no product tag, or excluded from the spec) and fix that first.
                    const response = await api.create('api/login/precheck', { email: values.user!.email })
                    return { status: 'completed', ...response }
                },
            },
        ],
        passkey2FA: [
            null as null,
            {
                beginPasskey2FA: async (_, breakpoint) => {
                    breakpoint()

                    // Step 1: Get authentication options from server
                    const beginResponse =
                        // nosemgrep: prefer-codegen-api -- Legacy raw API call with a hand-written URL and an unchecked response type. No generated function covers this endpoint yet. Find out why the generated client skips it (no schema, no product tag, or excluded from the spec) and fix that first.
                        await api.create<PublicKeyCredentialRequestOptionsJSON>('api/login/2fa/passkey/begin/')

                    // Step 2: Use SimpleWebAuthn to get assertion from authenticator
                    const assertion = await startAuthentication({
                        optionsJSON: {
                            challenge: beginResponse.challenge,
                            timeout: beginResponse.timeout,
                            rpId: beginResponse.rpId,
                            allowCredentials: beginResponse.allowCredentials,
                            userVerification: beginResponse.userVerification as UserVerificationRequirement,
                        },
                    })

                    // Step 3: Send assertion to server to complete 2FA
                    // nosemgrep: prefer-codegen-api -- Legacy raw API call with a hand-written URL and an unchecked response type. No generated function covers this endpoint yet. Find out why the generated client skips it (no schema, no product tag, or excluded from the spec) and fix that first.
                    await api.create('api/login/token', {
                        credential_id: assertion.id,
                        response: assertion.response,
                    })

                    return null
                },
            },
        ],
        setPasswordLinkSentTo: [
            null as string | null,
            {
                sendSetPasswordLink: async (_, breakpoint) => {
                    breakpoint()
                    const email = values.user?.email
                    if (!email) {
                        return null
                    }
                    // On an account without a password, the reset link sets its first password. The reset page
                    // works while signed in, so this is the way out when the user's passkey stops working.
                    // nosemgrep: prefer-codegen-api -- Legacy raw API call with a hand-written URL and an unchecked response type. No generated function covers this endpoint yet. Find out why the generated client skips it (no schema, no product tag, or excluded from the spec) and fix that first.
                    await api.create('api/reset/', { email })
                    posthog.capture('reauthentication_set_password_link_sent')
                    return email
                },
            },
        ],
        passkeysAvailable: [
            false as boolean,
            {
                checkPasskeysAvailable: async () => {
                    try {
                        // Get available 2FA methods
                        // nosemgrep: prefer-codegen-api -- Legacy raw API call with a hand-written URL and an unchecked response type. No generated function covers this endpoint yet. Find out why the generated client skips it (no schema, no product tag, or excluded from the spec) and fix that first.
                        const methods = await api.get<TwoFAMethodsResponse>('api/login/2fa/passkey/methods/')
                        // Store TOTP availability for UI
                        actions.setTotpAvailable(methods.has_totp)
                        return methods.has_passkeys
                    } catch {
                        // If it fails, assume no passkeys and TOTP might be available
                        actions.setTotpAvailable(true)
                        return false
                    }
                },
            },
        ],
    })),

    forms(({ actions, values }) => ({
        reauthentication: {
            defaults: {} as unknown as ReauthenticationForm,
            errors: ({ password, token }) => ({
                password: !password ? 'Please enter your password to continue' : undefined,
                token: values.twoFactorRequired && !token ? 'Please enter your 2FA code' : undefined,
            }),
            submit: async ({ password, token }, breakpoint): Promise<void> => {
                const email = userLogic.findMounted()?.values.user?.email
                await breakpoint(150)

                try {
                    if (!token) {
                        // nosemgrep: prefer-codegen-api -- Legacy raw API call with a hand-written URL and an unchecked response type. No generated function covers this endpoint yet. Find out why the generated client skips it (no schema, no product tag, or excluded from the spec) and fix that first.
                        await api.create('api/login', { email, password })
                    } else {
                        // nosemgrep: prefer-codegen-api -- Legacy raw API call with a hand-written URL and an unchecked response type. No generated function covers this endpoint yet. Find out why the generated client skips it (no schema, no product tag, or excluded from the spec) and fix that first.
                        await api.create('api/login/token', { token })
                    }
                } catch (e: unknown) {
                    if (e instanceof ApiError) {
                        if (e.code === '2fa_required') {
                            actions.setRequiresTwoFactor(true)
                            // Check for available 2FA methods when 2FA is required
                            actions.checkPasskeysAvailable()
                        }
                        if (e.code === 'invalid_credentials') {
                            actions.setReauthenticationManualErrors({ password: 'Incorrect password' })
                        }
                    }

                    throw e
                }
            },
        },
    })),

    selectors({
        showAuthenticationModal: [
            (s) => [s.timeSensitiveAuthenticationRequired, s.dismissedReauthentication],
            (
                timeSensitiveAuthenticationRequired: boolean | [onSuccess: () => void, onFailure: () => void],
                dismissedReauthentication: boolean
            ): boolean => {
                return !!timeSensitiveAuthenticationRequired && !dismissedReauthentication
            },
        ],

        sensitiveSessionExpiresAt: [
            (s) => [s.user],
            (user: null | import('../../../types').UserType): Dayjs => {
                return dayjs(user?.sensitive_session_expires_at)
            },
        ],
    }),

    subscriptions(({ values, actions }) => ({
        showAuthenticationModal: (shown) => {
            if (shown) {
                posthog.capture('reauthentication_modal_shown', {
                    interrupted_form: values.interruptedForm,
                })

                const modalTrackingLogic = modalInterruptionTrackingLogic.findMounted()
                if (modalTrackingLogic) {
                    modalTrackingLogic.actions.setInterruptedForm(null)
                }

                if (!values.precheckResponse) {
                    actions.precheck()
                }
            }
        },
    })),

    listeners(({ actions, values, cache }) => ({
        submitReauthenticationSuccess: () => {
            posthog.capture('reauthentication_completed')
            actions.resolveSensitiveAction('success')
            // Refresh the user so we know the new session expiry
            actions.loadUser()
        },
        beginPasskey2FASuccess: () => {
            posthog.capture('reauthentication_completed', { method: 'passkey_2fa' })
            actions.resolveSensitiveAction('success')
            // Refresh the user so we know the new session expiry
            actions.loadUser()
        },
        setDismissedReauthentication: ({ value }) => {
            if (value) {
                posthog.capture('reauthentication_modal_dismissed')
                actions.resolveSensitiveAction('failure')
            }
        },
        beginSsoReauthentication: ({ provider }) => {
            const params = { email: values.user?.email || '', reauth: 'true' }
            const redirectInPage = (): void => {
                window.location.href = getSocialLoginUrl(provider, {
                    ...params,
                    next: location.href.replace(location.origin, ''),
                })
            }
            // SAML posts back cross-site without the session cookie, so the backend runs a fresh login that can
            // switch accounts. In a popup that switch would be invisible and the pending write would retry as
            // the other account.
            if (provider === 'saml') {
                redirectInPage()
                return
            }
            cache.ssoReauthAttempt = uuid()
            // A popup keeps this page, and the request waiting on re-auth, alive.
            const popup = window.open(
                getSocialLoginUrl(
                    provider,
                    { ...params, next: `${SSO_REAUTH_COMPLETE_PATH}?attempt=${cache.ssoReauthAttempt}` },
                    {}
                ),
                'posthog-sso-reauth',
                'popup,width=600,height=700'
            )
            if (!popup) {
                redirectInPage()
            }
        },
        ssoReauthenticationFinished: ({ attempt, errorCode }) => {
            // Anyone can open the completion page, and every tab hears it. Only the attempt this tab started counts.
            if (!cache.ssoReauthAttempt || attempt !== cache.ssoReauthAttempt) {
                return
            }
            cache.ssoReauthAttempt = null
            cache.ssoReauthChannel.postMessage({ type: 'sso_reauth_received', attempt })
            if (errorCode) {
                lemonToast.error(ERROR_MESSAGES[errorCode] ?? ERROR_MESSAGES.social_login_failure)
                return
            }
            posthog.capture('reauthentication_completed', { method: 'sso_popup' })
            actions.resolveSensitiveAction('success')
            actions.loadUser()
        },
        showSsoReauthenticationError: () => {
            // A failed SSO re-auth keeps the session and comes back to the page that opened the modal,
            // carrying the reason as a query param (see posthog.helpers.sso.sso_failure_redirect_url).
            const { error_code, error_detail, ...remainingParams } = router.values.searchParams
            if (!error_code || !(error_code in ERROR_MESSAGES)) {
                return
            }
            lemonToast.error(ERROR_MESSAGES[error_code])
            router.actions.replace(router.values.location.pathname, remainingParams, router.values.hashParams)
        },
        checkReauthentication: () => {
            if (values.sensitiveSessionExpiresAt.diff(dayjs(), 'seconds') < LOOKAHEAD_EXPIRY_SECONDS) {
                // Here we try to offer a better UX by forcing re-authentication if they are about to timeout
                // which is nicer than when they try to do something later and get a 403.
                // We also make this a promise, so that `checkReauthentication` callsites can await
                // `asyncActions.checkReauthentication()` and proceed once the flow concludes.
                // Dismissal/failure resolves rather than rejects: the mount-time dispatch is
                // fire-and-forget, so a rejection (especially a bare `reject()`) surfaces as an
                // unhandled TypeError in kea's listener wrapper.
                return new Promise<void>((resolve) =>
                    actions.setTimeSensitiveAuthenticationRequired([resolve, resolve])
                )
            }
        },
    })),
    afterMount(({ actions, cache }) => {
        actions.showSsoReauthenticationError()
        cache.disposables.add(
            () => {
                const channel = new BroadcastChannel(SSO_REAUTH_CHANNEL)
                cache.ssoReauthChannel = channel
                channel.onmessage = (event: MessageEvent) => {
                    if (event.data?.type === 'sso_reauth_complete') {
                        actions.ssoReauthenticationFinished(String(event.data.attempt), event.data.error_code ?? null)
                    }
                }
                return () => channel.close()
            },
            'ssoReauthChannel',
            // The popup reports back while this tab can be hidden behind it.
            { pauseOnPageHidden: false }
        )
    }),
])