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.

18.6 KB
Raw Blame
import { MakeLogicType, actions, afterMount, connect, kea, listeners, path, reducers, selectors } from 'kea'
import { loaders } from 'kea-loaders'
import { urlToAction } from 'kea-router'

import { ApiError } from 'lib/api-error'
import {
    buildOAuthScopeRows,
    grantedResourceScopes,
    identityScopeDescriptions,
    requiredLevelsFromScopes,
    scopeGroupsToShow,
    type OAuthScopeGroup,
    type OAuthScopeRow,
    type RequiredLevel,
    type ScopeAccessSelections,
} from 'lib/oauthScopeRows'
import { type ScopeAccessLevel, countScopeRowsByLevel, getMinimumEquivalentScopes } from 'lib/scopes'
import { userLogic } from 'scenes/userLogic'

import {
    oauthDeviceApproveCreate,
    oauthDeviceDenyCreate,
    oauthDeviceLookupCreate,
    organizationsProjectsList,
} from '~/generated/core/api'
import type { DeviceDecisionEnumApi, DeviceGrantDetailsApi } from '~/generated/core/api.schemas'

import type { OrganizationBasicType, UserType } from '../../../types'

interface DeviceProject {
    id: number
    name: string
}

function deviceErrorMessage(error: unknown): string {
    if (error instanceof ApiError) {
        if (error.status === 429) {
            return 'Too many attempts. Wait a minute, then try again.'
        }
        if (typeof error.data?.error_description === 'string') {
            return error.data.error_description
        }
        if (error.detail) {
            return error.detail
        }
    }
    return "Couldn't reach PostHog. Check your connection and try again."
}

// The server's answer for a code that is wrong, expired or already used. Retrying it can't work.
function isInvalidCode(error: unknown): boolean {
    return error instanceof ApiError && error.data?.error === 'invalid_code'
}

// The project picker loads every page, so a project past the first page can still be picked.
const PROJECTS_PAGE_SIZE = 100

// The scopes the person already gave this client that work in the chosen project. A grant limited to
// another project or organization gives nothing here.
function grantedInProject(
    grant: DeviceGrantDetailsApi,
    projectId: number | null,
    organizationId: string | null
): string[] {
    return grant.granted_scopes
        .filter(
            (entry) =>
                (entry.project_id === null || entry.project_id === projectId) &&
                (entry.organization_id === null || entry.organization_id === organizationId)
        )
        .flatMap((entry) => entry.scopes)
}

// The scopes a step-up asks for beyond what the person already granted in the chosen project.
function addedScopes(grant: DeviceGrantDetailsApi, projectId: number | null, organizationId: string | null): string[] {
    const granted = new Set(grantedInProject(grant, projectId, organizationId))
    return grant.scopes.filter((scope) => !granted.has(scope))
}

const areas = (count: number): string => `${count} ${count === 1 ? 'area' : 'areas'}`

// One sentence for the collapsed permissions panel, counted from the levels the person picked.
function scopeSummary(rows: OAuthScopeRow[], appName: string): string {
    const { write, read } = countScopeRowsByLevel(rows)
    if (write && read) {
        return `${appName} can view and change data in ${areas(write)}, and view data in ${read} more.`
    }
    if (write) {
        return `${appName} can view and change data in ${areas(write)}.`
    }
    if (read) {
        return `${appName} can view data in ${areas(read)}.`
    }
    return `${appName} can only see your account details.`
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface oauthDeviceAuthorizeLogicValues {
    user: UserType | null // userLogic
    adjustableScopeRows: OAuthScopeRow[]
    allScopesRequired: boolean
    consentResourceScopes: string[]
    decision: DeviceDecisionEnumApi | null
    decisionLoading: boolean
    deviceGrant: DeviceGrantDetailsApi | null
    deviceGrantLoading: boolean
    error: string | null
    identityScopeDescriptions: string[]
    isStepUp: boolean
    keptScopes: string[]
    organizationId: string | null
    organizations: OrganizationBasicType[]
    projectId: number | null
    projects: DeviceProject[]
    projectsError: string | null
    projectsLoading: boolean
    requiredScopeLevels: Map<string, RequiredLevel>
    requiredScopeRows: OAuthScopeRow[]
    scopeAccessSelections: ScopeAccessSelections
    scopeGroups: OAuthScopeGroup[] | null
    scopeRows: OAuthScopeRow[]
    scopeSummary: string
    userCode: string
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface oauthDeviceAuthorizeLogicActions {
    approve: () => any
    approveFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    approveSuccess: (
        decision: DeviceDecisionEnumApi | null,
        payload?: any
    ) => {
        decision: DeviceDecisionEnumApi | null
        payload?: any
    }
    deny: () => any
    denyFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    denySuccess: (
        decision: DeviceDecisionEnumApi | null,
        payload?: any
    ) => {
        decision: DeviceDecisionEnumApi | null
        payload?: any
    }
    loadProjects: (organizationId: string) => string
    loadProjectsFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    loadProjectsSuccess: (
        projects: DeviceProject[],
        payload?: string
    ) => {
        projects: DeviceProject[]
        payload?: string
    }
    lookUpCode: () => any
    lookUpCodeFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    lookUpCodeSuccess: (
        deviceGrant: DeviceGrantDetailsApi,
        payload?: any
    ) => {
        deviceGrant: DeviceGrantDetailsApi
        payload?: any
    }
    setOrganizationId: (organizationId: string | null) => {
        organizationId: string | null
    }
    setProjectId: (projectId: number | null) => {
        projectId: number | null
    }
    setScopeAccess: (
        scopeObject: string,
        level: ScopeAccessLevel
    ) => {
        level: ScopeAccessLevel
        scopeObject: string
    }
    setScopeGroupAccess: (
        scopeObjects: string[],
        level: ScopeAccessLevel
    ) => {
        level: ScopeAccessLevel
        scopeObjects: string[]
    }
    setUserCode: (userCode: string) => {
        userCode: string
    }
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface oauthDeviceAuthorizeLogicMeta {
    __keaTypeGenInternalSelectorTypes: {
        organizations: (user: UserType | null) => OrganizationBasicType[]
        isStepUp: (
            deviceGrant: DeviceGrantDetailsApi | null,
            projectId: number | null,
            organizationId: string | null
        ) => boolean
        identityScopeDescriptions: (deviceGrant: DeviceGrantDetailsApi | null) => string[]
        consentResourceScopes: (deviceGrant: DeviceGrantDetailsApi | null) => string[]
        requiredScopeLevels: (deviceGrant: DeviceGrantDetailsApi | null) => Map<string, RequiredLevel>
        scopeRows: (
            deviceGrant: DeviceGrantDetailsApi | null,
            consentResourceScopes: string[],
            requiredScopeLevels: Map<string, RequiredLevel>,
            scopeAccessSelections: ScopeAccessSelections
        ) => OAuthScopeRow[]
        requiredScopeRows: (scopeRows: OAuthScopeRow[]) => OAuthScopeRow[]
        adjustableScopeRows: (scopeRows: OAuthScopeRow[]) => OAuthScopeRow[]
        scopeGroups: (adjustableScopeRows: OAuthScopeRow[]) => OAuthScopeGroup[] | null
        allScopesRequired: (scopeRows: OAuthScopeRow[]) => boolean
        scopeSummary: (scopeRows: OAuthScopeRow[], deviceGrant: DeviceGrantDetailsApi | null) => string
        keptScopes: (deviceGrant: DeviceGrantDetailsApi | null, scopeRows: OAuthScopeRow[]) => string[]
    }
}

export type oauthDeviceAuthorizeLogicType = MakeLogicType<
    oauthDeviceAuthorizeLogicValues,
    oauthDeviceAuthorizeLogicActions,
    Record<string, any>,
    oauthDeviceAuthorizeLogicMeta
>

export const oauthDeviceAuthorizeLogic = kea<oauthDeviceAuthorizeLogicType>([
    path(['scenes', 'authentication', 'device', 'oauthDeviceAuthorizeLogic']),
    connect(() => ({
        values: [userLogic, ['user']],
    })),
    actions({
        setUserCode: (userCode: string) => ({ userCode }),
        setOrganizationId: (organizationId: string | null) => ({ organizationId }),
        setProjectId: (projectId: number | null) => ({ projectId }),
        setScopeAccess: (scopeObject: string, level: ScopeAccessLevel) => ({ scopeObject, level }),
        setScopeGroupAccess: (scopeObjects: string[], level: ScopeAccessLevel) => ({ scopeObjects, level }),
    }),
    reducers({
        // The person's picks, per scope object. Absent entries keep the requested level, and every
        // pick is clamped between the required floor and the requested ceiling in scopeRows.
        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])),
                    },
                }),
                lookUpCodeSuccess: () => ({ bulk: null, overrides: {} }),
            },
        ],
        userCode: ['', { setUserCode: (_, { userCode }) => userCode.toUpperCase() }],
        organizationId: [null as string | null, { setOrganizationId: (_, { organizationId }) => organizationId }],
        projectId: [
            null as number | null,
            {
                setProjectId: (_, { projectId }) => projectId,
                setOrganizationId: () => null,
            },
        ],
        projectsError: [
            null as string | null,
            {
                loadProjects: () => null,
                loadProjectsFailure: (_, { errorObject }) => deviceErrorMessage(errorObject),
            },
        ],
        error: [
            null as string | null,
            {
                lookUpCodeFailure: (_, { errorObject }) => deviceErrorMessage(errorObject),
                approveFailure: (_, { errorObject }) => deviceErrorMessage(errorObject),
                denyFailure: (_, { errorObject }) => deviceErrorMessage(errorObject),
                lookUpCode: () => null,
                approve: () => null,
                deny: () => null,
                setUserCode: () => null,
            },
        ],
    }),
    loaders(({ values }) => ({
        deviceGrant: [
            null as DeviceGrantDetailsApi | null,
            {
                lookUpCode: async () => await oauthDeviceLookupCreate({ user_code: values.userCode }),
            },
        ],
        projects: [
            [] as DeviceProject[],
            {
                loadProjects: async (organizationId: string, breakpoint) => {
                    const projects: DeviceProject[] = []
                    for (let offset = 0; ; offset += PROJECTS_PAGE_SIZE) {
                        const page = await organizationsProjectsList(organizationId, {
                            limit: PROJECTS_PAGE_SIZE,
                            offset,
                        })
                        // Drops the answer for an organization the person already switched away from.
                        breakpoint()
                        projects.push(...page.results.map(({ id, name }) => ({ id, name })))
                        if (!page.next) {
                            return projects
                        }
                    }
                },
            },
        ],
        decision: [
            null as DeviceDecisionEnumApi | null,
            {
                approve: async () => {
                    const { deviceGrant, projectId } = values
                    if (!deviceGrant || projectId === null) {
                        return null
                    }
                    return (
                        await oauthDeviceApproveCreate({
                            user_code: deviceGrant.user_code,
                            project_id: projectId,
                            scopes: values.keptScopes,
                        })
                    ).status
                },
                deny: async () => {
                    if (!values.deviceGrant) {
                        return null
                    }
                    return (await oauthDeviceDenyCreate({ user_code: values.deviceGrant.user_code })).status
                },
            },
        ],
    })),
    reducers({
        // Another organization, or a failed load, must not leave the previous organization's projects
        // selectable while the organization picker shows a different one.
        projects: {
            setOrganizationId: () => [],
            loadProjectsFailure: () => [],
        },
        // A code that expired during review goes back to code entry, so the person can type the new one.
        deviceGrant: {
            approveFailure: (state, { errorObject }) => (isInvalidCode(errorObject) ? null : state),
            denyFailure: (state, { errorObject }) => (isInvalidCode(errorObject) ? null : state),
        },
    }),
    selectors({
        organizations: [(s) => [s.user], (user: UserType | null) => user?.organizations ?? []],
        isStepUp: [
            (s) => [s.deviceGrant, s.projectId, s.organizationId],
            // A login that adds nothing, such as logging in again for the same project, lists every scope.
            (
                deviceGrant: DeviceGrantDetailsApi | null,
                projectId: number | null,
                organizationId: string | null
            ): boolean => {
                const added = deviceGrant ? addedScopes(deviceGrant, projectId, organizationId).length : 0
                return added > 0 && added < (deviceGrant?.scopes.length ?? 0)
            },
        ],
        identityScopeDescriptions: [
            (s) => [s.deviceGrant],
            (deviceGrant: DeviceGrantDetailsApi | null): string[] =>
                identityScopeDescriptions(deviceGrant?.scopes ?? []),
        ],
        consentResourceScopes: [
            (s) => [s.deviceGrant],
            (deviceGrant: DeviceGrantDetailsApi | null): string[] =>
                getMinimumEquivalentScopes(deviceGrant?.scopes ?? []).filter((scope) => scope.includes(':')),
        ],
        requiredScopeLevels: [
            (s) => [s.deviceGrant],
            (deviceGrant: DeviceGrantDetailsApi | null): Map<string, RequiredLevel> =>
                requiredLevelsFromScopes(deviceGrant?.required_scopes ?? []),
        ],
        // One row per scope object, built the same way as on the OAuth consent screen. Only required
        // scopes set a floor: a device login replaces the client's stored token, so an earlier grant
        // gives the person no reason to keep that access.
        scopeRows: [
            (s) => [s.deviceGrant, s.consentResourceScopes, s.requiredScopeLevels, s.scopeAccessSelections],
            (
                deviceGrant: DeviceGrantDetailsApi | null,
                consentResourceScopes: string[],
                requiredScopeLevels: Map<string, RequiredLevel>,
                scopeAccessSelections: ScopeAccessSelections
            ): OAuthScopeRow[] =>
                deviceGrant
                    ? buildOAuthScopeRows(
                          consentResourceScopes,
                          scopeAccessSelections,
                          requiredScopeLevels,
                          new Map(),
                          deviceGrant.client_name
                      )
                    : [],
        ],
        requiredScopeRows: [
            (s) => [s.scopeRows],
            (scopeRows: OAuthScopeRow[]): OAuthScopeRow[] => scopeRows.filter((row) => row.locked),
        ],
        adjustableScopeRows: [
            (s) => [s.scopeRows],
            (scopeRows: OAuthScopeRow[]): OAuthScopeRow[] => scopeRows.filter((row) => !row.locked),
        ],
        scopeGroups: [
            (s) => [s.adjustableScopeRows],
            (adjustableScopeRows: OAuthScopeRow[]): OAuthScopeGroup[] | null => scopeGroupsToShow(adjustableScopeRows),
        ],
        allScopesRequired: [
            (s) => [s.scopeRows],
            (scopeRows: OAuthScopeRow[]): boolean => scopeRows.length > 0 && scopeRows.every((row) => row.locked),
        ],
        scopeSummary: [
            (s) => [s.scopeRows, s.deviceGrant],
            (scopeRows: OAuthScopeRow[], deviceGrant: DeviceGrantDetailsApi | null): string =>
                scopeSummary(scopeRows, deviceGrant?.client_name ?? ''),
        ],
        // What approval sends: the required scopes as requested, identity scopes included, and the
        // resource scopes at the level the person picked.
        keptScopes: [
            (s) => [s.deviceGrant, s.scopeRows],
            (deviceGrant: DeviceGrantDetailsApi | null, scopeRows: OAuthScopeRow[]): string[] => {
                if (!deviceGrant) {
                    return []
                }
                const resources = grantedResourceScopes(scopeRows, deviceGrant.scopes, () => [])
                return Array.from(new Set([...deviceGrant.required_scopes, ...resources]))
            },
        ],
    }),
    listeners(({ actions, values }) => ({
        setOrganizationId: ({ organizationId }) => {
            if (organizationId) {
                actions.loadProjects(organizationId)
            }
        },
        loadProjectsSuccess: ({ projects }) => {
            const currentProjectId = values.user?.team?.project_id
            if (values.projectId === null && projects.some((project) => project.id === currentProjectId)) {
                actions.setProjectId(currentProjectId ?? null)
            }
        },
    })),
    urlToAction(({ actions, values }) => ({
        '/device': (_, searchParams) => {
            const code = typeof searchParams.code === 'string' ? searchParams.code : ''
            if (code && code.toUpperCase() !== values.userCode) {
                actions.setUserCode(code)
                actions.lookUpCode()
            }
        },
    })),
    afterMount(({ actions, values }) => {
        const organizationId = values.user?.organization?.id ?? values.user?.organizations?.[0]?.id
        if (organizationId) {
            actions.setOrganizationId(organizationId)
        }
    }),
])