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.

19.1 KB
Raw Blame
import { startRegistration } from '@simplewebauthn/browser'
import { MakeLogicType, actions, 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, urlToAction } from 'kea-router'
import posthog from 'posthog-js'

import api from 'lib/api'
import { ValidatedPasswordResult, validatePassword } from 'lib/components/PasswordStrength'
import { getRelativeNextPath } from 'lib/utils/url'
import { getPasskeyErrorMessage } from 'scenes/settings/user/passkeys/utils'
import type { RegistrationBeginResponse } from 'scenes/settings/user/passkeySettingsLogic'

import { PrevalidatedInvite } from '~/types'

export enum ErrorCodes {
    InvalidInvite = 'invalid_invite',
    InvalidRecipient = 'invalid_recipient',
    UserAlreadyMember = 'user_already_member',
    Unknown = 'unknown',
}

export interface ErrorInterface {
    code: ErrorCodes
    detail?: string
}

export interface AcceptInvitePayloadInterface {
    first_name?: string
    password?: string
    role_at_organization?: string
}

const LOGIC_PATH = ['scenes', 'authentication', 'invite-signup', 'inviteSignupLogic']
const FORM_KEY = 'signup'

// In the order the form renders them, so a failed submit lands on the first field to fix
const FIELDS_IN_RENDER_ORDER: (keyof AcceptInvitePayloadInterface)[] = ['password', 'first_name']

// kea-forms ids each field input `<logic path>.<form key>.<field>`
const fieldInputId = (field: keyof AcceptInvitePayloadInterface): string => [...LOGIC_PATH, FORM_KEY, field].join('.')

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface inviteSignupLogicValues {
    acceptedInvite: null
    acceptedInviteLoading: boolean
    challengeNonce: string | null
    challengeRequired: boolean
    error: ErrorInterface | null
    invite: PrevalidatedInvite | null
    inviteLoading: boolean
    isPasskeyRegistering: boolean
    isSignupSubmitting: boolean
    isSignupValid: boolean
    passkeyError: string | null
    passkeyRegistered: boolean
    showSignupErrors: boolean
    signup: AcceptInvitePayloadInterface
    signupAllErrors: Record<string, any>
    signupChanged: boolean
    signupErrors: DeepPartialMap<AcceptInvitePayloadInterface, ValidationErrorType>
    signupHasErrors: boolean
    signupManualErrors: Record<string, any>
    signupTouched: boolean
    signupTouches: Record<string, boolean>
    signupValidationErrors: DeepPartialMap<AcceptInvitePayloadInterface, 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 inviteSignupLogicActions {
    acceptInvite: () => any
    acceptInviteFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    acceptInviteSuccess: (
        acceptedInvite: Promise<null> | null,
        payload?: any
    ) => {
        acceptedInvite: Promise<null> | null
        payload?: any
    }
    prevalidateInvite: (id: string) => string
    prevalidateInviteFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    prevalidateInviteSuccess: (
        invite: PrevalidatedInvite | null,
        payload?: string
    ) => {
        invite: PrevalidatedInvite | null
        payload?: string
    }
    registerPasskey: () => {
        value: true
    }
    resetChallenge: () => {
        value: true
    }
    resetSignup: (values?: AcceptInvitePayloadInterface) => {
        values?: AcceptInvitePayloadInterface
    }
    setChallengeNonce: (nonce: string | null) => {
        nonce: string | null
    }
    setChallengeRequired: (required: boolean) => {
        required: boolean
    }
    setError: (payload: ErrorInterface) => {
        payload: ErrorInterface
    }
    setPasskeyError: (error: string | null) => {
        error: string | null
    }
    setPasskeyRegistered: (registered: boolean) => {
        registered: boolean
    }
    setPasskeyRegistering: (registering: boolean) => {
        registering: boolean
    }
    setSignupManualErrors: (errors: Record<string, any>) => {
        errors: Record<string, any>
    }
    setSignupValue: (
        key: FieldName,
        value: any
    ) => {
        name: FieldName
        value: any
    }
    setSignupValues: (values: DeepPartial<AcceptInvitePayloadInterface>) => {
        values: DeepPartial<AcceptInvitePayloadInterface>
    }
    setTurnstileSiteKey: (siteKey: string | null) => {
        siteKey: string | null
    }
    setTurnstileToken: (token: string | null) => {
        token: string | null
    }
    submitSignup: () => {
        value: boolean
    }
    submitSignupFailure: (
        error: Error,
        errors: Record<string, any>
    ) => {
        error: Error
        errors: Record<string, any>
    }
    submitSignupRequest: (signup: AcceptInvitePayloadInterface) => {
        signup: AcceptInvitePayloadInterface
    }
    submitSignupSuccess: (signup: AcceptInvitePayloadInterface) => {
        signup: AcceptInvitePayloadInterface
    }
    touchSignupField: (key: string) => {
        key: string
    }
}

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

export type inviteSignupLogicType = MakeLogicType<
    inviteSignupLogicValues,
    inviteSignupLogicActions,
    Record<string, any>,
    inviteSignupLogicMeta
>

export const inviteSignupLogic = kea<inviteSignupLogicType>([
    path(LOGIC_PATH),
    actions({
        setError: (payload: ErrorInterface) => ({ payload }),
        registerPasskey: true,
        setPasskeyRegistered: (registered: boolean) => ({ registered }),
        setPasskeyRegistering: (registering: boolean) => ({ registering }),
        setPasskeyError: (error: string | null) => ({ error }),
        setChallengeRequired: (required: boolean) => ({ required }),
        setChallengeNonce: (nonce: string | null) => ({ nonce }),
        setTurnstileSiteKey: (siteKey: string | null) => ({ siteKey }),
        setTurnstileToken: (token: string | null) => ({ token }),
        resetChallenge: true,
    }),
    reducers({
        error: [
            null as ErrorInterface | null,
            {
                setError: (_, { payload }) => payload,
            },
        ],
        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,
            },
        ],
    }),
    loaders(({ actions, values }) => ({
        invite: [
            null as PrevalidatedInvite | null,
            {
                prevalidateInvite: async (id: string, 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.
                        return await api.get(`api/signup/${id}/`)
                    } catch (e: any) {
                        if (e.status === 400) {
                            if (e.code === 'invalid_recipient') {
                                actions.setError({ code: ErrorCodes.InvalidRecipient, detail: e.detail })
                            } else if (e.code === 'user_already_member') {
                                actions.setError({ code: ErrorCodes.UserAlreadyMember, detail: e.detail })
                            } else if (e.code === 'account_exists') {
                                location.href = e.detail
                            } else {
                                actions.setError({ code: ErrorCodes.InvalidInvite, detail: e.detail })
                            }
                        } else {
                            actions.setError({ code: ErrorCodes.Unknown })
                        }
                        return null
                    }
                },
            },
        ],
        acceptedInvite: [
            null,
            {
                acceptInvite: () => {
                    if (!values.invite) {
                        return null
                    }
                    // 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.
                    return api.create(`api/signup/${values.invite.id}/`)
                },
            },
        ],
    })),
    forms(({ actions, values }) => ({
        signup: {
            options: {
                showErrorsOnTouch: true,
            },
            defaults: { role_at_organization: '' } as AcceptInvitePayloadInterface,
            errors: ({ password, first_name }) => ({
                password:
                    !values.passkeyRegistered && !password
                        ? 'Please enter your password to continue'
                        : !values.passkeyRegistered
                          ? values.validatedPassword.feedback || undefined
                          : undefined,
                first_name: !first_name ? 'Please enter your name' : undefined,
            }),
            // A manual error from a rejected attempt counts as a validation error, and nothing touches
            // `generic` to clear it. Without this, every later submit fails without a request.
            preSubmit: () => {
                actions.setSignupManualErrors({})
            },
            submit: async (payload, breakpoint) => {
                breakpoint()

                if (!values.invite) {
                    return
                }

                try {
                    const submitPayload: Record<string, any> = { ...payload }
                    if (values.passkeyRegistered) {
                        delete submitPayload.password
                    }

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

                    const nextUrl = getRelativeNextPath(router.values.searchParams['next'], location)
                    if (nextUrl) {
                        submitPayload.next_url = nextUrl
                    }

                    // 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/${values.invite.id}/`, submitPayload)
                    location.href = res.redirect_url || '/' // hard refresh because the current_organization changed
                } 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
                    }

                    // A 5xx or lost-response (undefined status) submit can still have committed the
                    // account server-side. The invite is deleted in that same transaction, so probe the
                    // email instead (it survives). Reaching this form means prevalidate found no account,
                    // so one existing now was created by this submit — send them to login, not a
                    // misleading signup error.
                    const targetEmail = values.invite?.target_email
                    if ((error.status === undefined || error.status >= 500) && targetEmail) {
                        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/precheck', { email: targetEmail })
                        } catch (probeError) {
                            const probe = probeError as Record<string, any>
                            if (probe.status === 409 || probe.code === 'account_exists') {
                                location.href = '/login'
                                return
                            }
                        }
                    }

                    actions.resetChallenge()
                    posthog.captureException(e)
                    actions.setSignupManualErrors({
                        generic: {
                            code: error.code,
                            detail: error.detail,
                        },
                    })
                    throw e
                }
            },
        },
    })),
    selectors({
        validatedPassword: [
            (s) => [s.signup],
            ({ password }): ValidatedPasswordResult => {
                return validatePassword(password)
            },
        ],
    }),
    listeners(({ actions, values }) => ({
        // kea-forms passes its own `errors` payload here, but reads it off a selector that does not
        // exist, so it always arrives undefined. Take the errors from the logic instead.
        submitSignupFailure: () => {
            const errors = values.signupAllErrors
            const firstInvalidField = FIELDS_IN_RENDER_ORDER.find((field) => errors[field])
            if (!firstInvalidField) {
                return
            }
            const input = document.getElementById(fieldInputId(firstInvalidField))
            // preventScroll so the smooth scroll below is the only movement the person sees
            input?.focus({ preventScroll: true })
            input?.scrollIntoView({ behavior: 'smooth', block: 'center' })
        },
        setTurnstileToken: ({ token }) => {
            if (token && values.challengeNonce) {
                actions.submitSignup()
            }
        },
        prevalidateInviteSuccess: ({ invite }) => {
            if (invite?.first_name) {
                actions.setSignupValue('first_name', invite.first_name)
            }
        },
        setPasskeyRegistered: ({ registered }) => {
            if (registered) {
                actions.setSignupValue('password', '')
            }
        },
        registerPasskey: async () => {
            const email = values.invite?.target_email
            if (!email) {
                actions.setPasskeyError('Email is required')
                return
            }

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

            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<RegistrationBeginResponse>(
                    'api/webauthn/signup-register/begin/',
                    { email }
                )

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

                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,
                    },
                })

                // 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.setSignupValue('password', '')
            } catch (e: any) {
                actions.setPasskeyError(getPasskeyErrorMessage(e, 'Failed to register passkey. Please try again.'))
            } finally {
                actions.setPasskeyRegistering(false)
            }
        },
    })),
    urlToAction(({ actions }) => ({
        '/signup/*': ({ _: id }, { error_code, error_detail }) => {
            if (error_code) {
                if ((Object.values(ErrorCodes) as string[]).includes(error_code)) {
                    actions.setError({ code: error_code as ErrorCodes, detail: error_detail })
                } else {
                    actions.setError({ code: ErrorCodes.Unknown, detail: error_detail })
                }
            } else if (id) {
                actions.prevalidateInvite(id)
            }
        },
    })),
])