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.5 KB
Raw Blame
import { MakeLogicType, actions, connect, kea, listeners, path, reducers, selectors } from 'kea'
import { subscriptions } from 'kea-subscriptions'

import type { UserApi } from '~/generated/core/api.schemas'
import { toolbarPosthogJS } from '~/toolbar/shared/toolbarPosthogJS'

import { getStoredTokens, setStoredTokens } from '../../browser/extensionBrowser'
import { authenticateToolbar } from '../../browser/extensionOAuth'
import type { PageToolbarTokens } from '../../messaging/pageToolbarBridge'
import { extensionPanelLogic } from './extensionPanelLogic'
import type { ExtensionPanelState } from './extensionPanelState'

export type ToolbarAuthStatus = 'loading' | 'signed-out' | 'authenticating' | 'authenticated' | 'failed'

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface extensionAuthLogicValues {
    panelState: ExtensionPanelState // extensionPanelLogic
    tabUrl: string | null | undefined // extensionPanelLogic
    uiHost: string // extensionPanelLogic
    user: UserApi | null // extensionPanelLogic
    authStatus: ToolbarAuthStatus
    authenticating: boolean
    autoAuthenticationKey: string | null
    currentKey: string | null
    failed: boolean
    loadedKey: string | null
    tokens: PageToolbarTokens | null
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface extensionAuthLogicActions {
    authenticate: (interactive: boolean) => {
        interactive: boolean
    }
    authenticateFailure: () => {
        value: true
    }
    loadTokens: (key: string) => {
        key: string
    }
    setTokens: (
        key: string,
        tokens: PageToolbarTokens | null
    ) => {
        key: string
        tokens: PageToolbarTokens | null
    }
    tokensExpired: () => {
        value: true
    }
    updateTokens: (tokens: PageToolbarTokens) => {
        tokens: PageToolbarTokens
    }
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface extensionAuthLogicMeta {
    __keaTypeGenInternalSelectorTypes: {
        currentKey: (uiHost: string, user: UserApi | null) => string | null
        authStatus: (
            currentKey: string | null,
            loadedKey: string | null,
            tokens: PageToolbarTokens | null,
            authenticating: boolean,
            failed: boolean
        ) => ToolbarAuthStatus
        autoAuthenticationKey: (
            currentKey: string | null,
            authStatus: ToolbarAuthStatus,
            panelState: ExtensionPanelState
        ) => string | null
    }
}

export type extensionAuthLogicType = MakeLogicType<
    extensionAuthLogicValues,
    extensionAuthLogicActions,
    Record<string, any>,
    extensionAuthLogicMeta
>

/** The page tools use OAuth tokens, because a session cookie sent from an extension page fails Django's CSRF check. */
export const extensionAuthLogic = kea<extensionAuthLogicType>([
    path(['toolbar', 'extension', 'extensionAuthLogic']),
    connect(() => ({
        values: [extensionPanelLogic, ['uiHost', 'user', 'tabUrl', 'panelState']],
    })),
    actions({
        loadTokens: (key: string) => ({ key }),
        setTokens: (key: string, tokens: PageToolbarTokens | null) => ({ key, tokens }),
        updateTokens: (tokens: PageToolbarTokens) => ({ tokens }),
        tokensExpired: true,
        authenticate: (interactive: boolean) => ({ interactive }),
        authenticateFailure: true,
    }),
    reducers({
        loadedKey: [null as string | null, { setTokens: (_, { key }) => key }],
        tokens: [
            null as PageToolbarTokens | null,
            {
                loadTokens: () => null,
                setTokens: (_, { tokens }) => tokens,
                updateTokens: (_, { tokens }) => tokens,
                tokensExpired: () => null,
            },
        ],
        authenticating: [false, { authenticate: () => true, setTokens: () => false, authenticateFailure: () => false }],
        failed: [false, { authenticate: () => false, authenticateFailure: () => true, loadTokens: () => false }],
    }),
    selectors({
        currentKey: [
            (s) => [s.uiHost, s.user],
            (uiHost: string, user: UserApi | null): string | null => (user ? `${uiHost}|${user.team.id}` : null),
        ],
        authStatus: [
            (s) => [s.currentKey, s.loadedKey, s.tokens, s.authenticating, s.failed],
            (
                currentKey: string | null,
                loadedKey: string | null,
                tokens: PageToolbarTokens | null,
                authenticating: boolean,
                failed: boolean
            ): ToolbarAuthStatus => {
                if (authenticating) {
                    return 'authenticating'
                }
                if (!currentKey || currentKey !== loadedKey) {
                    return 'loading'
                }
                if (tokens) {
                    return 'authenticated'
                }
                return failed ? 'failed' : 'signed-out'
            },
        ],
        autoAuthenticationKey: [
            (s) => [s.currentKey, s.authStatus, s.panelState],
            (
                currentKey: string | null,
                authStatus: ToolbarAuthStatus,
                panelState: ExtensionPanelState
            ): string | null => (authStatus === 'signed-out' && panelState.kind === 'ready' ? currentKey : null),
        ],
    }),
    listeners(({ actions, values, cache }) => ({
        loadTokens: async ({ key }) => {
            const tokens = await getStoredTokens(key)
            if (values.currentKey === key) {
                actions.setTokens(key, tokens)
            }
        },
        updateTokens: ({ tokens }) => {
            if (values.currentKey) {
                void setStoredTokens(values.currentKey, tokens)
            }
        },
        tokensExpired: () => {
            if (values.currentKey) {
                void setStoredTokens(values.currentKey, null)
            }
        },
        authenticate: async ({ interactive }) => {
            const key = values.currentKey
            const pageUrl = values.tabUrl
            if (!key || !pageUrl) {
                actions.authenticateFailure()
                return
            }
            cache.autoAuthenticatedKeys = (cache.autoAuthenticatedKeys ?? new Set<string>()).add(key)
            try {
                const tokens = await authenticateToolbar({ uiHost: values.uiHost, pageUrl, interactive })
                await setStoredTokens(key, tokens)
                // pinned: analytics event name
                toolbarPosthogJS.capture('toolbar extension authenticated', { status: 'success', interactive })
                actions.setTokens(key, tokens)
            } catch (error) {
                toolbarPosthogJS.capture('toolbar extension authenticated', {
                    status: 'error',
                    interactive,
                    error: String(error),
                })
                actions.authenticateFailure()
            }
        },
    })),
    subscriptions(({ actions, cache }) => ({
        currentKey: (currentKey: string | null) => {
            if (currentKey) {
                actions.loadTokens(currentKey)
            }
        },
        autoAuthenticationKey: (key: string | null) => {
            // Connects by itself once per project. After a failure, or when the tokens expire again, the user decides.
            const autoAuthenticatedKeys: Set<string> | undefined = cache.autoAuthenticatedKeys
            if (key && !autoAuthenticatedKeys?.has(key)) {
                actions.authenticate(false)
            }
        },
    })),
])