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.

13.9 KB
Raw Blame
import {
    browserSupportsWebAuthnAutofill,
    type PublicKeyCredentialDescriptorJSON,
    startAuthentication,
} from '@simplewebauthn/browser'
import { MakeLogicType, actions, connect, kea, listeners, path, reducers } from 'kea'
import type { FieldName } from 'kea-forms'
import { loaders } from 'kea-loaders'
import { router } from 'kea-router'
import posthog from 'posthog-js'

import api from 'lib/api'
import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'
import { apiStatusLogic } from 'lib/logic/apiStatusLogic'
import { isWebKitBrowser } from 'lib/utils/dom'
import { redirectAfterLogin } from 'lib/utils/loginRedirect'
import { loginLogic } from 'scenes/authentication/auth/loginLogic'
import { ssoEnforcedMessage } from 'scenes/authentication/shared/loginErrorMessages'
import { getPasskeyErrorMessage, isWebAuthnCancellation } from 'scenes/settings/user/passkeys/utils'
import { urls } from 'scenes/urls'
import { userLogic } from 'scenes/userLogic'

export interface PasskeyLoginBeginResponse {
    challenge: string
    timeout: number
    rpId: string
    allowCredentials: PublicKeyCredentialDescriptorJSON[]
    userVerification: string
}

export interface BeginPasskeyLoginParams {
    next?: string
    email?: string
    reauth?: 'true' | 'false'
}

// A login on an unverified account fails with code `verify_email_pending` and the user
// uuid in `detail`. The page at /verify_email/<uuid> has the code entry form.
function routeToEmailVerification(e: unknown): boolean {
    const { code, detail } = (e ?? {}) as Record<string, any>
    if (code !== 'verify_email_pending' || typeof detail !== 'string') {
        return false
    }
    lemonToast.info('Verify your email to continue. We just sent you a new code.')
    const next: string | undefined = router.values.searchParams.next
    router.actions.push(urls.verifyEmail(detail), next ? { next } : {})
    return true
}

// A discoverable passkey is picked before any email is typed, so an SSO-enforced account is only
// refused at the complete step. The response carries the account's email: prefill it and run the
// precheck, which swaps the password form for the required SSO button.
function showPasskeyLoginError(e: unknown, actions: passkeyLogicType['actions']): void {
    const { code, data } = (e ?? {}) as Record<string, any>
    if (code !== 'sso_enforced') {
        actions.setGeneralError('passkey_error', getPasskeyErrorMessage(e))
        return
    }
    // The code stays `passkey_error` so login telemetry keeps counting this as a passkey step.
    actions.setGeneralError('passkey_error', ssoEnforcedMessage(data?.sso_enforcement))
    if (data?.email) {
        actions.setLoginValue('email', data.email)
        actions.precheck({ email: data.email })
    }
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface passkeyLogicValues {
    allowCredentialsFromPrecheck: PublicKeyCredentialDescriptorJSON[]
    isLoading: boolean
    isReauth: boolean
    loginWithPasskey: null
    loginWithPasskeyLoading: boolean
    redirectLink: string | undefined
    wasCancelled: boolean
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface passkeyLogicActions {
    resolveSensitiveAction: (outcome: 'failure' | 'success') => {
        outcome: 'failure' | 'success'
    } // apiStatusLogic
    precheck: (args_0: { autoAttempt?: boolean; email: string }) => {
        autoAttempt?: boolean
        email: string
    } // loginLogic
    setGeneralError: (
        code: string,
        detail: string
    ) => {
        code: string
        detail: string
    } // loginLogic
    setLoginValue: (
        key: FieldName,
        value: any
    ) => {
        name: FieldName
        value: any
    } // loginLogic
    loadUser: (resetOnFailure?: boolean | undefined) => {
        resetOnFailure: boolean | undefined
    } // userLogic
    beginPasskeyLogin: (
        allowCredentials?: PublicKeyCredentialDescriptorJSON[],
        params?: BeginPasskeyLoginParams
    ) => {
        allowCredentials: PublicKeyCredentialDescriptorJSON[] | undefined
        params: BeginPasskeyLoginParams | undefined
    }
    passkeyAuthenticationCancelled: () => {
        value: true
    }
    reset: () => {
        value: true
    }
    startConditionalPasskeyLogin: () => {
        value: true
    }
    startPasskeyAuthentication: () => {
        value: true
    }
    startPasskeyAuthenticationFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    startPasskeyAuthenticationSuccess: (
        loginWithPasskey: null,
        payload?: {
            value: true
        }
    ) => {
        loginWithPasskey: null
        payload?: {
            value: true
        }
    }
}

export type passkeyLogicType = MakeLogicType<passkeyLogicValues, passkeyLogicActions>

export const passkeyLogic = kea<passkeyLogicType>([
    path(['scenes', 'authentication', 'shared', 'passkeyLogic']),
    connect(() => ({
        actions: [
            loginLogic,
            ['setGeneralError', 'setLoginValue', 'precheck'],
            apiStatusLogic,
            ['resolveSensitiveAction'],
            userLogic,
            ['loadUser'],
        ],
    })),
    actions({
        beginPasskeyLogin: (
            allowCredentials?: PublicKeyCredentialDescriptorJSON[],
            params?: BeginPasskeyLoginParams
        ) => ({ allowCredentials, params }),
        startPasskeyAuthentication: true,
        startConditionalPasskeyLogin: true,
        passkeyAuthenticationCancelled: true,
        reset: true,
    }),
    reducers({
        allowCredentialsFromPrecheck: [
            [] as PublicKeyCredentialDescriptorJSON[],
            {
                beginPasskeyLogin: (state, { allowCredentials }) => allowCredentials ?? state,
                reset: () => [],
            },
        ],
        redirectLink: [
            undefined as string | undefined,
            {
                beginPasskeyLogin: (state, { params }) => params?.next ?? state,
            },
        ],
        isReauth: [
            false,
            {
                beginPasskeyLogin: (_, { params }) => params?.reauth === 'true',
                reset: () => false,
            },
        ],
        isLoading: [
            false,
            {
                beginPasskeyLogin: () => true,
                startPasskeyAuthenticationSuccess: () => false,
                startPasskeyAuthenticationFailure: () => false,
                reset: () => false,
            },
        ],
        wasCancelled: [
            false,
            {
                beginPasskeyLogin: () => false,
                passkeyAuthenticationCancelled: () => true,
            },
        ],
    }),
    loaders(({ values, actions }) => ({
        loginWithPasskey: [
            null as null,
            {
                startPasskeyAuthentication: async () => {
                    try {
                        // Step 1: Get authentication options from server
                        // 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 beginResponse = await api.create<PasskeyLoginBeginResponse>('api/webauthn/login/begin/')

                        // Step 2: Use SimpleWebAuthn to get assertion from authenticator
                        // Use provided allowCredentials if available (from precheck), otherwise use server response
                        const precheckCredentials = values.allowCredentialsFromPrecheck ?? []
                        const credentialsToUse =
                            precheckCredentials.length > 0 ? precheckCredentials : beginResponse.allowCredentials

                        const assertion = await startAuthentication({
                            optionsJSON: {
                                challenge: beginResponse.challenge,
                                timeout: beginResponse.timeout,
                                rpId: beginResponse.rpId,
                                allowCredentials: credentialsToUse,
                                userVerification: beginResponse.userVerification as UserVerificationRequirement,
                            },
                        })

                        // Step 3: Send assertion to server to complete login
                        // 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/webauthn/login/complete/', assertion)

                        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.passkeyAuthenticationCancelled()
                            return null
                        }
                        if (routeToEmailVerification(e)) {
                            // Throw so the failure listener resets the passkey state. The user
                            // continues on the verification page, not with a login error.
                            throw e
                        }
                        showPasskeyLoginError(e, actions)
                        throw e
                    }
                },
            },
        ],
    })),
    listeners(({ actions, values, cache }) => ({
        beginPasskeyLogin: () => {
            // Don't start a second passkey sign-in while one is already in flight (e.g. a
            // double-clicked passkey button) — concurrent WebAuthn requests hang WebKit.
            if (values.loginWithPasskeyLoading) {
                return
            }
            // After setting credentials in reducer, start the authentication
            actions.startPasskeyAuthentication()
        },
        startConditionalPasskeyLogin: async () => {
            // WebKit-only. Safari/iOS freeze on the auto-modal, so there we offer passkeys via the
            // email field's autofill instead
            if (!isWebKitBrowser()) {
                return
            }
            // Latch synchronously before the first await so a repeat trigger can't race past the guard.
            if (cache.passkeyAutofillStarted) {
                return
            }
            cache.passkeyAutofillStarted = true
            if (!(await browserSupportsWebAuthnAutofill())) {
                return
            }
            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.
                const beginResponse = await api.create<PasskeyLoginBeginResponse>('api/webauthn/login/begin/')
                const assertion = await startAuthentication({
                    optionsJSON: {
                        challenge: beginResponse.challenge,
                        timeout: beginResponse.timeout,
                        rpId: beginResponse.rpId,
                        // Conditional UI must not constrain credentials — the browser offers whatever
                        // discoverable passkeys exist for this site.
                        allowCredentials: [],
                        userVerification: beginResponse.userVerification as UserVerificationRequirement,
                    },
                    useBrowserAutofill: true,
                })
                // 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/webauthn/login/complete/', assertion)
                redirectAfterLogin()
            } catch (e: unknown) {
                // The autofill passkey prompt is routinely dismissed — the user types a password
                // instead, or navigates away. Swallow those; surface anything genuinely wrong.
                if (!isWebAuthnCancellation(e) && !routeToEmailVerification(e)) {
                    showPasskeyLoginError(e, actions)
                }
            }
        },
        startPasskeyAuthenticationSuccess: async () => {
            // 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
            // login screen and can retry.
            if (values.wasCancelled) {
                actions.reset()
                return
            }
            // for reauth, clear authentication required flag
            if (values.isReauth) {
                posthog.capture('reauthentication_completed', { method: 'passkey' })
                actions.resolveSensitiveAction('success')
                actions.loadUser()
                actions.reset()
                return
            }

            // For regular login, load the destination as a fresh document so its app context is the
            // logged-in one. `redirectLink` is guarded against other origins by `redirectAfterLogin`.
            redirectAfterLogin(values.redirectLink)
        },
        startPasskeyAuthenticationFailure: () => {
            // Reset state on real authentication failures so the user can fall
            // back to the normal login flow (e.g., password + 2FA).
            actions.reset()
        },
    })),
])