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.

11.4 KB
Raw Blame
import { type PublicKeyCredentialRequestOptionsJSON, startAuthentication } from '@simplewebauthn/browser'
import { MakeLogicType, actions, connect, kea, listeners, path, reducers } from 'kea'
import { forms } from 'kea-forms'
import type { DeepPartial, DeepPartialMap, FieldName, ValidationErrorType } from 'kea-forms'
import { loaders } from 'kea-loaders'
import { urlToAction } from 'kea-router'

import api, { ApiError } from 'lib/api'
import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
import { preflightLogic } from 'lib/logic/preflightLogic'
import { redirectAfterLogin } from 'lib/utils/loginRedirect'
import { getPasskeyErrorMessage, isWebAuthnCancellation } from 'scenes/settings/user/passkeys/utils'
import { urls } from 'scenes/urls'

import type { FeatureFlagsSet } from '../../../lib/logic/featureFlagLogic'
import type { PreflightStatus } from '../../../types'

export interface AuthenticateResponseType {
    success: boolean
    errorCode?: string
    errorDetail?: string
}

export interface TwoFactorForm {
    token: string
}

export enum LoginStep {
    LOGIN = 'login',
    TWO_FACTOR = 'two_factor',
}

export interface TwoFAMethodsResponse {
    has_totp: boolean
    has_passkeys: boolean
}

export interface LoginTokenResponse {
    success: boolean
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface login2FALogicValues {
    featureFlags: FeatureFlagsSet // featureFlagLogic
    preflight: PreflightStatus | null // preflightLogic
    generalError: {
        code: string
        detail: string
    } | null
    isTwofactortokenSubmitting: boolean
    isTwofactortokenValid: boolean
    passkey2FA: null
    passkey2FALoading: boolean
    passkey2FAWasCancelled: boolean
    passkeysAvailable: boolean
    passkeysAvailableLoading: boolean
    showTwofactortokenErrors: boolean
    totpAvailable: boolean
    twofactortoken: TwoFactorForm
    twofactortokenAllErrors: Record<string, any>
    twofactortokenChanged: boolean
    twofactortokenErrors: DeepPartialMap<TwoFactorForm, ValidationErrorType>
    twofactortokenHasErrors: boolean
    twofactortokenManualErrors: Record<string, any>
    twofactortokenTouched: boolean
    twofactortokenTouches: Record<string, boolean>
    twofactortokenValidationErrors: DeepPartialMap<TwoFactorForm, ValidationErrorType>
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface login2FALogicActions {
    beginPasskey2FA: () => {
        value: true
    }
    beginPasskey2FAFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    beginPasskey2FASuccess: (
        passkey2FA: null,
        payload?: {
            value: true
        }
    ) => {
        passkey2FA: null
        payload?: {
            value: true
        }
    }
    checkPasskeysAvailable: () => {
        value: true
    }
    checkPasskeysAvailableFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    checkPasskeysAvailableSuccess: (
        passkeysAvailable: boolean,
        payload?: {
            value: true
        }
    ) => {
        passkeysAvailable: boolean
        payload?: {
            value: true
        }
    }
    clearGeneralError: () => {
        value: true
    }
    passkey2FACancelled: () => {
        value: true
    }
    resetTwofactortoken: (values?: TwoFactorForm) => {
        values?: TwoFactorForm
    }
    setGeneralError: (
        code: string,
        detail: string
    ) => {
        code: string
        detail: string
    }
    setLoginStep: (step: LoginStep) => {
        step: LoginStep
    }
    setTotpAvailable: (available: boolean) => {
        available: boolean
    }
    setTwofactortokenManualErrors: (errors: Record<string, any>) => {
        errors: Record<string, any>
    }
    setTwofactortokenValue: (
        key: FieldName,
        value: any
    ) => {
        name: FieldName
        value: any
    }
    setTwofactortokenValues: (values: DeepPartial<TwoFactorForm>) => {
        values: DeepPartial<TwoFactorForm>
    }
    submitTwofactortoken: () => {
        value: boolean
    }
    submitTwofactortokenFailure: (
        error: Error,
        errors: Record<string, any>
    ) => {
        error: Error
        errors: Record<string, any>
    }
    submitTwofactortokenRequest: (twofactortoken: TwoFactorForm) => {
        twofactortoken: TwoFactorForm
    }
    submitTwofactortokenSuccess: (twofactortoken: TwoFactorForm) => {
        twofactortoken: TwoFactorForm
    }
    touchTwofactortokenField: (key: string) => {
        key: string
    }
}

export type login2FALogicType = MakeLogicType<login2FALogicValues, login2FALogicActions>

export const login2FALogic = kea<login2FALogicType>([
    path(['scenes', 'authentication', 'login-2fa', 'login2FALogic']),
    connect(() => ({
        values: [preflightLogic, ['preflight'], featureFlagLogic, ['featureFlags']],
    })),
    actions({
        setGeneralError: (code: string, detail: string) => ({ code, detail }),
        setLoginStep: (step: LoginStep) => ({ step }),
        clearGeneralError: true,
        beginPasskey2FA: true,
        passkey2FACancelled: true,
        checkPasskeysAvailable: true,
        setTotpAvailable: (available: boolean) => ({ available }),
    }),
    reducers({
        generalError: [
            null as { code: string; detail: string } | null,
            {
                setGeneralError: (_, error) => error,
                clearGeneralError: () => null,
            },
        ],
        totpAvailable: [
            true as boolean,
            {
                setTotpAvailable: (_, { available }) => available,
            },
        ],
        passkey2FAWasCancelled: [
            false,
            {
                beginPasskey2FA: () => false,
                passkey2FACancelled: () => true,
            },
        ],
    }),
    loaders(({ actions }) => ({
        passkey2FA: [
            null as null,
            {
                beginPasskey2FA: async (_, breakpoint) => {
                    breakpoint()
                    try {
                        // 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,
                            },
                        })

                        // 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<LoginTokenResponse>('api/login/token', {
                            credential_id: assertion.id,
                            response: assertion.response,
                        })

                        return null
                    } catch (e: unknown) {
                        if (isWebAuthnCancellation(e)) {
                            // Expected user cancellation — fully swallow so it
                            // doesn't surface in the UI or in error tracking.
                            actions.passkey2FACancelled()
                            return null
                        }
                        actions.setGeneralError('passkey_error', getPasskeyErrorMessage(e))
                        throw e
                    }
                },
            },
        ],
        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 }) => ({
        twofactortoken: {
            defaults: { token: '' } as TwoFactorForm,
            errors: ({ token }) => ({
                token: !token ? 'Please enter a token to continue' : null,
            }),
            submit: async ({ token }, breakpoint) => {
                breakpoint()
                try {
                    // 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<LoginTokenResponse>('api/login/token', { token })
                } catch (e: unknown) {
                    if (e instanceof ApiError) {
                        actions.setGeneralError(e.code || 'unknown_error', e.detail || 'An error occurred')
                    } else {
                        actions.setGeneralError('unknown_error', 'An unexpected error occurred')
                    }
                    throw e
                }
            },
        },
    })),
    listeners(({ values }) => ({
        submitTwofactortokenSuccess: () => {
            redirectAfterLogin()
        },
        beginPasskey2FASuccess: () => {
            // The loader returns null on user cancellation to avoid surfacing
            // the DOMException to global error capture. Skip the post-login
            // redirect/reload path in that case so the user stays on the
            // 2FA screen and can retry.
            if (values.passkey2FAWasCancelled) {
                return
            }
            redirectAfterLogin()
        },
    })),
    // The server answers this only for a pending 2FA session. Kea mounts this logic alongside
    // anything that references its actions, so the route, not the mount, decides when to ask.
    urlToAction(({ actions }) => ({
        [urls.login2FA()]: () => {
            actions.checkPasskeysAvailable()
        },
    })),
])