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.

15.1 KB
Raw Blame
import { MakeLogicType, actions, afterMount, kea, listeners, path, reducers } from 'kea'
import { router } from 'kea-router'
import posthog from 'posthog-js'

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

import api from 'lib/api'
import { ACCESS_BLOCKED_ERROR_CODE, PROJECT_ACCESS_DENIED_DETAIL } from 'lib/api-error'
import { timeSensitiveAuthenticationLogic } from 'lib/components/TimeSensitiveAuthentication/timeSensitiveAuthenticationLogic'
import { twoFactorLogic } from 'scenes/authentication/two-factor-setup/twoFactorLogic'
import { teamLogic } from 'scenes/teamLogic'
import { userLogic } from 'scenes/userLogic'

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface apiStatusLogicValues {
    internetConnectionIssue: boolean
    timeSensitiveAuthenticationRequired: boolean | [onSuccess: () => void, onFailure: () => void]
    twoFactorVerificationExpiredToastShown: boolean
    verifiedDomainBlockedToastShown: boolean
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface apiStatusLogicActions {
    onApiResponse: (
        response?: Response,
        error?: any,
        startedByUserAction?: boolean
    ) => {
        error: any
        response: Response | undefined
        startedByUserAction: boolean
    }
    resolveSensitiveAction: (outcome: 'failure' | 'success') => {
        outcome: 'failure' | 'success'
    }
    setInternetConnectionIssue: (issue: boolean) => {
        issue: boolean
    }
    setTimeSensitiveAuthenticationRequired: (required: boolean | [onSuccess: () => void, onFailure: () => void]) => {
        required: boolean | [onSuccess: () => void, onFailure: () => void]
    }
    setTwoFactorVerificationExpiredToastShown: (shown: boolean) => {
        shown: boolean
    }
    setVerifiedDomainBlockedToastShown: (shown: boolean) => {
        shown: boolean
    }
}

export type apiStatusLogicType = MakeLogicType<apiStatusLogicValues, apiStatusLogicActions>

// True from the start of a click, an Enter key press, or a form submit until the browser finishes
// that task, so it covers the handlers, the kea listeners they dispatch, and their microtasks.
// A request that starts in this span counts as one the user asked for. A request that starts
// after an `await`, such as a debounced save, does not.
let userActionInProgress = false
let userActionPathname: string | null = null

export function isUserActionInProgress(): boolean {
    // A click that navigates mounts a new scene, and the writes that scene sends are not what
    // the user clicked. The router stores the new location before any `locationChanged`
    // listener runs, so compare paths.
    return userActionInProgress && router.values.location.pathname === userActionPathname
}

const PROJECT_API_PATH = /^\/api\/(?:projects|environments)\/([^/]+)\//

function isCurrentProjectAccessDenial(url: string, responseData: any): boolean {
    if (responseData?.detail !== PROJECT_ACCESS_DENIED_DETAIL) {
        return false
    }
    const currentTeam = teamLogic.findMounted()?.values.currentTeam
    if (!currentTeam || !url) {
        return false
    }
    let pathname: string
    try {
        pathname = new URL(url, window.location.origin).pathname
    } catch {
        return false
    }
    const projectInPath = pathname.match(PROJECT_API_PATH)?.[1]
    return !!projectInPath && [String(currentTeam.id), String(currentTeam.project_id)].includes(projectInPath)
}

function markCurrentProjectAccessDenied(url: string, responseData: any): void {
    if (isCurrentProjectAccessDenial(url, responseData)) {
        teamLogic.findMounted()?.actions.currentProjectAccessDenied()
    }
}

type SensitiveActionCallbacks = [onSuccess: () => void, onFailure: () => void]

function callEach(callbacks: (() => void)[]): void {
    for (const callback of callbacks) {
        try {
            callback()
        } catch (e) {
            posthog.captureException(e)
        }
    }
}

function joinSensitiveActionCallbacks(
    pending: SensitiveActionCallbacks,
    next: boolean | SensitiveActionCallbacks
): SensitiveActionCallbacks {
    if (!Array.isArray(next)) {
        return pending
    }
    return [() => callEach([pending[0], next[0]]), () => callEach([pending[1], next[1]])]
}

export const apiStatusLogic = kea<apiStatusLogicType>([
    path(['lib', 'apiStatusLogic']),
    actions({
        onApiResponse: (response?: Response, error?: any, startedByUserAction?: boolean) => ({
            response,
            error,
            startedByUserAction: !!startedByUserAction,
        }),
        resolveSensitiveAction: (outcome: 'success' | 'failure') => ({ outcome }),
        setInternetConnectionIssue: (issue: boolean) => ({ issue }),
        setTimeSensitiveAuthenticationRequired: (
            required: boolean | [onSuccess: () => void, onFailure: () => void]
        ) => ({
            required,
        }),
        setTwoFactorVerificationExpiredToastShown: (shown: boolean) => ({ shown }),
        setVerifiedDomainBlockedToastShown: (shown: boolean) => ({ shown }),
    }),

    reducers({
        internetConnectionIssue: [
            false,
            {
                setInternetConnectionIssue: (_, { issue }) => issue,
            },
        ],

        timeSensitiveAuthenticationRequired: [
            // When a tuple of callbacks is passed, one of these will be called
            // when re-authentication succeeds or fails/is dismissed. Neither may throw
            // or reject: the pending checkReauthentication listener awaits them fire-and-forget.
            false as boolean | [onSuccess: () => void, onFailure: () => void],
            {
                // Several requests can wait on one re-authentication. A new waiter joins the pending
                // callbacks instead of replacing them, or the replaced waiter never settles.
                setTimeSensitiveAuthenticationRequired: (state, { required }) =>
                    Array.isArray(state) && required !== false
                        ? joinSensitiveActionCallbacks(state, required)
                        : required,
            },
        ],

        twoFactorVerificationExpiredToastShown: [
            false,
            {
                setTwoFactorVerificationExpiredToastShown: (_, { shown }) => shown,
            },
        ],

        verifiedDomainBlockedToastShown: [
            false,
            {
                setVerifiedDomainBlockedToastShown: (_, { shown }) => shown,
            },
        ],
    }),
    listeners(({ cache, actions, values }) => ({
        resolveSensitiveAction: ({ outcome }) => {
            const pending = values.timeSensitiveAuthenticationRequired
            if (outcome === 'success') {
                // Clear the gate first. A callback that throws is the caller's own bug, and it must
                // not leave the user behind the re-authentication modal with the action blocked.
                actions.setTimeSensitiveAuthenticationRequired(false)
            }
            if (!Array.isArray(pending)) {
                return
            }
            try {
                pending[outcome === 'success' ? 0 : 1]()
            } catch (e) {
                posthog.captureException(e)
            }
        },
        onApiResponse: async ({ response, error, startedByUserAction }, breakpoint) => {
            if (error || !response?.status) {
                await breakpoint(50)
                // Likely CORS headers errors (i.e. request failing without reaching Django))
                if (error?.message === 'Failed to fetch') {
                    actions.setInternetConnectionIssue(true)
                }
            }

            if (response?.ok && values.internetConnectionIssue) {
                actions.setInternetConnectionIssue(false)
            }

            try {
                if (response?.status === 403) {
                    const responseData = await response?.json()
                    markCurrentProjectAccessDenied(response.url, responseData)
                    if (
                        responseData.code === 'two_factor_setup_required' &&
                        !values.timeSensitiveAuthenticationRequired &&
                        !twoFactorLogic.findMounted()?.values.isTwoFactorSetupModalOpen
                    ) {
                        twoFactorLogic.findMounted()?.actions.openTwoFactorSetupModal(true)
                    } else if (
                        responseData.code === 'two_factor_verification_required' &&
                        !values.twoFactorVerificationExpiredToastShown
                    ) {
                        actions.setTwoFactorVerificationExpiredToastShown(true)
                        lemonToast.error(
                            'Your session requires re-authentication. You will be logged out to verify your identity again.',
                            {
                                button: {
                                    label: 'Understood',
                                    action: () => {
                                        userLogic.findMounted()?.actions.logout(true)
                                    },
                                },
                                autoClose: false,
                            }
                        )
                    } else if (
                        responseData.code === 'verified_domain_required' &&
                        !values.verifiedDomainBlockedToastShown
                    ) {
                        // The member isn't admitted to their current organization, and there's nothing
                        // they can do in-app about it, so send them back out to log in.
                        actions.setVerifiedDomainBlockedToastShown(true)
                        lemonToast.error(
                            typeof responseData.detail === 'string' && responseData.detail
                                ? responseData.detail
                                : 'Your organization only allows members with a verified email domain.',
                            {
                                button: {
                                    label: 'Log out',
                                    action: () => {
                                        userLogic.findMounted()?.actions.logout(true)
                                    },
                                },
                                autoClose: false,
                            }
                        )
                    } else if (responseData.code === 'impersonation_read_only' && startedByUserAction) {
                        lemonToast.error(
                            typeof responseData.detail === 'string' && responseData.detail
                                ? responseData.detail
                                : 'This action is not allowed during read-only user impersonation.',
                            { hideButton: true }
                        )
                    }
                }
            } catch {
                // Pass
            }

            if (response?.status === 401) {
                if (!userLogic.findMounted()?.values.user) {
                    // We should only check and logout if we have a user
                    return
                }

                // During impersonation, don't auto-logout on 401.
                // The ImpersonationNotice component handles session expiry
                // via its countdown timer and shows a re-impersonation overlay.
                if (userLogic.findMounted()?.values.user?.is_impersonated) {
                    return
                }

                // api.ts calls this if we see a 401
                const now = Date.now()

                // We don't want to check too often (multiple api calls might fail at once)
                if (now - 10000 > (cache.lastUnauthorizedCheck ?? 0)) {
                    cache.lastUnauthorizedCheck = Date.now()

                    // nosemgrep: prefer-codegen-api -- Legacy raw API call with a hand-written URL and an unchecked response type. Use usersRetrieve() from '~/generated/core/api' instead.
                    await api.get('api/users/@me/').catch((error: any) => {
                        if (error.status === 401) {
                            // An access rule refusal is not an expired session, so the person is told why.
                            const reason =
                                error.code === ACCESS_BLOCKED_ERROR_CODE ? ACCESS_BLOCKED_ERROR_CODE : undefined
                            userLogic.findMounted()?.actions.logout(true, undefined, reason)
                        }
                    })
                }
            }
        },
    })),
    afterMount(({ cache }) => {
        cache.disposables.add(() => {
            // `click` also fires for keyboard activation of buttons. Enter counts on its own because
            // some forms, such as LemonFormDialog, submit from a keydown handler. Other keys do not
            // submit. An Enter that confirms an IME composition still counts: the flag lasts only for
            // that Enter's own task, so it can only toast for a write that this Enter started.
            const onUserAction = (event: Event): void => {
                if (event.type === 'keydown' && (event as KeyboardEvent).key !== 'Enter') {
                    return
                }
                // Activating a link is navigation, not a write. A button inside a link is still a button.
                const control = (event.target as Element | null)?.closest?.('button, a[href]')
                if (control?.matches('a[href]')) {
                    return
                }
                // Re-adding the key runs the previous cleanup, so set the flag after it.
                cache.disposables.add(
                    () => {
                        const timeout = window.setTimeout(() => {
                            userActionInProgress = false
                        }, 0)
                        return () => {
                            window.clearTimeout(timeout)
                            userActionInProgress = false
                        }
                    },
                    'endUserAction',
                    { pauseOnPageHidden: false }
                )
                userActionInProgress = true
                userActionPathname = router.values.location.pathname
            }
            window.addEventListener('click', onUserAction, { capture: true })
            window.addEventListener('submit', onUserAction, { capture: true })
            window.addEventListener('keydown', onUserAction, { capture: true })
            return () => {
                window.removeEventListener('click', onUserAction, { capture: true })
                window.removeEventListener('submit', onUserAction, { capture: true })
                window.removeEventListener('keydown', onUserAction, { capture: true })
            }
        })
    }),
])

export function awaitReauthentication(): Promise<boolean> {
    const logic = apiStatusLogic.findMounted()
    if (!logic || !timeSensitiveAuthenticationLogic.findMounted()) {
        return Promise.resolve(false)
    }
    return new Promise((resolve) =>
        logic.actions.setTimeSensitiveAuthenticationRequired([() => resolve(true), () => resolve(false)])
    )
}