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.

44.5 KB
Raw Blame
import { decode } from 'he'
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 { loaders } from 'kea-loaders'
import { router, urlToAction } from 'kea-router'

import api from 'lib/api'
import { timeSensitiveAuthenticationLogic } from 'lib/components/TimeSensitiveAuthentication/timeSensitiveAuthenticationLogic'
import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'
import {
    IDENTITY_SCOPES,
    SCOPE_GROUPING_MIN_ROWS,
    buildOAuthScopeRows,
    grantedResourceScopes,
    identityScopeDescriptions,
    requiredLevelsFromScopes,
    type OAuthScopeGroup,
    type OAuthScopeRow,
    type RequiredLevel,
    type ScopeAccessSelections,
} from 'lib/oauthScopeRows'
import { OAUTH_SCOPES_SUPPORTED } from 'lib/oauthScopes.generated'
import { DEFAULT_OAUTH_SCOPES, getMinimumEquivalentScopes, groupScopeRows, type ScopeAccessLevel } from 'lib/scopes'
import { getAppContext } from 'lib/utils/getAppContext'
import { userLogic } from 'scenes/userLogic'

import type { OAuthApplicationPublicMetadata, OrganizationBasicType, TeamBasicType, UserType } from '~/types'

import { create as createOrganization } from 'products/platform_features/frontend/generated/api'

export type OAuthAuthorizationFormValues = {
    scoped_organizations: string[]
    scoped_teams: number[]
    access_type: 'all' | 'organizations' | 'teams'
}

// `*` grants read+write to everything; its read-only form is every grantable object's read
// scope. The server-computed list is authoritative, because it applies the app's ceiling.
// The fallback only covers a missing app context, and takes the read scopes OAuth advertises
// so it never names a scope the server would reject with invalid_scope.
const wildcardReadScopes = (oauthApplication: OAuthApplicationPublicMetadata | null): string[] =>
    oauthApplication?.wildcard_read_scopes?.length
        ? oauthApplication.wildcard_read_scopes
        : OAUTH_SCOPES_SUPPORTED.filter((scope) => scope.endsWith(':read'))

const isNativeProtocol = (url: string): boolean => {
    try {
        const parsed = new URL(url)
        return !['http:', 'https:'].includes(parsed.protocol)
    } catch {
        return false
    }
}

type OAuthAuthorizeResult = { redirectTo: string; isNative: boolean }

// `/oauth/authorize/` fails in two shapes, and `ApiError` reads neither usefully: the RFC 6749
// §4.1.2.1 envelope `{ error, error_description }`, where it surfaces the machine code rather
// than the prose, and DRF serializer errors `{ "<field>": ["<message>"] }`, where it finds no
// key at all and falls back to the transport text ("Non-OK response [POST ...] (status 400: )").
export const describeOAuthError = (data: unknown): string | null => {
    if (!data || typeof data !== 'object' || Array.isArray(data)) {
        return null
    }
    const body = data as Record<string, unknown>

    if (typeof body.error_description === 'string' && body.error_description) {
        return body.error_description
    }

    const sentences: string[] = []
    for (const [field, value] of Object.entries(body)) {
        // DRF always reports field errors as a list, which is what tells them apart from the
        // envelope above — `{ error: 'access_denied' }` is not a parameter named "error".
        if (!Array.isArray(value)) {
            continue
        }
        const messages = value.filter((message): message is string => typeof message === 'string' && !!message)
        if (!messages.length) {
            continue
        }
        const text = messages.join(' ')
        sentences.push(field === 'non_field_errors' ? text : `The parameter "${field}" is not correct: ${text}`)
    }
    if (!sentences.length) {
        return null
    }
    return ['The application sent an incorrect authorization request.', ...sentences].join(' ')
}

const oauthAuthorize = async (
    values: OAuthAuthorizationFormValues & { allow: boolean; scopes: string[] }
): Promise<OAuthAuthorizeResult | null> => {
    // Not kea-router's `searchParams`: it JSON-parses object-like values and coerces numbers
    // and booleans, and its own `location.search` is re-encoded from those. RFC 6749 A.5 allows
    // any printable ASCII in `state`, so a raw-JSON state must reach the API byte-for-byte.
    const params = new URLSearchParams(window.location.search)
    try {
        // nosemgrep: prefer-codegen-api -- Legacy raw API call to a route outside /api/, with an unchecked response type. No generated function can cover it until the route is in the OpenAPI schema.
        const response = await api.create('/oauth/authorize/', {
            client_id: params.get('client_id'),
            redirect_uri: params.get('redirect_uri'),
            response_type: params.get('response_type'),
            state: params.get('state'),
            scope: values.scopes.join(' '),
            code_challenge: params.get('code_challenge'),
            code_challenge_method: params.get('code_challenge_method'),
            nonce: params.get('nonce'),
            claims: params.get('claims'),
            scoped_organizations: values.access_type === 'organizations' ? values.scoped_organizations : [],
            scoped_teams: values.access_type === 'teams' ? values.scoped_teams : [],
            access_level:
                values.access_type === 'all' ? 'all' : values.access_type === 'organizations' ? 'organization' : 'team',
            allow: values.allow,
        })

        if (response.redirect_to) {
            return {
                redirectTo: response.redirect_to,
                isNative: isNativeProtocol(response.redirect_to),
            }
        }
        return null
    } catch (error: any) {
        const detail =
            error?.detail ||
            describeOAuthError(error?.data) ||
            error?.message ||
            'PostHog could not authorize the application.'
        lemonToast.error(detail)
        throw error
    }
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface oauthAuthorizeLogicValues {
    user: UserType | null // userLogic
    accessControlsApply: boolean
    adjustableScopeRows: OAuthScopeRow[]
    allOrganizations: OrganizationBasicType[]
    allScopesRequired: boolean
    allTeams: TeamBasicType[] | null
    allTeamsLoading: boolean
    alreadyGrantedScopeLevels: Map<string, RequiredLevel>
    alreadyGrantedScopes: string[]
    appName: string
    authorizationComplete: boolean
    consentResourceScopes: string[]
    effectiveScopes: string[]
    filteredTeams: TeamBasicType[] | null
    identityScopeDescriptions: string[]
    isCanceling: boolean
    isMcpResource: boolean
    isOauthAuthorizationSubmitting: boolean
    isOauthAuthorizationValid: boolean
    isRedirecting: boolean
    newOrganizationLoading: boolean
    newProjectLoading: boolean
    oauthApplication: OAuthApplicationPublicMetadata | null
    oauthApplicationLoading: boolean
    oauthAuthorization: OAuthAuthorizationFormValues
    oauthAuthorizationAllErrors: Record<string, any>
    oauthAuthorizationChanged: boolean
    oauthAuthorizationErrors: DeepPartialMap<OAuthAuthorizationFormValues, ValidationErrorType>
    oauthAuthorizationHasErrors: boolean
    oauthAuthorizationManualErrors: Record<string, any>
    oauthAuthorizationTouched: boolean
    oauthAuthorizationTouches: Record<string, boolean>
    oauthAuthorizationValidationErrors: DeepPartialMap<OAuthAuthorizationFormValues, ValidationErrorType>
    redirectDomain: string
    redirectUrl: string
    requiredAccessLevel: 'organization' | 'team' | null
    requiredScopeLevels: Map<string, RequiredLevel>
    requiredScopeRows: OAuthScopeRow[]
    scopeAccessSelections: ScopeAccessSelections
    scopeGroups: OAuthScopeGroup[]
    scopeRows: OAuthScopeRow[]
    scopeRowsGrouped: boolean
    scopes: string[]
    scopesWereDefaulted: boolean
    selectedOrganization: string | null
    showCreateProject: boolean
    showOauthAuthorizationErrors: boolean
    showReadOnlyBulkAction: boolean
    sortedTeams: TeamBasicType[] | null
    teamHint: number | null
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface oauthAuthorizeLogicActions {
    cancel: () => {}
    createNewOrganization: (name: string) => {
        name: string
    }
    createNewProject: (name: string) => {
        name: string
    }
    loadAllTeams: () => any
    loadAllTeamsFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    loadAllTeamsSuccess: (
        allTeams: TeamBasicType[],
        payload?: any
    ) => {
        allTeams: TeamBasicType[]
        payload?: any
    }
    loadOAuthApplication: () => any
    loadOAuthApplicationFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    loadOAuthApplicationSuccess: (
        oauthApplication: OAuthApplicationPublicMetadata | null,
        payload?: any
    ) => {
        oauthApplication: OAuthApplicationPublicMetadata | null
        payload?: any
    }
    resetOauthAuthorization: (values?: OAuthAuthorizationFormValues) => {
        values?: OAuthAuthorizationFormValues
    }
    setAllScopeAccess: (level: ScopeAccessLevel) => {
        level: ScopeAccessLevel
    }
    setAlreadyGrantedScopes: (alreadyGrantedScopes: string[]) => {
        alreadyGrantedScopes: string[]
    }
    setAuthorizationComplete: (complete: boolean) => {
        complete: boolean
    }
    setCanceling: (canceling: boolean) => {
        canceling: boolean
    }
    setIsMcpResource: (isMcpResource: boolean) => {
        isMcpResource: boolean
    }
    setNewOrganizationLoading: (loading: boolean) => {
        loading: boolean
    }
    setNewProjectLoading: (loading: boolean) => {
        loading: boolean
    }
    setOauthAuthorizationManualErrors: (errors: Record<string, any>) => {
        errors: Record<string, any>
    }
    setOauthAuthorizationValue: (
        key: FieldName,
        value: any
    ) => {
        name: FieldName
        value: any
    }
    setOauthAuthorizationValues: (values: DeepPartial<OAuthAuthorizationFormValues>) => {
        values: DeepPartial<OAuthAuthorizationFormValues>
    }
    setRedirecting: (redirectUrl: string) => {
        redirectUrl: string
    }
    setRequiredAccessLevel: (requiredAccessLevel: 'organization' | 'team' | null) => {
        requiredAccessLevel: 'organization' | 'team' | null
    }
    setScopeAccess: (
        scopeObject: string,
        level: ScopeAccessLevel
    ) => {
        level: ScopeAccessLevel
        scopeObject: string
    }
    setScopeGroupAccess: (
        scopeObjects: string[],
        level: ScopeAccessLevel
    ) => {
        level: ScopeAccessLevel
        scopeObjects: string[]
    }
    setScopes: (scopes: string[]) => {
        scopes: string[]
    }
    setScopesWereDefaulted: (scopesWereDefaulted: boolean) => {
        scopesWereDefaulted: boolean
    }
    setSelectedOrganization: (
        organizationId: string,
        preferredTeamId?: number
    ) => {
        organizationId: string
        preferredTeamId: number | undefined
    }
    setShowCreateProject: (show: boolean) => {
        show: boolean
    }
    setTeamHint: (teamId: number | null) => {
        teamId: number | null
    }
    submitOauthAuthorization: () => {
        value: boolean
    }
    submitOauthAuthorizationFailure: (
        error: Error,
        errors: Record<string, any>
    ) => {
        error: Error
        errors: Record<string, any>
    }
    submitOauthAuthorizationRequest: (oauthAuthorization: OAuthAuthorizationFormValues) => {
        oauthAuthorization: OAuthAuthorizationFormValues
    }
    submitOauthAuthorizationSuccess: (oauthAuthorization: OAuthAuthorizationFormValues) => {
        oauthAuthorization: OAuthAuthorizationFormValues
    }
    touchOauthAuthorizationField: (key: string) => {
        key: string
    }
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface oauthAuthorizeLogicMeta {
    __keaTypeGenInternalSelectorTypes: {
        appName: (oauthApplication: OAuthApplicationPublicMetadata | null) => string
        allOrganizations: (user: UserType | null) => OrganizationBasicType[]
        sortedTeams: (
            allTeams: TeamBasicType[] | null,
            allOrganizations: OrganizationBasicType[],
            user: UserType | null
        ) => TeamBasicType[] | null
        filteredTeams: (
            sortedTeams: TeamBasicType[] | null,
            selectedOrganization: string | null
        ) => TeamBasicType[] | null
        identityScopeDescriptions: (scopes: string[]) => string[]
        requiredScopeLevels: (oauthApplication: OAuthApplicationPublicMetadata | null) => Map<string, RequiredLevel>
        alreadyGrantedScopeLevels: (alreadyGrantedScopes: string[]) => Map<string, RequiredLevel>
        consentResourceScopes: (
            scopes: string[],
            oauthApplication: OAuthApplicationPublicMetadata | null,
            alreadyGrantedScopes: string[]
        ) => string[]
        scopeRows: (
            consentResourceScopes: string[],
            scopeAccessSelections: ScopeAccessSelections,
            requiredScopeLevels: Map<string, RequiredLevel>,
            alreadyGrantedScopeLevels: Map<string, RequiredLevel>,
            appName: string
        ) => OAuthScopeRow[]
        requiredScopeRows: (scopeRows: OAuthScopeRow[]) => OAuthScopeRow[]
        adjustableScopeRows: (scopeRows: OAuthScopeRow[]) => OAuthScopeRow[]
        scopeRowsGrouped: (adjustableScopeRows: OAuthScopeRow[]) => boolean
        scopeGroups: (adjustableScopeRows: OAuthScopeRow[]) => OAuthScopeGroup[]
        allScopesRequired: (scopeRows: OAuthScopeRow[]) => boolean
        showReadOnlyBulkAction: (adjustableScopeRows: OAuthScopeRow[]) => boolean
        effectiveScopes: (
            scopes: string[],
            scopeRows: OAuthScopeRow[],
            oauthApplication: OAuthApplicationPublicMetadata | null,
            alreadyGrantedScopes: string[]
        ) => string[]
        redirectDomain: (oauthApplication: OAuthApplicationPublicMetadata | null) => string
    }
}

export type oauthAuthorizeLogicType = MakeLogicType<
    oauthAuthorizeLogicValues,
    oauthAuthorizeLogicActions,
    Record<string, any>,
    oauthAuthorizeLogicMeta
>

export const oauthAuthorizeLogic = kea<oauthAuthorizeLogicType>([
    path(['oauth', 'authorize']),
    connect(() => ({
        values: [userLogic, ['user']],
    })),
    actions({
        setScopes: (scopes: string[]) => ({ scopes }),
        setAlreadyGrantedScopes: (alreadyGrantedScopes: string[]) => ({ alreadyGrantedScopes }),
        setScopeAccess: (scopeObject: string, level: ScopeAccessLevel) => ({ scopeObject, level }),
        setScopeGroupAccess: (scopeObjects: string[], level: ScopeAccessLevel) => ({ scopeObjects, level }),
        setAllScopeAccess: (level: ScopeAccessLevel) => ({ level }),
        setRequiredAccessLevel: (requiredAccessLevel: 'organization' | 'team' | null) => ({ requiredAccessLevel }),
        setTeamHint: (teamId: number | null) => ({ teamId }),
        setScopesWereDefaulted: (scopesWereDefaulted: boolean) => ({ scopesWereDefaulted }),
        setIsMcpResource: (isMcpResource: boolean) => ({ isMcpResource }),
        cancel: () => ({}),
        setCanceling: (canceling: boolean) => ({ canceling }),
        setAuthorizationComplete: (complete: boolean) => ({ complete }),
        setRedirecting: (redirectUrl: string) => ({ redirectUrl }),
        setSelectedOrganization: (organizationId: string, preferredTeamId?: number) => ({
            organizationId,
            preferredTeamId,
        }),
        setShowCreateProject: (show: boolean) => ({ show }),
        createNewProject: (name: string) => ({ name }),
        setNewProjectLoading: (loading: boolean) => ({ loading }),
        createNewOrganization: (name: string) => ({ name }),
        setNewOrganizationLoading: (loading: boolean) => ({ loading }),
    }),
    loaders({
        allTeams: [
            null as TeamBasicType[] | null,
            {
                loadAllTeams: async () => {
                    const user = userLogic.values.user
                    if (!user?.organizations?.length) {
                        // Without an organization there are no projects to list, and `api/projects`
                        // would 404 because it resolves the current organization.
                        return []
                    }
                    const results = await Promise.all(
                        user.organizations.map((org) =>
                            // nosemgrep: prefer-codegen-api -- Legacy raw API call with a hand-written URL and an unchecked response type. Use organizationsProjectsList() from '~/generated/core/api' instead.
                            api.loadPaginatedResults<TeamBasicType>(`api/organizations/${org.id}/projects`)
                        )
                    )
                    return results.flat()
                },
            },
        ],
        oauthApplication: [
            null as OAuthApplicationPublicMetadata | null,
            {
                loadOAuthApplication: async () => {
                    // The authorize view injects the application metadata into the page
                    // context after resolving the client_id (including CIMD clients).
                    // No API call needed.
                    const preloaded = getAppContext()?.oauth_application
                    return preloaded ?? null
                },
            },
        ],
    }),
    listeners(({ values, actions }) => ({
        cancel: async () => {
            actions.setCanceling(true)
            try {
                const result = await oauthAuthorize({
                    scoped_organizations: values.oauthAuthorization.scoped_organizations,
                    scoped_teams: values.oauthAuthorization.scoped_teams,
                    access_type: values.oauthAuthorization.access_type,
                    allow: false,
                    scopes: values.scopes,
                })
                if (result) {
                    location.href = result.redirectTo
                }
            } finally {
                actions.setCanceling(false)
            }
        },
        createNewOrganization: async ({ name }) => {
            actions.setNewOrganizationLoading(true)
            try {
                await timeSensitiveAuthenticationLogic.findMounted()?.asyncActions.checkReauthentication()
                const previousUser = userLogic.values.user
                // The backend creates a default project with the organization and makes both current.
                // nosemgrep: prefer-codegen-api -- False positive: this is the generated create() from products/platform_features/frontend/generated/api, which semgrep resolves to api.create because the module is named api.
                const organization = await createOrganization({ name })
                // The loaders below report their own failures and resolve anyway. A retry here would
                // create a second organization, so offer a reload, which keeps the authorize URL.
                const showReloadToast = (): void => {
                    lemonToast.error(
                        "Your organization was created, but it couldn't be loaded. Reload the page to continue.",
                        {
                            button: { label: 'Reload', action: () => window.location.reload() },
                        }
                    )
                }
                await userLogic.asyncActions.loadUser()
                if (!userLogic.values.user) {
                    // A failed loadUser sets the user to null, which hides this screen.
                    if (previousUser) {
                        userLogic.actions.loadUserSuccess(previousUser)
                    }
                    showReloadToast()
                    return
                }
                await oauthAuthorizeLogic.asyncActions.loadAllTeams()
                if (!values.allTeams?.some((team) => team.organization === organization.id)) {
                    showReloadToast()
                    return
                }
                if (values.requiredAccessLevel === 'team') {
                    actions.setSelectedOrganization(organization.id, userLogic.values.user?.team?.id)
                }
            } catch (e: any) {
                lemonToast.error(e.detail || "Couldn't create the organization. Try again.")
            } finally {
                actions.setNewOrganizationLoading(false)
            }
        },
        createNewProject: async ({ name }) => {
            actions.setNewProjectLoading(true)
            try {
                const orgId = values.selectedOrganization
                const endpoint = orgId ? `api/organizations/${orgId}/projects/` : 'api/projects/'
                // nosemgrep: prefer-codegen-api -- Legacy raw API call with a URL built at runtime and an unchecked response type. Use a generated function if one covers this endpoint.
                await api.create(endpoint, { name })
                lemonToast.success(`Project "${name}" created`)
                actions.setShowCreateProject(false)
                // Remember existing team IDs so we can find the new one after reload
                const existingIds = new Set((values.allTeams ?? []).map((t) => t.id))
                await oauthAuthorizeLogic.asyncActions.loadAllTeams()
                // Find the newly created team and auto-select it
                const newTeam = (values.allTeams ?? []).find(
                    (t) => !existingIds.has(t.id) && t.organization === values.selectedOrganization
                )
                if (newTeam) {
                    actions.setOauthAuthorizationValue('scoped_teams', [newTeam.id])
                }
            } catch (e: any) {
                lemonToast.error(e.detail || 'Failed to create project')
            } finally {
                actions.setNewProjectLoading(false)
            }
        },
    })),
    reducers({
        scopes: [
            [] as string[],
            {
                setScopes: (_, { scopes }) => scopes,
            },
        ],
        alreadyGrantedScopes: [
            [] as string[],
            {
                setAlreadyGrantedScopes: (_, { alreadyGrantedScopes }) => alreadyGrantedScopes,
            },
        ],
        // The user's picks. `bulk` is the last bulk action (Select all / Read-only / Deselect
        // all); `overrides` are per-object picks made after it. Absent entries default to the
        // requested ceiling, and every pick is clamped to [required floor, requested ceiling]
        // in scopeRows, so bulk actions can apply one level blindly to heterogeneous rows.
        scopeAccessSelections: [
            { bulk: null, overrides: {} } as ScopeAccessSelections,
            {
                setScopeAccess: (state, { scopeObject, level }) => ({
                    ...state,
                    overrides: { ...state.overrides, [scopeObject]: level },
                }),
                setScopeGroupAccess: (state, { scopeObjects, level }) => ({
                    ...state,
                    overrides: {
                        ...state.overrides,
                        ...Object.fromEntries(scopeObjects.map((scopeObject) => [scopeObject, level])),
                    },
                }),
                setAllScopeAccess: (_, { level }) => ({ bulk: level, overrides: {} }),
                setScopes: () => ({ bulk: null, overrides: {} }),
            },
        ],
        requiredAccessLevel: [
            null as 'organization' | 'team' | null,
            {
                setRequiredAccessLevel: (_, { requiredAccessLevel }) => requiredAccessLevel,
            },
        ],
        scopesWereDefaulted: [
            false,
            {
                setScopesWereDefaulted: (_, { scopesWereDefaulted }) => scopesWereDefaulted,
            },
        ],
        isMcpResource: [
            false,
            {
                setIsMcpResource: (_, { isMcpResource }) => isMcpResource,
            },
        ],
        isCanceling: [
            false,
            {
                setCanceling: (_, { canceling }) => canceling,
            },
        ],
        authorizationComplete: [
            false,
            {
                setAuthorizationComplete: (_, { complete }) => complete,
            },
        ],
        isRedirecting: [
            false,
            {
                setRedirecting: () => true,
            },
        ],
        redirectUrl: [
            '',
            {
                setRedirecting: (_, { redirectUrl }) => redirectUrl,
            },
        ],
        selectedOrganization: [
            null as string | null,
            {
                setSelectedOrganization: (_, { organizationId }) => organizationId,
            },
        ],
        teamHint: [
            null as number | null,
            {
                setTeamHint: (_, { teamId }) => teamId,
            },
        ],
        showCreateProject: [
            false,
            {
                setShowCreateProject: (_, { show }) => show,
            },
        ],
        newProjectLoading: [
            false,
            {
                setNewProjectLoading: (_, { loading }) => loading,
            },
        ],
        newOrganizationLoading: [
            false,
            {
                setNewOrganizationLoading: (_, { loading }) => loading,
            },
        ],
    }),
    listeners(({ actions, values }) => ({
        setRequiredAccessLevel: ({ requiredAccessLevel }) => {
            if (requiredAccessLevel === 'organization') {
                actions.setOauthAuthorizationValue('access_type', 'organizations')
                const currentOrganizationId = userLogic.values.user?.organization?.id
                if (currentOrganizationId) {
                    actions.setOauthAuthorizationValue('scoped_organizations', [currentOrganizationId])
                }
            } else if (requiredAccessLevel === 'team') {
                actions.setOauthAuthorizationValue('access_type', 'teams')
                // With a team_id hint pending, let it drive org+project selection once
                // teams load — don't pre-select the user's current org/team, or a CTA
                // link could authorize the wrong project before the hint resolves. The
                // empty project keeps the submit blocked until the hint fills it in.
                if (!values.teamHint) {
                    const user = userLogic.values.user
                    if (user?.organization?.id) {
                        actions.setSelectedOrganization(user.organization.id, user?.team?.id)
                    }
                }
            }
        },
        setSelectedOrganization: ({ preferredTeamId }) => {
            // Auto-select the preferred team or the first team in the org
            const teams = values.sortedTeams
            const orgId = values.selectedOrganization
            if (teams && orgId) {
                const orgTeams = teams.filter((t) => t.organization === orgId)
                const match = preferredTeamId ? orgTeams.find((t) => t.id === preferredTeamId) : orgTeams[0]
                actions.setOauthAuthorizationValue('scoped_teams', match ? [match.id] : [])
            } else {
                // Teams not loaded yet — loadAllTeamsSuccess will handle it
                actions.setOauthAuthorizationValue('scoped_teams', preferredTeamId ? [preferredTeamId] : [])
            }
        },
        loadAllTeamsSuccess: () => {
            const teams = values.sortedTeams
            if (!teams) {
                return
            }
            // A team_id hint from the authorize URL (e.g. the wizard's --project-id) wins:
            // pre-select that project and its org so the user just clicks Authorize. We only
            // honor it if the user has access to that team (it's in their loaded teams), and
            // consume it once — so it can't override a later manual change or a project the
            // user creates here (both also re-fire this listener).
            if (values.teamHint) {
                const hinted = teams.find((t) => t.id === values.teamHint)
                actions.setTeamHint(null)
                if (hinted && values.requiredAccessLevel === 'team') {
                    actions.setSelectedOrganization(hinted.organization, hinted.id)
                    return
                }
                // Hint didn't resolve (inaccessible team, or not a team-level grant). Fall
                // back to the user's current org/team — setRequiredAccessLevel skipped this
                // while the hint was pending, so without it the screen would be left empty.
                if (values.requiredAccessLevel === 'team' && !values.selectedOrganization) {
                    const user = userLogic.values.user
                    if (user?.organization?.id) {
                        actions.setSelectedOrganization(user.organization.id, user?.team?.id)
                        return
                    }
                }
            }
            // After teams load, auto-select first project if org is set but no project selected
            const orgId = values.selectedOrganization
            const currentTeams = values.oauthAuthorization.scoped_teams
            if (orgId && (!currentTeams || currentTeams.length === 0)) {
                const orgTeams = teams.filter((t) => t.organization === orgId)
                if (orgTeams.length > 0) {
                    actions.setOauthAuthorizationValue('scoped_teams', [orgTeams[0].id])
                }
            }
        },
    })),
    forms(({ actions }) => ({
        oauthAuthorization: {
            defaults: {
                scoped_organizations: [],
                scoped_teams: [],
                access_type: 'all',
            } as OAuthAuthorizationFormValues,
            errors: ({ access_type, scoped_organizations, scoped_teams }: OAuthAuthorizationFormValues) => ({
                access_type: !access_type ? ('Select access mode' as any) : undefined,
                scoped_organizations:
                    access_type === 'organizations' && !scoped_organizations?.length
                        ? ('Select at least one organization' as any)
                        : undefined,
                scoped_teams:
                    access_type === 'teams' && !scoped_teams?.length
                        ? ('Select at least one project' as any)
                        : undefined,
            }),
            submit: async (values: OAuthAuthorizationFormValues) => {
                const scopes = oauthAuthorizeLogic.values.effectiveScopes
                const result = await oauthAuthorize({
                    ...values,
                    allow: true,
                    scopes,
                })
                if (!result) {
                    return
                }
                // Swap the form for a "Redirecting…" view so the user sees progress
                // while the browser navigates — for HTTP loopback redirects (Cursor,
                // Claude Code, etc.) the browser may sit waiting for the local
                // listener to respond, which makes the original screen feel hung.
                actions.setRedirecting(result.redirectTo)
                location.href = result.redirectTo
                if (result.isNative) {
                    // Native protocol handlers (vscode://, cursor://, etc.) don't
                    // navigate the browser away; show success after a brief delay.
                    setTimeout(() => actions.setAuthorizationComplete(true), 100)
                }
            },
        },
    })),
    selectors(() => ({
        // The server sets this flag once for the page, so no action changes it.
        accessControlsApply: [() => [], (): boolean => getAppContext()?.oauth_consent_access_controls_apply === true],
        appName: [
            (s) => [s.oauthApplication],
            // The name is HTML-escaped at ingestion (see posthog/api/oauth/client_name.py). Decode
            // it back to plain text so React's own output escaping renders it correctly instead of
            // showing literal entities like "&amp;".
            (oauthApplication: OAuthApplicationPublicMetadata | null): string =>
                oauthApplication ? decode(oauthApplication.name) : '',
        ],
        allOrganizations: [
            (s) => [s.user],
            (user: UserType): OrganizationBasicType[] => {
                return user?.organizations ?? []
            },
        ],
        sortedTeams: [
            (s) => [s.allTeams, s.allOrganizations, s.user],
            (
                teams: TeamBasicType[] | null,
                organizations: OrganizationBasicType[],
                user: UserType
            ): TeamBasicType[] | null => {
                if (!teams) {
                    return null
                }
                const currentTeamId = user?.team?.id
                const orgNameMap = new Map(organizations.map((org) => [org.id, org.name]))
                return [...teams].sort((a, b) => {
                    // Current team always comes first
                    if (a.id === currentTeamId) {
                        return -1
                    }
                    if (b.id === currentTeamId) {
                        return 1
                    }
                    const orgA = orgNameMap.get(a.organization) ?? ''
                    const orgB = orgNameMap.get(b.organization) ?? ''
                    if (orgA !== orgB) {
                        return orgA.localeCompare(orgB)
                    }
                    return a.name.localeCompare(b.name)
                })
            },
        ],
        filteredTeams: [
            (s) => [s.sortedTeams, s.selectedOrganization],
            (teams: TeamBasicType[] | null, selectedOrg: string | null): TeamBasicType[] | null => {
                if (!teams || !selectedOrg) {
                    return teams
                }
                return teams.filter((t) => t.organization === selectedOrg)
            },
        ],
        identityScopeDescriptions: [
            (s) => [s.scopes],
            (scopes: string[]): string[] => identityScopeDescriptions(scopes),
        ],
        requiredScopeLevels: [
            (s) => [s.oauthApplication],
            (oauthApplication: OAuthApplicationPublicMetadata | null): Map<string, RequiredLevel> =>
                requiredLevelsFromScopes(oauthApplication?.required_scopes ?? []),
        ],
        // A step-up keeps what the user granted this app before, so those scopes set a floor
        // like required scopes do, with their own label.
        alreadyGrantedScopeLevels: [
            (s) => [s.alreadyGrantedScopes],
            (alreadyGrantedScopes: string[]): Map<string, RequiredLevel> =>
                requiredLevelsFromScopes(alreadyGrantedScopes),
        ],
        // Requested plus required resource scopes, collapsed to the highest action per
        // object. Both the rows and the grant derive from this one set, so the consent
        // screen always displays exactly what authorizing will grant — required scopes
        // the client didn't request get a visible (locked) row, never a silent grant.
        // Scopes outside the app's ceiling are dropped first: `/authorize` clamps them
        // away, so rendering them would promise the user access the token won't carry.
        // `*` survives because the server resolves it separately (`wildcard_read_scopes`)
        // rather than matching it against the ceiling.
        consentResourceScopes: [
            (s) => [s.scopes, s.oauthApplication, s.alreadyGrantedScopes],
            (
                scopes: string[],
                oauthApplication: OAuthApplicationPublicMetadata | null,
                alreadyGrantedScopes: string[]
            ): string[] => {
                const grantable = oauthApplication?.grantable_scopes
                const grantableSet = grantable ? new Set(grantable) : null
                const requested = grantableSet
                    ? scopes.filter((scope) => scope === '*' || !scope.includes(':') || grantableSet.has(scope))
                    : scopes
                const required = [...(oauthApplication?.required_scopes ?? []), ...alreadyGrantedScopes].filter(
                    (scope) => scope.includes(':') || scope === '*'
                )
                return getMinimumEquivalentScopes([...requested, ...required]).filter(
                    (scope) => scope.includes(':') || scope === '*'
                )
            },
        ],
        // One row per scope object. The requested set caps the ceiling, the required set
        // sets the floor, and the user's selection is clamped between the two — so no pick
        // (including bulk actions) can grant more than requested or less than required.
        scopeRows: [
            (s) => [
                s.consentResourceScopes,
                s.scopeAccessSelections,
                s.requiredScopeLevels,
                s.alreadyGrantedScopeLevels,
                s.appName,
            ],
            (
                consentResourceScopes: string[],
                scopeAccessSelections: ScopeAccessSelections,
                requiredScopeLevels: Map<string, RequiredLevel>,
                alreadyGrantedScopeLevels: Map<string, RequiredLevel>,
                appName: string
            ): OAuthScopeRow[] => {
                return buildOAuthScopeRows(
                    consentResourceScopes,
                    scopeAccessSelections,
                    requiredScopeLevels,
                    alreadyGrantedScopeLevels,
                    appName
                )
            },
        ],
        // Locked rows (required at exactly the requested level) render as a plain checkmark
        // list — there is nothing to choose — while adjustable rows get an access selector.
        requiredScopeRows: [
            (s) => [s.scopeRows],
            (scopeRows: OAuthScopeRow[]): OAuthScopeRow[] => scopeRows.filter((row) => row.locked),
        ],
        adjustableScopeRows: [
            (s) => [s.scopeRows],
            (scopeRows: OAuthScopeRow[]): OAuthScopeRow[] => scopeRows.filter((row) => !row.locked),
        ],
        scopeRowsGrouped: [
            (s) => [s.adjustableScopeRows],
            (adjustableScopeRows: OAuthScopeRow[]): boolean => adjustableScopeRows.length > SCOPE_GROUPING_MIN_ROWS,
        ],
        scopeGroups: [
            (s) => [s.adjustableScopeRows],
            (adjustableScopeRows: OAuthScopeRow[]): OAuthScopeGroup[] => groupScopeRows(adjustableScopeRows),
        ],
        allScopesRequired: [
            (s) => [s.scopeRows],
            (scopeRows: OAuthScopeRow[]): boolean => scopeRows.length > 0 && scopeRows.every((row) => row.locked),
        ],
        // Only offer the bulk read-only action when it would change something — i.e. at least
        // one adjustable row can sit at write level.
        showReadOnlyBulkAction: [
            (s) => [s.adjustableScopeRows],
            (adjustableScopeRows: OAuthScopeRow[]): boolean =>
                adjustableScopeRows.some((row) => row.maxLevel === 'write'),
        ],
        effectiveScopes: [
            (s) => [s.scopes, s.scopeRows, s.oauthApplication, s.alreadyGrantedScopes],
            (
                scopes: string[],
                scopeRows: OAuthScopeRow[],
                oauthApplication: OAuthApplicationPublicMetadata | null,
                alreadyGrantedScopes: string[]
            ): string[] => {
                const identity = scopes.filter((scope) => IDENTITY_SCOPES.includes(scope))
                const resources = grantedResourceScopes(scopeRows, scopes, () => wildcardReadScopes(oauthApplication))
                // Also grant the required strings verbatim: collapsing read+write pairs above
                // could otherwise drop a literal entry the server's set-difference check expects.
                const required = [...(oauthApplication?.required_scopes ?? []), ...alreadyGrantedScopes].filter(
                    (scope) => scope.includes(':') || scope === '*'
                )
                return Array.from(new Set([...identity, ...resources, ...required]))
            },
        ],
        redirectDomain: [
            (s) => [s.oauthApplication],
            (): string => {
                // Stays on kea-router: a redirect_uri is always a URL, which `parseValue` leaves
                // alone, and only the request payload needs verbatim bytes. Reading
                // `window.location` here would break under Storybook's in-memory history.
                const redirectUri = router.values.searchParams['redirect_uri'] as string
                if (!redirectUri) {
                    return ''
                }
                try {
                    const url = new URL(redirectUri)
                    return url.hostname
                } catch {
                    return ''
                }
            },
        ],
    })),
    urlToAction(({ actions }) => {
        const handleAuthorize = (_: Record<string, any>, searchParams: Record<string, any>): void => {
            const requestedScopes = searchParams['scope']?.split(' ')?.filter((scope: string) => scope.length) ?? []
            const oauthMcpConsent = getAppContext()?.oauth_mcp_consent
            const scopeResolution = getAppContext()?.oauth_scope_resolution
            // The screen needs a set it can submit, because an empty one renders no
            // permissions and posts a blank scope the API rejects. An empty server
            // resolution therefore falls back to the identity-only DEFAULT_OAUTH_SCOPES,
            // which is safe: it grants no resource access, so the person consents to
            // nothing they did not see. The URL's own tokens are deliberately not reused,
            // since those are what the server resolved to nothing.
            const fallbackScopes = scopeResolution || !requestedScopes.length ? DEFAULT_OAUTH_SCOPES : requestedScopes

            const scopesWereDefaulted = scopeResolution?.was_defaulted ?? requestedScopes.length === 0

            const rawRequiredAccessLevel = searchParams['required_access_level'] as 'organization' | 'project' | null
            const requiredAccessLevel = rawRequiredAccessLevel === 'project' ? 'team' : rawRequiredAccessLevel

            // Optional project to pre-select on the consent screen (e.g. the wizard's
            // `--project-id`). Honored only when the user has access to it; otherwise ignored.
            const teamIdParam = Number(searchParams['team_id'])
            const teamHint = Number.isInteger(teamIdParam) && teamIdParam > 0 ? teamIdParam : null

            // A step-up keeps the projects the token already applies to, so the screen starts there.
            // The user can still pick others.
            const earlierAccess = scopeResolution?.earlier_access
            const earlierTeam = requiredAccessLevel === 'team' ? (earlierAccess?.scoped_teams[0] ?? null) : null

            actions.setScopesWereDefaulted(scopesWereDefaulted)
            actions.setAlreadyGrantedScopes(scopeResolution?.already_granted_scopes ?? [])
            actions.setTeamHint(teamHint ?? earlierTeam)
            actions.setRequiredAccessLevel(requiredAccessLevel || null)
            if (earlierAccess && !requiredAccessLevel) {
                actions.setOauthAuthorizationValues(
                    earlierAccess.scoped_teams.length
                        ? { access_type: 'teams', scoped_teams: earlierAccess.scoped_teams }
                        : earlierAccess.scoped_organizations.length
                          ? { access_type: 'organizations', scoped_organizations: earlierAccess.scoped_organizations }
                          : { access_type: 'all' }
                )
            } else if (earlierAccess?.scoped_organizations.length && requiredAccessLevel === 'organization') {
                actions.setOauthAuthorizationValue('scoped_organizations', [earlierAccess.scoped_organizations[0]])
            }
            actions.loadOAuthApplication()
            actions.loadAllTeams()

            if (scopesWereDefaulted && oauthMcpConsent?.is_mcp_resource) {
                // The MCP branch narrows the resolved set to the scopes MCP tools actually
                // require, so an app with a broad ceiling doesn't consent to more than the
                // resource server can use.
                actions.setIsMcpResource(true)
                actions.setScopes(oauthMcpConsent.scopes ?? DEFAULT_OAUTH_SCOPES)
            } else {
                actions.setIsMcpResource(false)
                // `??` keeps an empty array, so the length is what to test here.
                actions.setScopes(scopeResolution?.scopes.length ? scopeResolution.scopes : fallbackScopes)
            }
        }

        return {
            '/oauth/authorize': handleAuthorize,
        }
    }),
])