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.

16.6 KB
Raw Blame
import { type PublicKeyCredentialDescriptorJSON, startAuthentication, startRegistration } from '@simplewebauthn/browser'
import { MakeLogicType, actions, connect, kea, listeners, path, reducers } from 'kea'
import { loaders } from 'kea-loaders'

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

import api from 'lib/api'
import { twoFactorLogic } from 'scenes/authentication/two-factor-setup/twoFactorLogic'
import { userLogic } from 'scenes/userLogic'

import { getPasskeyErrorMessage } from './passkeys/utils'

export interface PasskeyCredential {
    id: number
    label: string
    created_at: string
    transports: string[]
    verified: boolean
    authenticator_type: 'platform' | 'hardware' | 'hybrid' | 'unknown'
}

export interface RegistrationBeginResponse {
    rp: { id: string; name: string }
    user: { id: string; name: string; displayName: string }
    challenge: string
    pubKeyCredParams: Array<{ type: 'public-key'; alg: number }>
    timeout: number
    excludeCredentials: PublicKeyCredentialDescriptorJSON[]
    authenticatorSelection: { residentKey: string; userVerification: string }
    attestation: string
    already_registered?: boolean
}

export interface RegistrationCompleteResponse {
    success: boolean
    message: string
    credential_id: string
}

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

export type RegistrationStep = 'idle' | 'registering' | 'verifying' | 'complete'

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface passkeySettingsLogicValues {
    deleteModalId: number | null
    error: string | null
    passkeys: PasskeyCredential[]
    passkeysLoading: boolean
    registerPasskey: null
    registerPasskeyLoading: boolean
    registrationLabel: string
    registrationStep: RegistrationStep
    renameModal: {
        currentLabel: string
        id: number
    } | null
    verifyingPasskeyId: number | null
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface passkeySettingsLogicActions {
    loadStatus: () => {
        value: true
    } // twoFactorLogic
    loadUser: (resetOnFailure?: boolean | undefined) => {
        resetOnFailure: boolean | undefined
    } // userLogic
    beginRegistration: (label: string) => {
        label: string
    }
    beginRegistrationFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    beginRegistrationSuccess: (
        registerPasskey: null,
        payload?: {
            label: string
        }
    ) => {
        registerPasskey: null
        payload?: {
            label: string
        }
    }
    clearError: () => {
        value: true
    }
    closeDeleteModal: () => {
        value: true
    }
    closeRenameModal: () => {
        value: true
    }
    deletePasskey: (id: number) => {
        id: number
    }
    deletePasskeyFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    deletePasskeySuccess: (
        passkeys: PasskeyCredential[],
        payload?: {
            id: number
        }
    ) => {
        passkeys: PasskeyCredential[]
        payload?: {
            id: number
        }
    }
    loadPasskeys: () => any
    loadPasskeysFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    loadPasskeysSuccess: (
        passkeys: PasskeyCredential[],
        payload?: any
    ) => {
        passkeys: PasskeyCredential[]
        payload?: any
    }
    openDeleteModal: (id: number) => {
        id: number
    }
    openRenameModal: (
        id: number,
        currentLabel: string
    ) => {
        currentLabel: string
        id: number
    }
    renamePasskey: (
        id: number,
        label: string
    ) => {
        id: number
        label: string
    }
    renamePasskeyFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    renamePasskeySuccess: (
        passkeys: PasskeyCredential[],
        payload?: {
            id: number
            label: string
        }
    ) => {
        passkeys: PasskeyCredential[]
        payload?: {
            id: number
            label: string
        }
    }
    setError: (error: string | null) => {
        error: string | null
    }
    setRegistrationStep: (step: RegistrationStep) => {
        step: RegistrationStep
    }
    verifyPasskey: (id: number) => {
        id: number
    }
    verifyPasskeyFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    verifyPasskeySuccess: (
        passkeys: PasskeyCredential[],
        payload?: {
            id: number
        }
    ) => {
        passkeys: PasskeyCredential[]
        payload?: {
            id: number
        }
    }
}

export type passkeySettingsLogicType = MakeLogicType<passkeySettingsLogicValues, passkeySettingsLogicActions>

export const passkeySettingsLogic = kea<passkeySettingsLogicType>([
    path(['scenes', 'settings', 'user', 'passkeySettingsLogic']),
    connect(() => ({
        actions: [userLogic, ['loadUser'], twoFactorLogic, ['loadStatus']],
    })),
    actions({
        beginRegistration: (label: string) => ({ label }),
        setRegistrationStep: (step: RegistrationStep) => ({ step }),
        setError: (error: string | null) => ({ error }),
        clearError: true,
        deletePasskey: (id: number) => ({ id }),
        renamePasskey: (id: number, label: string) => ({ id, label }),
        verifyPasskey: (id: number) => ({ id }),
        openDeleteModal: (id: number) => ({ id }),
        closeDeleteModal: true,
        openRenameModal: (id: number, currentLabel: string) => ({ id, currentLabel }),
        closeRenameModal: true,
    }),
    reducers({
        registrationStep: [
            'idle' as RegistrationStep,
            {
                setRegistrationStep: (_, { step }) => step,
                beginRegistration: () => 'registering',
            },
        ],
        registrationLabel: [
            '' as string,
            {
                beginRegistration: (_, { label }) => label,
                setRegistrationStep: (state, { step }) => (step === 'idle' ? '' : state),
            },
        ],
        error: [
            null as string | null,
            {
                setError: (_, { error }) => error,
                clearError: () => null,
                beginRegistration: () => null,
                verifyPasskeySuccess: () => null,
            },
        ],
        deleteModalId: [
            null as number | null,
            {
                openDeleteModal: (_, { id }) => id,
                closeDeleteModal: () => null,
                deletePasskeySuccess: () => null,
            },
        ],
        renameModal: [
            null as { id: number; currentLabel: string } | null,
            {
                openRenameModal: (_, { id, currentLabel }) => ({ id, currentLabel }),
                closeRenameModal: () => null,
                renamePasskeySuccess: () => null,
            },
        ],
        verifyingPasskeyId: [
            null as number | null,
            {
                verifyPasskey: (_, { id }) => id,
                verifyPasskeySuccess: () => null,
                verifyPasskeyFailure: () => null,
            },
        ],
    }),
    loaders(({ actions, values }) => ({
        passkeys: [
            [] as PasskeyCredential[],
            {
                loadPasskeys: 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.get<PasskeyCredential[]>('api/webauthn/credentials/')
                    return response
                },
                deletePasskey: async ({ id }) => {
                    // 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.delete(`api/webauthn/credentials/${id}/`)
                    lemonToast.success('Passkey deleted')
                    return values.passkeys.filter((p: PasskeyCredential) => p.id !== id)
                },
                renamePasskey: async ({ id, label }) => {
                    // 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 updated = await api.update<PasskeyCredential>(`api/webauthn/credentials/${id}/`, { label })
                    lemonToast.success('Passkey renamed')
                    return values.passkeys.map((p: PasskeyCredential) => (p.id === id ? updated : p))
                },
                verifyPasskey: async ({ id }) => {
                    try {
                        // Step 1: Begin verification
                        // 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 verifyResponse = await api.create<VerificationBeginResponse>(
                            `api/webauthn/credentials/${id}/verify`
                        )

                        // Step 2: Verify with authenticator
                        const assertion = await startAuthentication({
                            optionsJSON: {
                                challenge: verifyResponse.challenge,
                                timeout: verifyResponse.timeout,
                                rpId: verifyResponse.rpId,
                                allowCredentials: verifyResponse.allowCredentials,
                                userVerification: verifyResponse.userVerification as UserVerificationRequirement,
                            },
                        })

                        // Step 3: Complete verification
                        // 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 updated = await api.create<PasskeyCredential>(
                            `api/webauthn/credentials/${id}/verify_complete`,
                            assertion
                        )

                        lemonToast.success('Passkey verified successfully!')
                        return values.passkeys.map((p: PasskeyCredential) => (p.id === id ? updated : p))
                    } catch (e: any) {
                        actions.setError(getPasskeyErrorMessage(e, 'Failed to verify passkey. Please try again.'))
                        throw e
                    }
                },
            },
        ],
        registerPasskey: [
            null as null,
            {
                beginRegistration: async ({ label }) => {
                    try {
                        // Step 1: Get registration options
                        // 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<RegistrationBeginResponse>('api/webauthn/register/begin')

                        // Step 2: Create credential with authenticator
                        const attestation = await startRegistration({
                            optionsJSON: {
                                rp: beginResponse.rp,
                                user: beginResponse.user,
                                challenge: beginResponse.challenge,
                                pubKeyCredParams: beginResponse.pubKeyCredParams as PublicKeyCredentialParameters[],
                                timeout: beginResponse.timeout,
                                excludeCredentials: beginResponse.excludeCredentials,
                                authenticatorSelection:
                                    beginResponse.authenticatorSelection as AuthenticatorSelectionCriteria,
                                attestation: beginResponse.attestation as AttestationConveyancePreference,
                            },
                        })

                        // Step 3: Send attestation to 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 { credential_id: credentialId } = await api.create<RegistrationCompleteResponse>(
                            'api/webauthn/register/complete',
                            {
                                ...attestation,
                                label,
                            }
                        )

                        // Load passkeys so the new passkey appears in the list even if verification fails
                        actions.loadPasskeys()

                        // Step 4: Begin verification
                        actions.setRegistrationStep('verifying')

                        // 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 verifyResponse = await api.create<VerificationBeginResponse>(
                            `api/webauthn/credentials/${credentialId}/verify`
                        )

                        // Step 5: Verify with authenticator
                        const assertion = await startAuthentication({
                            optionsJSON: {
                                challenge: verifyResponse.challenge,
                                timeout: verifyResponse.timeout,
                                rpId: verifyResponse.rpId,
                                allowCredentials: verifyResponse.allowCredentials,
                                userVerification: verifyResponse.userVerification as UserVerificationRequirement,
                            },
                        })

                        // Step 6: Complete verification
                        // 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/credentials/${credentialId}/verify_complete`, assertion)

                        actions.setRegistrationStep('complete')
                        lemonToast.success('Passkey added successfully!')
                        actions.loadPasskeys()
                        actions.loadUser()
                        actions.loadStatus()

                        return null
                    } catch (e: any) {
                        actions.setRegistrationStep('idle')
                        actions.setError(getPasskeyErrorMessage(e, 'Failed to register passkey. Please try again.'))
                        // Load passkeys in case the passkey was created but verification failed
                        actions.loadPasskeys()
                        throw e
                    }
                },
            },
        ],
    })),
    listeners(({ actions }) => ({
        deletePasskeySuccess: () => {
            actions.loadUser()
            actions.loadStatus()
        },
        verifyPasskeySuccess: () => {
            actions.loadUser()
            actions.loadStatus()
        },
    })),
])