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.

33.0 KB
Raw Blame
import { startRegistration } from '@simplewebauthn/browser'
import { MakeLogicType, actions, connect, kea, listeners, path, reducers, selectors } from 'kea'
import { forms } from 'kea-forms'
import type { DeepPartial, DeepPartialMap, FieldName, ValidationErrorType } from 'kea-forms'
import { router, urlToAction } from 'kea-router'
import posthog from 'posthog-js'

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

import api, { ApiError } from 'lib/api'
import { ValidatedPasswordResult, validatePassword } from 'lib/components/PasswordStrength'
import { getReferralFollowUp } from 'lib/components/SignupReferralSource'
import { CLOUD_HOSTNAMES, FEATURE_FLAGS } from 'lib/constants'
import { dayjs } from 'lib/dayjs'
import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
import { preflightLogic } from 'lib/logic/preflightLogic'
import { splitFullName } from 'lib/utils/strings'
import { getRelativeNextPath } from 'lib/utils/url'
import { readPendingOAuthConnection } from 'scenes/authentication/shared/pendingOAuthConnectionLogic'
import {
    clearPendingVerificationEmail,
    setPendingVerificationEmail,
} from 'scenes/authentication/shared/verificationCode'
import { getPasskeyErrorMessage, isWebAuthnCancellation } from 'scenes/settings/user/passkeys/utils'
import { RegistrationBeginResponse } from 'scenes/settings/user/passkeySettingsLogic'
import { urls } from 'scenes/urls'

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

export interface AccountResponse {
    success: boolean
    redirect_url?: string
    errorCode?: string
    errorDetail?: string
    errorAttribute?: string
}

export interface SignupPanelAuthForm {
    password: string
}

export interface SignupPanelOnboardingForm {
    name: string
    organization_name: string
    role_at_organization: string
    referral_source: string
    referral_source_ai_prompt: string
    referral_source_influencer: string
}

export interface PendingInvite {
    organization_name: string
}

interface SignupEmailPrecheckResponse {
    email_exists: boolean
    code?: string
    detail?: string
    pending_invite?: PendingInvite | null
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface signupLogicValues {
    featureFlags: FeatureFlagsSet // featureFlagLogic
    preflight: PreflightStatus | null // preflightLogic
    challengeNonce: string | null
    challengeRequired: boolean
    isPasskeyRegistering: boolean
    isPendingInviteResending: boolean
    isSignupEmailChecking: boolean
    isSignupPanelAuthSubmitting: boolean
    isSignupPanelAuthValid: boolean
    isSignupPanelOnboardingSubmitting: boolean
    isSignupPanelOnboardingValid: boolean
    panel: number
    passkeyError: string | null
    passkeyRegistered: boolean
    pendingInvite: PendingInvite | null
    pendingInviteResent: boolean
    showSignupPanelAuthErrors: boolean
    showSignupPanelOnboardingErrors: boolean
    signupEmail: string
    signupEmailError: string | null
    signupEmailTaken: boolean
    signupPanelAuth: SignupPanelAuthForm
    signupPanelAuthAllErrors: Record<string, any>
    signupPanelAuthChanged: boolean
    signupPanelAuthErrors: DeepPartialMap<SignupPanelAuthForm, ValidationErrorType>
    signupPanelAuthHasErrors: boolean
    signupPanelAuthManualErrors: Record<string, any>
    signupPanelAuthTouched: boolean
    signupPanelAuthTouches: Record<string, boolean>
    signupPanelAuthValidationErrors: DeepPartialMap<SignupPanelAuthForm, ValidationErrorType>
    signupPanelOnboarding: SignupPanelOnboardingForm
    signupPanelOnboardingAllErrors: Record<string, any>
    signupPanelOnboardingChanged: boolean
    signupPanelOnboardingErrors: DeepPartialMap<SignupPanelOnboardingForm, ValidationErrorType>
    signupPanelOnboardingHasErrors: boolean
    signupPanelOnboardingManualErrors: Record<string, any>
    signupPanelOnboardingTouched: boolean
    signupPanelOnboardingTouches: Record<string, boolean>
    signupPanelOnboardingValidationErrors: DeepPartialMap<SignupPanelOnboardingForm, ValidationErrorType>
    turnstileSiteKey: string | null
    turnstileToken: string | null
    validatedPassword: ValidatedPasswordResult
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface signupLogicActions {
    dismissPendingInvite: () => {
        value: true
    }
    finishSignupEmailPrecheck: () => {
        value: true
    }
    precheckSignupEmail: (email: string) => {
        email: string
    }
    registerPasskey: () => {
        value: true
    }
    resendPendingInvite: (email: string) => {
        email: string
    }
    resetChallenge: () => {
        value: true
    }
    resetSignupCredentials: () => {
        value: true
    }
    resetSignupPanelAuth: (values?: SignupPanelAuthForm) => {
        values?: SignupPanelAuthForm
    }
    resetSignupPanelOnboarding: (values?: SignupPanelOnboardingForm) => {
        values?: SignupPanelOnboardingForm
    }
    setChallengeNonce: (nonce: string | null) => {
        nonce: string | null
    }
    setChallengeRequired: (required: boolean) => {
        required: boolean
    }
    setPanel: (panel: number) => {
        panel: number
    }
    setPasskeyError: (error: string | null) => {
        error: string | null
    }
    setPasskeyRegistered: (registered: boolean) => {
        registered: boolean
    }
    setPasskeyRegistering: (registering: boolean) => {
        registering: boolean
    }
    setPendingInvite: (invite: PendingInvite | null) => {
        invite: PendingInvite | null
    }
    setPendingInviteResending: (resending: boolean) => {
        resending: boolean
    }
    setPendingInviteResent: (resent: boolean) => {
        resent: boolean
    }
    setSignupEmail: (email: string) => {
        email: string
    }
    setSignupEmailError: (
        error: string | null,
        isTaken?: boolean
    ) => {
        error: string | null
        isTaken: boolean
    }
    setSignupPanelAuthManualErrors: (errors: Record<string, any>) => {
        errors: Record<string, any>
    }
    setSignupPanelAuthValue: (
        key: FieldName,
        value: any
    ) => {
        name: FieldName
        value: any
    }
    setSignupPanelAuthValues: (values: DeepPartial<SignupPanelAuthForm>) => {
        values: DeepPartial<SignupPanelAuthForm>
    }
    setSignupPanelOnboardingManualErrors: (errors: Record<string, any>) => {
        errors: Record<string, any>
    }
    setSignupPanelOnboardingValue: (
        key: FieldName,
        value: any
    ) => {
        name: FieldName
        value: any
    }
    setSignupPanelOnboardingValues: (values: DeepPartial<SignupPanelOnboardingForm>) => {
        values: DeepPartial<SignupPanelOnboardingForm>
    }
    setTurnstileSiteKey: (siteKey: string | null) => {
        siteKey: string | null
    }
    setTurnstileToken: (token: string | null) => {
        token: string | null
    }
    submitSignupPanelAuth: () => {
        value: boolean
    }
    submitSignupPanelAuthFailure: (
        error: Error,
        errors: Record<string, any>
    ) => {
        error: Error
        errors: Record<string, any>
    }
    submitSignupPanelAuthRequest: (signupPanelAuth: SignupPanelAuthForm) => {
        signupPanelAuth: SignupPanelAuthForm
    }
    submitSignupPanelAuthSuccess: (signupPanelAuth: SignupPanelAuthForm) => {
        signupPanelAuth: SignupPanelAuthForm
    }
    submitSignupPanelOnboarding: () => {
        value: boolean
    }
    submitSignupPanelOnboardingFailure: (
        error: Error,
        errors: Record<string, any>
    ) => {
        error: Error
        errors: Record<string, any>
    }
    submitSignupPanelOnboardingRequest: (signupPanelOnboarding: SignupPanelOnboardingForm) => {
        signupPanelOnboarding: SignupPanelOnboardingForm
    }
    submitSignupPanelOnboardingSuccess: (signupPanelOnboarding: SignupPanelOnboardingForm) => {
        signupPanelOnboarding: SignupPanelOnboardingForm
    }
    touchSignupPanelAuthField: (key: string) => {
        key: string
    }
    touchSignupPanelOnboardingField: (key: string) => {
        key: string
    }
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface signupLogicMeta {
    __keaTypeGenInternalSelectorTypes: {
        validatedPassword: (signupPanelAuth: SignupPanelAuthForm) => ValidatedPasswordResult
    }
}

export type signupLogicType = MakeLogicType<signupLogicValues, signupLogicActions, Record<string, any>, signupLogicMeta>

const MAINTENANCE_REGIONS = ['eu', 'us'] as const
type MaintenanceRegion = (typeof MAINTENANCE_REGIONS)[number]

/** The cloud region that takes all signups while the other one is under maintenance, if any. */
function maintenanceSignupRegion(
    preflight: PreflightStatus | null,
    featureFlags: FeatureFlagsSet
): MaintenanceRegion | null {
    const region = featureFlags[FEATURE_FLAGS.REDIRECT_SIGNUPS_TO_INSTANCE]
    if (!preflight?.cloud || typeof region !== 'string') {
        return null
    }
    return (MAINTENANCE_REGIONS as readonly string[]).includes(region) ? (region as MaintenanceRegion) : null
}

/**
 * Where to send a signup on this instance while the other region takes all signups, or null to stay.
 * The `email` carries over, so the person does not type it again on the other instance. A pending
 * OAuth connection always stays, because its client is registered in this region.
 */
export function maintenanceSignupRedirectUrl(
    preflight: PreflightStatus | null,
    featureFlags: FeatureFlagsSet,
    email?: string
): string | null {
    if (readPendingOAuthConnection()) {
        return null
    }
    const region = maintenanceSignupRegion(preflight, featureFlags)
    // KLUDGE: the backend can technically return null, and we don't want to redirect to the app
    // unless the preflight region is valid
    const currentRegion = preflight?.region?.toLowerCase()
    if (!region || !currentRegion || !(MAINTENANCE_REGIONS as readonly string[]).includes(currentRegion)) {
        return null
    }
    if (region === currentRegion) {
        return null
    }
    const params = new URLSearchParams({ maintenanceRedirect: 'true' })
    if (email) {
        params.set('email', email)
    }
    return `https://${CLOUD_HOSTNAMES[region.toUpperCase() as keyof typeof CLOUD_HOSTNAMES]}${urls.signup()}?${params}`
}

function getRetryAfterSeconds(error: unknown): number | null {
    const header = error instanceof ApiError ? error.headers?.get('Retry-After') : null
    const seconds = header ? Number(header) : NaN
    return Number.isFinite(seconds) && seconds > 0 ? seconds : null
}

function throttledSignupMessage(retryAfterSeconds: number | null, googleAvailable: boolean): string {
    const retryAfter =
        retryAfterSeconds !== null ? dayjs.duration(retryAfterSeconds, 'seconds').humanize(true) : 'later'
    const googleSuggestion = googleAvailable ? ', or sign up with Google instead' : ''
    return `Too many signup attempts from your network. Try again ${retryAfter}${googleSuggestion}.`
}

export const signupLogic = kea<signupLogicType>([
    path(['scenes', 'authentication', 'auth', 'signupLogic']),
    connect(() => ({
        values: [preflightLogic, ['preflight'], featureFlagLogic, ['featureFlags']],
    })),
    actions(() => ({
        setPanel: (panel: number) => ({ panel }),
        // The signup precheck refuses aliases of an existing address and finds pending invites
        precheckSignupEmail: (email: string) => ({ email }),
        setSignupEmail: (email: string) => ({ email }),
        // `isTaken`: the email, or an alias of it, already has an account, so the error offers login
        setSignupEmailError: (error: string | null, isTaken: boolean = false) => ({ error, isTaken }),
        finishSignupEmailPrecheck: true,
        // Clears the password and passkey picked for the previous email
        resetSignupCredentials: true,
        // Passkey actions
        registerPasskey: true,
        setPasskeyRegistered: (registered: boolean) => ({ registered }),
        setPasskeyRegistering: (registering: boolean) => ({ registering }),
        setPasskeyError: (error: string | null) => ({ error }),
        // Turnstile challenge actions
        setChallengeRequired: (required: boolean) => ({ required }),
        setChallengeNonce: (nonce: string | null) => ({ nonce }),
        setTurnstileSiteKey: (siteKey: string | null) => ({ siteKey }),
        setTurnstileToken: (token: string | null) => ({ token }),
        resetChallenge: true,
        // Pending-invite banner actions
        setPendingInvite: (invite: PendingInvite | null) => ({ invite }),
        dismissPendingInvite: true,
        resendPendingInvite: (email: string) => ({ email }),
        setPendingInviteResent: (resent: boolean) => ({ resent }),
        setPendingInviteResending: (resending: boolean) => ({ resending }),
    })),
    reducers(() => ({
        panel: [
            0,
            {
                setPanel: (_, { panel }) => panel,
                // Set here rather than in a listener, so the panel never reads 0 between the two
                dismissPendingInvite: () => 1,
            },
        ],
        signupEmail: [
            '',
            {
                precheckSignupEmail: (_, { email }) => email,
                setSignupEmail: (_, { email }) => email,
            },
        ],
        signupEmailError: [
            null as string | null,
            {
                precheckSignupEmail: () => null,
                setSignupEmailError: (_, { error }) => error,
            },
        ],
        signupEmailTaken: [
            false,
            {
                precheckSignupEmail: () => false,
                setSignupEmailError: (_, { isTaken }) => isTaken,
            },
        ],
        isSignupEmailChecking: [
            false,
            {
                precheckSignupEmail: () => true,
                finishSignupEmailPrecheck: () => false,
            },
        ],
        passkeyRegistered: [
            false,
            {
                setPasskeyRegistered: (_, { registered }) => registered,
            },
        ],
        isPasskeyRegistering: [
            false,
            {
                setPasskeyRegistering: (_, { registering }) => registering,
            },
        ],
        passkeyError: [
            null as string | null,
            {
                setPasskeyError: (_, { error }) => error,
                registerPasskey: () => null,
            },
        ],
        challengeRequired: [
            false,
            {
                setChallengeRequired: (_, { required }) => required,
                resetChallenge: () => false,
            },
        ],
        challengeNonce: [
            null as string | null,
            {
                setChallengeNonce: (_, { nonce }) => nonce,
                resetChallenge: () => null,
            },
        ],
        turnstileSiteKey: [
            null as string | null,
            {
                setTurnstileSiteKey: (_, { siteKey }) => siteKey,
            },
        ],
        turnstileToken: [
            null as string | null,
            {
                setTurnstileToken: (_, { token }) => token,
                resetChallenge: () => null,
            },
        ],
        pendingInvite: [
            null as PendingInvite | null,
            {
                setPendingInvite: (_, { invite }) => invite,
                dismissPendingInvite: () => null,
            },
        ],
        pendingInviteResent: [
            false,
            {
                setPendingInviteResent: (_, { resent }) => resent,
                setPendingInvite: () => false,
                dismissPendingInvite: () => false,
            },
        ],
        isPendingInviteResending: [
            false,
            {
                setPendingInviteResending: (_, { resending }) => resending,
            },
        ],
    })),
    forms(({ actions, values }) => ({
        signupPanelAuth: {
            alwaysShowErrors: true,
            showErrorsOnTouch: true,
            defaults: {
                password: '',
            } as SignupPanelAuthForm,
            errors: ({ password }) => ({
                // Password not required if passkey is registered
                password:
                    !values.passkeyRegistered && !values.preflight?.demo
                        ? !password
                            ? 'Please enter your password to continue'
                            : values.validatedPassword.feedback || undefined
                        : undefined,
            }),
            // Same reason as the email panel: a manual error left behind by the server would block
            // every later submit of this form.
            preSubmit: () => {
                actions.setSignupPanelAuthManualErrors({})
            },
            submit: async () => {
                actions.setPanel(2)
            },
        },
        signupPanelOnboarding: {
            alwaysShowErrors: true,
            showErrorsOnTouch: true,
            defaults: {
                name: '',
                organization_name: '',
                role_at_organization: '',
                // The partner that started the OAuth connection is where this person heard about PostHog
                referral_source: readPendingOAuthConnection()?.clientName ?? '',
                referral_source_ai_prompt: '',
                referral_source_influencer: '',
            } as SignupPanelOnboardingForm,
            errors: ({ name, role_at_organization }) => ({
                name: !name?.trim() ? 'Please enter your name' : undefined,
                role_at_organization: !role_at_organization ? 'Please select your role in the organization' : undefined,
            }),
            // Same reason as the email panel: without this, the generic or name error left behind by
            // a failed signup would make every retry of this form a no-op.
            preSubmit: () => {
                actions.setSignupPanelOnboardingManualErrors({})
            },
            submit: async (payload, breakpoint) => {
                breakpoint()
                // A new signup attempt must not inherit the address a previous attempt stored
                clearPendingVerificationEmail()
                try {
                    const nextUrl = getRelativeNextPath(new URLSearchParams(location.search).get('next'), location)

                    // An answer typed into a follow-up that a later referral source edit hid again must not be sent
                    const followUp = getReferralFollowUp(payload.referral_source ?? '')
                    const signupData: Record<string, any> = {
                        email: values.signupEmail,
                        ...splitFullName(payload.name),
                        organization_name: payload.organization_name?.trim() || undefined,
                        role_at_organization: payload.role_at_organization,
                        referral_source: payload.referral_source,
                        referral_source_ai_prompt: followUp === 'ai' ? payload.referral_source_ai_prompt : '',
                        referral_source_influencer: followUp === 'influencer' ? payload.referral_source_influencer : '',
                        next_url: nextUrl ?? undefined,
                    }

                    // Only include password for password-based signup
                    if (!values.passkeyRegistered && values.signupPanelAuth.password) {
                        signupData.password = values.signupPanelAuth.password
                    }

                    if (values.turnstileToken && values.challengeNonce) {
                        signupData.turnstile_token = values.turnstileToken
                        signupData.challenge_nonce = values.challengeNonce
                    }

                    // 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 res = await api.create('api/signup/', signupData)

                    if (!payload.organization_name?.trim()) {
                        posthog.capture('sign up organization name not provided')
                    }

                    if (values.passkeyRegistered) {
                        posthog.capture('signup completed with passkey')
                    }

                    // The verify page has no session yet, so store the address for its copy,
                    // keyed by the user uuid from the redirect path
                    const verifyUuid = res.redirect_url?.match(/\/verify_email\/([^/?#]+)/)?.[1]
                    if (verifyUuid && signupData.email) {
                        setPendingVerificationEmail(verifyUuid, signupData.email)
                    }
                    // it's ok to trust the url sent from the server
                    // nosemgrep: javascript.browser.security.open-redirect.js-open-redirect
                    location.href = res.redirect_url || '/'
                } catch (e) {
                    const error = e as Record<string, any>

                    if (error.code === 'challenge_required') {
                        actions.setTurnstileToken(null)
                        actions.setChallengeNonce(error.data?.extra?.challenge_nonce)
                        actions.setTurnstileSiteKey(error.data?.extra?.turnstile_site_key)
                        actions.setChallengeRequired(true)
                        return
                    }

                    actions.resetChallenge()

                    // If the server returns an email validation error, send the user back to the
                    // email step so the error appears next to the field that caused it.
                    // DRF sends `attr: 'email'`, and an older body shape keys the message by field
                    const emailError = error.attr === 'email' ? error.detail : error.data?.email
                    if (emailError) {
                        const message = Array.isArray(emailError) ? String(emailError[0]) : String(emailError)
                        // A passkey registered for this email would fail the next submit the same way
                        actions.resetSignupCredentials()
                        actions.setSignupEmailError(message, error.code === 'unique')
                        actions.setPanel(0)
                        return
                    }

                    // The strength meter fails open while its zxcvbn chunk is loading, so a password it
                    // never scored can reach the server and be refused there. Send the user back to the
                    // password step.
                    if (error.attr === 'password') {
                        // The session lost the passkey, so a submit without a password would fail the same way
                        if (values.passkeyRegistered) {
                            actions.setPasskeyRegistered(false)
                        }
                        actions.setSignupPanelAuthManualErrors({
                            password: String(error.detail || 'Please choose a stronger password'),
                        })
                        actions.setPanel(1)
                        return
                    }

                    // The `name` input is split into first_name/last_name for the API — surface
                    // errors on those attributes next to the field the user actually sees.
                    // Must throw (not return) so kea-forms marks the submit as failed and keeps
                    // showing errors — on a successful submit it hides them again.
                    if (error.attr === 'first_name' || error.attr === 'last_name') {
                        actions.setSignupPanelOnboardingManualErrors({
                            name: String(error.detail || 'Please enter your name'),
                        })
                        throw e
                    }

                    if (error.code === 'throttled') {
                        const retryAfterSeconds = getRetryAfterSeconds(e)
                        posthog.capture('signup throttled', {
                            retry_after_seconds: retryAfterSeconds,
                            with_passkey: values.passkeyRegistered,
                        })
                        const googleAvailable = !!values.preflight?.available_social_auth_providers?.['google-oauth2']
                        actions.setSignupPanelOnboardingManualErrors({
                            generic: {
                                code: error.code,
                                detail: throttledSignupMessage(retryAfterSeconds, googleAvailable),
                            },
                        })
                    } else {
                        actions.setSignupPanelOnboardingManualErrors({
                            generic: {
                                code: error.code,
                                detail: error.detail,
                            },
                        })
                    }
                    throw e
                }
            },
        },
    })),
    selectors({
        validatedPassword: [
            (s) => [s.signupPanelAuth],
            (signupPanelAuth: SignupPanelAuthForm): ValidatedPasswordResult => {
                return validatePassword(signupPanelAuth.password)
            },
        ],
    }),
    listeners(({ actions, values }) => ({
        precheckSignupEmail: async ({ email }, breakpoint) => {
            actions.setPasskeyError(null)
            // Reset rather than `setSignupPanelAuthManualErrors({})`: kea-forms turns error display on with
            // any manual errors call, so the empty password field would open with a red error
            actions.resetSignupPanelAuth()
            let precheckResponse: SignupEmailPrecheckResponse
            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.
                precheckResponse = await api.create<SignupEmailPrecheckResponse>('api/signup/precheck', { email })
            } catch (e: any) {
                breakpoint()
                actions.finishSignupEmailPrecheck()
                if (e?.status === 409 || e?.code === 'account_exists') {
                    actions.setSignupEmailError(
                        e?.detail || 'There is already an account with this email address.',
                        true
                    )
                    actions.setPanel(0)
                    return
                }
                const fieldError = e?.data?.email
                actions.setSignupEmailError(
                    fieldError
                        ? Array.isArray(fieldError)
                            ? String(fieldError[0])
                            : String(fieldError)
                        : e?.detail || 'Could not verify your email. Please try again.'
                )
                return
            }
            breakpoint()
            actions.finishSignupEmailPrecheck()
            const pendingInvite = precheckResponse.pending_invite ?? null
            if (pendingInvite && (router.values.searchParams as Record<string, string>).skip_invite_check !== '1') {
                actions.setPendingInvite(pendingInvite)
                return
            }
            actions.setPendingInvite(null)
            // Demo is passwordless — skip the password/passkey panel straight to onboarding.
            actions.setPanel(values.preflight?.demo ? 2 : 1)
        },
        resendPendingInvite: async ({ email }, breakpoint) => {
            actions.setPendingInviteResending(true)
            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('api/signup/resend-invite', { email })
                breakpoint()
                actions.setPendingInviteResent(true)
            } catch {
                lemonToast.error('Could not resend the invite email. Please try again.')
            } finally {
                actions.setPendingInviteResending(false)
            }
        },
        resetSignupCredentials: () => {
            actions.setPasskeyRegistered(false)
            actions.setPasskeyError(null)
            actions.resetSignupPanelAuth()
        },
        setPasskeyRegistered: ({ registered }) => {
            if (registered) {
                // Advance to onboarding panel after successful passkey registration
                actions.setPanel(2)
            }
        },
        setTurnstileToken: ({ token }) => {
            if (token && values.challengeNonce) {
                actions.submitSignupPanelOnboarding()
            }
        },
        registerPasskey: async () => {
            const email = values.signupEmail
            if (!email) {
                actions.setPasskeyError('Email is required')
                return
            }

            actions.setPasskeyRegistering(true)
            actions.setPasskeyError(null)

            try {
                // Step 1: Begin registration - get 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<RegistrationBeginResponse>(
                    'api/webauthn/signup-register/begin/',
                    { email }
                )

                if (beginResponse.already_registered) {
                    actions.setPasskeyRegistered(true)
                    actions.setSignupPanelAuthValue('password', '')
                    return
                }

                // Step 2: Create credential using SimpleWebAuthn
                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: Complete registration - 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.
                await api.create('api/webauthn/signup-register/complete/', attestation)

                actions.setPasskeyRegistered(true)
                actions.setSignupPanelAuthValue('password', '') // Clear password since we're using passkey
            } catch (e: any) {
                if (!isWebAuthnCancellation(e)) {
                    actions.setPasskeyError(getPasskeyErrorMessage(e, 'Failed to register passkey. Please try again.'))
                }
            } finally {
                actions.setPasskeyRegistering(false)
            }
        },
    })),
    urlToAction(({ actions, values }) => ({
        '/signup': (_, { email, maintenanceRedirect }) => {
            const redirectUrl = maintenanceSignupRedirectUrl(values.preflight, values.featureFlags, email)
            if (redirectUrl) {
                window.location.href = redirectUrl
            }
            const region = maintenanceSignupRegion(values.preflight, values.featureFlags)
            if (maintenanceRedirect && region) {
                lemonToast.info(
                    `You've been redirected to signup on our ${region.toUpperCase()} instance while we perform maintenance on our other instance.`
                )
            }
            // Outside demo mode, `authLogic` puts `?email=` into the shared email field
            if (email && values.preflight?.demo) {
                // In demo mode no password is needed, so we can log in right away
                // This allows us to give a quick login link in the `generate_demo_data` command
                // X and Y are placeholders, irrelevant because the account should already exists
                actions.setSignupEmail(email)
                actions.setSignupPanelOnboardingValues({
                    name: 'X',
                    organization_name: 'Y',
                    role_at_organization: 'other',
                })
                actions.submitSignupPanelOnboarding()
            }
        },
    })),
])