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.

7.0 KB
Raw Blame
import { MakeLogicType, afterMount, connect, kea, listeners, path, selectors, useValues } from 'kea'
import { loaders } from 'kea-loaders'

import { FeatureFlagKey } from 'lib/constants'
import { permanentlyMount } from 'lib/utils/kea-logic-builders'

import type { ToolbarEntitlementsApiEntitlements } from '~/generated/core/api.schemas'
import { toolbarConfigLogic } from '~/toolbar/shared/toolbarConfigLogic'
import { captureToolbarApiRequest } from '~/toolbar/shared/toolbarFetch'
import { toolbarLogger } from '~/toolbar/shared/toolbarLogger'
import { toolbarPosthogJS, useToolbarFeatureFlag } from '~/toolbar/shared/toolbarPosthogJS'
import { safeFetch } from '~/toolbar/shared/utils'
import { AvailableFeature } from '~/types'

export type ToolbarEntitlements = ToolbarEntitlementsApiEntitlements

const ENTITLEMENTS_PATH = '/api/user/toolbar_entitlements'
// Matches the toolbar's other blocking check, the uiHost reachability HEAD request.
const ENTITLEMENTS_TIMEOUT_MS = 5000

/** Sends the PostHog session cookie. The extension panel makes the same request to check toolbar access. */
export function fetchToolbarEntitlements(uiHost: string): Promise<Response> {
    return safeFetch(`${uiHost}${ENTITLEMENTS_PATH}`, {
        credentials: 'include',
        // A stall would hold the gate closed for the whole page session,
        // because the retry lives in the failed branch, not the pending one.
        signal: AbortSignal.timeout(ENTITLEMENTS_TIMEOUT_MS),
    })
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface toolbarEntitlementsLogicValues {
    isAuthenticated: boolean // toolbarConfigLogic
    uiHost: string // toolbarConfigLogic
    entitlements: ToolbarEntitlements | null
    entitlementsLoading: boolean
    isEntitled: (feature: AvailableFeature) => boolean
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface toolbarEntitlementsLogicActions {
    setOAuthTokens: (
        accessToken: string,
        refreshToken: string | null,
        clientId: string
    ) => {
        accessToken: string
        clientId: string
        refreshToken: string | null
    } // toolbarConfigLogic
    loadEntitlements: () => any
    loadEntitlementsFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    loadEntitlementsSuccess: (
        entitlements: ToolbarEntitlementsApiEntitlements | null,
        payload?: any
    ) => {
        entitlements: ToolbarEntitlementsApiEntitlements | null
        payload?: any
    }
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface toolbarEntitlementsLogicMeta {
    __keaTypeGenInternalSelectorTypes: {
        isEntitled: (
            entitlements: ToolbarEntitlementsApiEntitlements | null,
            entitlementsLoading: boolean
        ) => (feature: AvailableFeature) => boolean
    }
}

export type toolbarEntitlementsLogicType = MakeLogicType<
    toolbarEntitlementsLogicValues,
    toolbarEntitlementsLogicActions,
    Record<string, any>,
    toolbarEntitlementsLogicMeta
>

export const toolbarEntitlementsLogic = kea<toolbarEntitlementsLogicType>([
    path(['toolbar', 'toolbarEntitlementsLogic']),
    connect(() => ({
        values: [toolbarConfigLogic, ['uiHost', 'isAuthenticated']],
        actions: [toolbarConfigLogic, ['setOAuthTokens']],
    })),
    loaders(({ values }) => ({
        entitlements: [
            null as ToolbarEntitlements | null,
            {
                loadEntitlements: async () => {
                    const startTime = performance.now()
                    // 0 keeps a network failure distinguishable from an HTTP status in telemetry.
                    let status = 0
                    try {
                        const response = await fetchToolbarEntitlements(values.uiHost)
                        status = response.status
                        if (!response.ok) {
                            toolbarLogger.warn('entitlements', 'Entitlements request failed', { status })
                            return null
                        }
                        const data = await response.json()
                        return (data.entitlements as ToolbarEntitlements) ?? null
                    } catch (error) {
                        toolbarLogger.warn('entitlements', 'Entitlements request failed', {
                            status,
                            error: error instanceof Error ? error.message : String(error),
                        })
                        return null
                    } finally {
                        captureToolbarApiRequest({
                            url: ENTITLEMENTS_PATH,
                            method: 'GET',
                            status,
                            durationMs: Math.round(performance.now() - startTime),
                        })
                    }
                },
            },
        ],
    })),
    selectors({
        isEntitled: [
            (s) => [s.entitlements, s.entitlementsLoading],
            (entitlements: ToolbarEntitlements | null, entitlementsLoading: boolean) =>
                (feature: AvailableFeature): boolean =>
                    !entitlementsLoading && entitlements?.[feature] === true,
        ],
    }),
    listeners(({ actions }) => ({
        setOAuthTokens: () => {
            actions.loadEntitlements()
        },
    })),
    afterMount(({ actions, values }) => {
        if (values.isAuthenticated) {
            actions.loadEntitlements()
        }
    }),
    permanentlyMount(),
])

/** `checking` and `unknown` block the feature like `locked` does, but the plan is not the reason. */
export type ToolbarFeatureGateStatus = 'available' | 'checking' | 'unknown' | 'locked'

export function toolbarFeatureGateStatus(
    feature: AvailableFeature,
    rolloutEnabled: boolean,
    entitlements: ToolbarEntitlements | null,
    entitlementsLoading: boolean
): ToolbarFeatureGateStatus {
    if (!rolloutEnabled) {
        return 'available'
    }
    if (entitlementsLoading) {
        return 'checking'
    }
    const entitled = entitlements?.[feature]
    if (entitled === true) {
        return 'available'
    }
    return entitled === false ? 'locked' : 'unknown'
}

export function useToolbarFeatureGateStatus(
    feature: AvailableFeature,
    rolloutFlag: FeatureFlagKey
): ToolbarFeatureGateStatus {
    const rolloutEnabled = useToolbarFeatureFlag(rolloutFlag)
    const { entitlements, entitlementsLoading } = useValues(toolbarEntitlementsLogic)
    return toolbarFeatureGateStatus(feature, rolloutEnabled, entitlements, entitlementsLoading)
}

export function isToolbarFeatureGated(feature: AvailableFeature, rolloutFlag: FeatureFlagKey): boolean {
    const rolloutEnabled = !!toolbarPosthogJS.getFeatureFlag(rolloutFlag)
    const values = toolbarEntitlementsLogic.findMounted()?.values
    return (
        toolbarFeatureGateStatus(
            feature,
            rolloutEnabled,
            values?.entitlements ?? null,
            values?.entitlementsLoading ?? false
        ) !== 'available'
    )
}