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.

36.2 KB
Raw Blame
import { AGENT_USE_CASE_SCOPES } from 'lib/agentScopes.generated'
import { RISKY_SCOPE_WARNINGS } from 'lib/oauthScopes.generated'

import type { APIScopeAction, APIScopeObject } from '~/types'

// Fallback when the user has not loaded yet. The real limit comes from the `personal_api_keys`
// entitlement and travels on the user as `personal_api_keys_limit`.
export const DEFAULT_MAX_API_KEYS_PER_USER = 10

export type ScopeAccessLevel = 'none' | 'read' | 'write'

const SCOPE_ACCESS_LEVELS: readonly ScopeAccessLevel[] = ['none', 'read', 'write']

const SCOPE_ACCESS_LEVEL_LABELS: Record<ScopeAccessLevel, string> = { none: 'no access', read: 'read', write: 'write' }

/**
 * One scope object in a picker, with the levels it can take. The OAuth consent screen and the key
 * modal both build this shape, so one group control serves both. A level with no disabled reason is
 * available. The reason is the text the row's segment shows.
 */
export type ScopePickerRow = {
    key: string
    label: string
    value: ScopeAccessLevel
    disabledReasons: Partial<Record<ScopeAccessLevel, string>>
    info?: string | JSX.Element
    warning?: string | JSX.Element
    /** True when the row is dimmed, for example at no access or when a project scoped key rules it out. */
    muted?: boolean
}

export type ScopePickerGroup<Row extends ScopePickerRow = ScopePickerRow> = {
    label: string
    rows: Row[]
}

export const scopeRowAllows = (row: ScopePickerRow, level: ScopeAccessLevel): boolean => !row.disabledReasons[level]

// The nearest available level: the same or a lower one first, so a group set to write holds a
// read-only row at read, then a higher one, so a row an app requires at read never drops to none.
export const clampScopeLevel = (row: ScopePickerRow, level: ScopeAccessLevel): ScopeAccessLevel => {
    const index = SCOPE_ACCESS_LEVELS.indexOf(level)
    const candidates = [...SCOPE_ACCESS_LEVELS.slice(0, index + 1).reverse(), ...SCOPE_ACCESS_LEVELS.slice(index + 1)]
    return candidates.find((candidate) => scopeRowAllows(row, candidate)) ?? row.value
}

// The group shows a level as selected when each row is at that level after the clamp. A level no
// row can take is never selected, which removes the tie between write and read in a group with no
// writable row, and between none and read in a group of required rows.
export const scopeGroupLevel = (rows: ScopePickerRow[]): ScopeAccessLevel | undefined =>
    [...SCOPE_ACCESS_LEVELS]
        .reverse()
        .find(
            (level) =>
                rows.some((row) => scopeRowAllows(row, level)) &&
                rows.every((row) => row.value === clampScopeLevel(row, level))
        )

// A level is disabled on the group when no row can take it. The reason is the rows' own.
export const scopeGroupDisabledReasons = (rows: ScopePickerRow[]): Partial<Record<ScopeAccessLevel, string>> =>
    Object.fromEntries(
        SCOPE_ACCESS_LEVELS.flatMap((level) => {
            const reason = rows.find((row) => !scopeRowAllows(row, level))?.disabledReasons[level]
            return reason && rows.every((row) => !scopeRowAllows(row, level)) ? [[level, reason]] : []
        })
    )

// Tooltip on the selected group level, for the rows that sit at another level after the clamp.
// Each row gives the reason its own segment shows, so the text names the real cause.
export const scopeGroupTooltip = (rows: ScopePickerRow[], level: ScopeAccessLevel | undefined): string | undefined => {
    if (!level) {
        return undefined
    }
    const counts = new Map<string, number>()
    for (const row of rows.filter((row) => row.value !== level)) {
        const note = `at ${SCOPE_ACCESS_LEVEL_LABELS[row.value]}: ${row.disabledReasons[level] ?? ''}`
        counts.set(note, (counts.get(note) ?? 0) + 1)
    }
    const notes = [...counts].map(
        ([note, count]) => `${count} of these permissions ${count === 1 ? 'stays' : 'stay'} ${note}.`
    )
    return notes.length > 0 ? notes.join(' ') : undefined
}

export const countScopeRowsByLevel = (rows: { value: ScopeAccessLevel }[]): Record<ScopeAccessLevel, number> => {
    const counts: Record<ScopeAccessLevel, number> = { none: 0, read: 0, write: 0 }
    for (const row of rows) {
        counts[row.value] += 1
    }
    return counts
}

export type APIScope = {
    key: APIScopeObject
    objectName: string
    objectPlural: string
    info?: string | JSX.Element
    disabledActions?: ('read' | 'write')[]
    disabledWhenProjectScoped?: boolean
    description?: string
    warnings?: Partial<Record<'read' | 'write', string | JSX.Element>>
    /** Mirrors `PRIVILEGED_SCOPES` in posthog/scopes.py — excluded from every unprivileged preset. */
    unprivilegedExcluded?: boolean
}

/** Fields a scope search matches against. `label` covers rows that show a name outside `objectName`. */
export type ScopeSearchFields = {
    key?: string
    objectName?: string
    objectPlural?: string
    label?: string
    info?: string | JSX.Element
}

/**
 * Shared scope-search matcher for every scope picker. It splits the term into tokens and requires
 * each token to appear in the scope's key, names, or info text, so a multi-word or plural search
 * still matches the label the row shows. Keep all pickers on this one matcher so they can't drift.
 */
export function scopeMatchesSearch(scope: ScopeSearchFields, searchTerm: string): boolean {
    const tokens = searchTerm.toLowerCase().trim().split(/\s+/).filter(Boolean)
    if (tokens.length === 0) {
        return true
    }
    const haystack = [scope.key, scope.objectName, scope.objectPlural, scope.label, scope.info]
        .filter((field): field is string => typeof field === 'string')
        .join(' ')
        .toLowerCase()
    return tokens.every((token) => haystack.includes(token))
}

/**
 * The warning a scope picker row shows for a risky scope at the picked level. The backend owns the list of
 * risky scopes and their wording. Write access includes read, so a write pick also shows the read warning.
 */
export const riskyScopeWarning = (
    scopeObject: string,
    level: ScopeAccessLevel,
    riskyScopes: Record<string, string>
): string | undefined => {
    const actions: APIScopeAction[] = level === 'write' ? ['write', 'read'] : level === 'read' ? ['read'] : []
    const warnings = actions.map((action) => riskyScopes[`${scopeObject}:${action}`]).filter(Boolean)
    return warnings.length > 0 ? `Add with care: ${warnings.join(' ')}` : undefined
}

/**
 * What a personal API key or OAuth scope row warns about at the picked level: the scope's own note, such as a
 * feature flag it also writes, followed by the backend's risky scope warning.
 */
export function scopeRowWarning(
    apiScope: APIScope | undefined,
    scopeObject: string,
    level: ScopeAccessLevel
): string | JSX.Element | undefined {
    const note = level === 'none' ? undefined : apiScope?.warnings?.[level]
    const risky = riskyScopeWarning(scopeObject, level, RISKY_SCOPE_WARNINGS)
    return note && risky ? (
        <>
            {note} {risky}
        </>
    ) : (
        (note ?? risky)
    )
}

// Scopes whose write action also writes a feature flag as a side effect (survey targeting flag,
// early access feature linked flag), so they imply `feature_flag:write`. Single source of truth for
// both the picker warning (attached below) and the auto-select in personalAPIKeysLogic, so the rule
// and the copy can't drift. `ScopeAccessRow` renders warnings as plain text — no markdown formatting.
export const SCOPES_IMPLYING_FEATURE_FLAG_WRITE: Partial<Record<APIScopeObject, string>> = {
    survey: 'Surveys with targeting also manage a feature flag, so this key needs write access to feature flags too.',
    early_access_feature:
        'Early access features manage a linked feature flag, so this key needs write access to feature flags too.',
}

export const API_SCOPES: APIScope[] = [
    { key: 'action', objectName: 'Action', objectPlural: 'actions' },
    { key: 'access_control', objectName: 'Access control', objectPlural: 'access controls' },
    { key: 'account', objectName: 'Account', objectPlural: 'accounts' },
    { key: 'activity_log', objectName: 'Activity log', objectPlural: 'activity logs' },
    { key: 'alert', objectName: 'Alert', objectPlural: 'alerts' },
    { key: 'annotation', objectName: 'Annotation', objectPlural: 'annotations' },
    { key: 'approvals', objectName: 'Approvals', objectPlural: 'approvals' },
    { key: 'autoresearch', objectName: 'Autoresearch', objectPlural: 'autoresearch pipelines' },
    { key: 'batch_export', objectName: 'Batch export', objectPlural: 'batch exports' },
    { key: 'billing', objectName: 'Billing', objectPlural: 'billing' },
    { key: 'business_knowledge', objectName: 'Business knowledge', objectPlural: 'business knowledge' },
    { key: 'canvas', objectName: 'Canvas', objectPlural: 'canvases' },
    {
        key: 'workload_trust_policy',
        objectName: 'Workload trust policy',
        objectPlural: 'workload trust policies',
        disabledActions: ['write'],
    },
    {
        key: 'workload_trust_policy_request',
        objectName: 'Workload trust policy request',
        objectPlural: 'workload trust policy requests',
        info: 'Write access lets the key ask an organization admin for a workload trust policy. A request grants nothing until an admin approves it.',
    },
    { key: 'cohort', objectName: 'Cohort', objectPlural: 'cohorts' },
    { key: 'comment', objectName: 'Comment', objectPlural: 'comments' },
    {
        key: 'conversation',
        objectName: 'AI conversation',
        objectPlural: 'AI conversations',
        info: 'Programmatic access to the PostHog AI (Max) chat via the conversations API.',
    },
    { key: 'customer_analytics', objectName: 'Customer analytics', objectPlural: 'customer analytics' },
    { key: 'customer_task', objectName: 'Customer task', objectPlural: 'customer tasks' },
    { key: 'customer_journey', objectName: 'Customer journey', objectPlural: 'customer journeys' },
    { key: 'data_catalog', objectName: 'Data catalog', objectPlural: 'data catalog' },
    {
        key: 'data_catalog_approval',
        objectName: 'Data catalog approval',
        objectPlural: 'data catalog approvals',
        info: 'Grants the ability to promote catalog entries (approve a metric, certify a table, accept a relationship). This is the human-in-the-loop trust boundary: agents that can write to the catalog still cannot self-approve without this scope.',
        disabledActions: ['read'],
    },
    { key: 'data_deletion', objectName: 'Data deletion', objectPlural: 'data deletion requests' },
    { key: 'dashboard', objectName: 'Dashboard', objectPlural: 'dashboards' },
    { key: 'dashboard_template', objectName: 'Dashboard template', objectPlural: 'dashboard templates' },
    {
        key: 'cross_project_dashboard',
        objectName: 'Cross-project dashboard',
        objectPlural: 'cross-project dashboards',
        disabledWhenProjectScoped: true,
    },
    { key: 'dataset', objectName: 'Dataset', objectPlural: 'datasets' },
    {
        key: 'early_access_feature',
        objectName: 'Early access feature',
        objectPlural: 'early access features',
        warnings: {
            write: SCOPES_IMPLYING_FEATURE_FLAG_WRITE.early_access_feature,
        },
    },
    { key: 'element', objectName: 'Element', objectPlural: 'elements' },
    { key: 'endpoint', objectName: 'Endpoint', objectPlural: 'endpoints' },
    { key: 'engineering_analytics', objectName: 'Engineering analytics', objectPlural: 'engineering analytics' },
    { key: 'event_definition', objectName: 'Event definition', objectPlural: 'event definitions' },
    { key: 'event_filter', objectName: 'Event filter', objectPlural: 'event filters' },
    { key: 'error_tracking', objectName: 'Error tracking', objectPlural: 'error tracking' },
    { key: 'evaluation', objectName: 'Evaluation', objectPlural: 'evaluations' },
    {
        key: 'offline_evaluation_ingestion',
        objectName: 'Offline evaluation ingestion',
        objectPlural: 'offline evaluation uploads',
        info: 'Create experiments, upload results, and mark experiments as completed or failed.',
        disabledActions: ['read'],
    },
    { key: 'experiment', objectName: 'Experiment', objectPlural: 'experiments' },
    { key: 'experiment_holdout', objectName: 'Holdout', objectPlural: 'holdouts' },
    { key: 'experiment_saved_metric', objectName: 'Shared metric', objectPlural: 'shared metrics' },
    { key: 'external_data_source', objectName: 'External data source', objectPlural: 'external data sources' },
    { key: 'export', objectName: 'Export', objectPlural: 'exports' },
    { key: 'feature_flag', objectName: 'Feature flag', objectPlural: 'feature flags' },
    {
        key: 'file_system',
        objectName: 'File system',
        objectPlural: 'file system items',
        // Read-only for now: the file-system delete path cascades into the backing
        // object (dashboard, insight, cohort, feature flag, hog function, ...), so a
        // `file_system:write` token would bypass the more specific resource scopes.
        disabledActions: ['write'],
    },
    { key: 'file_system_shortcut', objectName: 'File system shortcut', objectPlural: 'file system shortcuts' },
    { key: 'group', objectName: 'Group', objectPlural: 'groups' },
    { key: 'health_issue', objectName: 'Health issue', objectPlural: 'health issues' },
    { key: 'heatmap', objectName: 'Heatmap', objectPlural: 'heatmaps' },
    { key: 'hog_flow', objectName: 'Workflow', objectPlural: 'workflows' },
    { key: 'hog_function', objectName: 'Hog function', objectPlural: 'hog functions' },
    { key: 'inbox', objectName: 'Inbox', objectPlural: 'inbox reports' },
    {
        key: 'ingestion_warning',
        objectName: 'Ingestion warning',
        objectPlural: 'ingestion warnings',
        disabledActions: ['write'],
    },
    { key: 'insight', objectName: 'Insight', objectPlural: 'insights' },
    { key: 'insight_variable', objectName: 'Insight variable', objectPlural: 'insight variables' },
    { key: 'integration', objectName: 'Integration', objectPlural: 'integrations', disabledActions: ['write'] },
    { key: 'legal_document', objectName: 'Legal document', objectPlural: 'legal documents' },
    { key: 'link', objectName: 'Link', objectPlural: 'links' },
    { key: 'knowledge_writer', objectName: 'Knowledge writer', objectPlural: 'knowledge writer verdicts' },
    { key: 'live_debugger', objectName: 'Live debugger', objectPlural: 'live debugger' },
    { key: 'llm_analytics', objectName: 'AI observability', objectPlural: 'AI observability' },
    { key: 'ai_observability_clusters', objectName: 'Cluster', objectPlural: 'clusters' },
    {
        key: 'llm_gateway',
        objectName: 'LLM gateway',
        objectPlural: 'LLM gateway',
        disabledActions: ['write'],
        unprivilegedExcluded: true,
    },
    { key: 'llm_playground', objectName: 'LLM playground', objectPlural: 'LLM playground' },
    { key: 'llm_prompt', objectName: 'LLM prompt', objectPlural: 'LLM prompts' },
    { key: 'llm_provider_key', objectName: 'LLM provider key', objectPlural: 'LLM provider keys' },
    { key: 'llm_skill', objectName: 'LLM skill', objectPlural: 'LLM skills' },
    { key: 'logs', objectName: 'Logs', objectPlural: 'logs' },
    { key: 'loop', objectName: 'Loop', objectPlural: 'loops' },
    { key: 'marketing_analytics', objectName: 'Marketing analytics', objectPlural: 'marketing analytics' },
    { key: 'mcp_analytics', objectName: 'MCP analytics', objectPlural: 'MCP analytics' },
    { key: 'metrics', objectName: 'Metrics', objectPlural: 'metrics' },
    { key: 'notebook', objectName: 'Notebook', objectPlural: 'notebooks' },
    { key: 'organization', objectName: 'Organization', objectPlural: 'organizations', disabledWhenProjectScoped: true },
    {
        key: 'organization_integration',
        objectName: 'Organization integration',
        objectPlural: 'organization integrations',
        disabledWhenProjectScoped: true,
    },
    {
        key: 'organization_member',
        objectName: 'Organization member',
        objectPlural: 'organization members',
        disabledWhenProjectScoped: true,
    },
    { key: 'person', objectName: 'Person', objectPlural: 'persons' },
    { key: 'customer_profile_config', objectName: 'Customer profile config', objectPlural: 'customer profile configs' },
    { key: 'plugin', objectName: 'Plugin', objectPlural: 'plugins' },
    {
        key: 'product_enablement',
        objectName: 'Product enablement',
        objectPlural: 'product enablement',
        disabledActions: ['read'],
    },
    { key: 'product_tour', objectName: 'Product tour', objectPlural: 'product tours' },
    {
        key: 'project',
        objectName: 'Project',
        objectPlural: 'projects',
        info: 'If you grant write access, this scope can be used to create or modify projects, including settings about how data is ingested.',
    },
    { key: 'property_definition', objectName: 'Property definition', objectPlural: 'property definitions' },
    { key: 'query', objectName: 'Query', objectPlural: 'queries', disabledActions: ['write'] },
    { key: 'replay_scanner', objectName: 'Replay scanner', objectPlural: 'replay scanners' },
    { key: 'revenue_analytics', objectName: 'Revenue analytics', objectPlural: 'revenue analytics' },
    { key: 'session_recording', objectName: 'Session recording', objectPlural: 'session recordings' },
    {
        key: 'session_recording_playlist',
        objectName: 'Session recording playlist',
        objectPlural: 'session recording playlists',
    },
    { key: 'sharing_configuration', objectName: 'Sharing configuration', objectPlural: 'sharing configurations' },
    { key: 'subscription', objectName: 'Subscription', objectPlural: 'subscriptions' },
    { key: 'support_ticket', objectName: 'Support ticket', objectPlural: 'support tickets' },
    {
        key: 'survey',
        objectName: 'Survey',
        objectPlural: 'surveys',
        warnings: {
            write: SCOPES_IMPLYING_FEATURE_FLAG_WRITE.survey,
        },
    },
    { key: 'tagger', objectName: 'Tagger', objectPlural: 'taggers' },
    { key: 'ticket', objectName: 'Ticket', objectPlural: 'tickets' },
    { key: 'toolbar', objectName: 'Toolbar', objectPlural: 'toolbar' },
    { key: 'tracing', objectName: 'Tracing', objectPlural: 'tracing' },
    {
        key: 'transactional_email',
        objectName: 'Transactional email',
        objectPlural: 'transactional emails',
        info: "Write makes a template transactional and sends email from it. Read gets a sent email's status and works only with a project secret API key. This scope can't edit templates or workflows.",
    },
    { key: 'field_note', objectName: 'Field note', objectPlural: 'field notes' },
    { key: 'uploaded_media', objectName: 'Uploaded media', objectPlural: 'uploaded media' },
    { key: 'usage_metric', objectName: 'Usage metric', objectPlural: 'usage metrics' },
    {
        key: 'user',
        objectName: 'User',
        objectPlural: 'users',
        disabledActions: ['write'],
    },
    { key: 'signal_scout', objectName: 'Signals agent', objectPlural: 'signals agents' },
    {
        key: 'signal_usage',
        objectName: 'Self-driving usage',
        objectPlural: 'self-driving usage',
        disabledActions: ['write'],
    },
    { key: 'review_hog', objectName: 'PostHog Review', objectPlural: 'PostHog Review reviews' },
    { key: 'stamphog', objectName: 'Stamphog', objectPlural: 'stamphog' },
    { key: 'streamlit_app', objectName: 'Streamlit app', objectPlural: 'Streamlit apps' },
    { key: 'task', objectName: 'Task', objectPlural: 'tasks' },
    { key: 'today', objectName: 'Today home', objectPlural: 'Today home' },
    { key: 'user_interview', objectName: 'User interview', objectPlural: 'user interviews' },
    { key: 'vision_alert', objectName: 'Vision alert', objectPlural: 'vision alerts' },
    { key: 'visual_review', objectName: 'Visual review', objectPlural: 'visual reviews' },
    {
        key: 'webhook',
        objectName: 'Webhook',
        objectPlural: 'webhooks',
        info: 'Webhook configuration is currently only enabled for the Zapier integration.',
    },
    { key: 'warehouse_view', objectName: 'Warehouse view', objectPlural: 'warehouse views' },
    { key: 'warehouse_table', objectName: 'Warehouse table', objectPlural: 'warehouse tables' },
    { key: 'web_analytics', objectName: 'Web analytics', objectPlural: 'web analytics' },
]
API_SCOPES.sort((a, b) => a.objectName.localeCompare(b.objectName))

// Scope objects deliberately absent from the key-creation modal above, each with the reason.
// Every scope object in `ScopeObjectEnumApi` must be either offered in `API_SCOPES` or listed here,
// except the OAuth-hidden ones in `OAUTH_SCOPES_HIDDEN` (lib/oauthScopes.generated), which no picker shows.
// scopes.test.ts enforces that partition so a newly added backend scope can't silently go missing.
export const API_SCOPES_OMITTED_FROM_MODAL: Partial<Record<APIScopeObject, string>> = {
    // Umbrella access-control resource that `warehouse_view`/`warehouse_table` inherit from —
    // the granular scopes are offered instead, so keep the umbrella out of the modal.
    warehouse_objects: 'Umbrella resource: grant warehouse_view/warehouse_table instead.',
    // Pending removal — no endpoint enforces these, so they do nothing when granted.
    // Remove from posthog/scopes.py once no PAK/OAuth grant references them.
    batch_import: 'Pending removal: no endpoint enforces it (its viewset is INTERNAL).',
    mcp_registry: 'Behind a feature flag.',
    external_data_schema: 'Pending removal: covered by external_data_source; no viewset uses it.',
    vision_action: 'Retired: no endpoint enforces it; kept for desktop OAuth clients that still request it.',
}

// Keep in sync with PROJECT_SECRET_API_KEY_ALLOWED_API_SCOPE_ACTION in posthog/scopes.py.
// posthog/test/test_scopes.py compares the two lists.
export const PROJECT_SECRET_API_KEY_ALLOWED_API_SCOPE_ACTION = [
    'endpoint:read',
    'feature_flag:read',
    'account:read',
    'account:write',
    'support_ticket:read',
    'loop:write',
    'experiment:read',
    'offline_evaluation_ingestion:write',
    'billing:read',
    'replay_scanner:write',
    'session_recording:read',
    'hog_flow:read',
    'hog_flow:write',
    'messaging_preference:write',
    'transactional_email:read',
    'transactional_email:write',
    'llm_prompt:read',
] as const

export type ProjectSecretAPIKeyAllowedScope = (typeof PROJECT_SECRET_API_KEY_ALLOWED_API_SCOPE_ACTION)[number]

const API_KEY_CREATION_ACTIONS = ['read', 'write'] as const

// Scopes the manual key-creation UI can render and submit. This excludes actions
// disabled for Personal API Keys and any generated scope whose object has no UI row.
const API_KEY_CREATION_RENDERABLE_SCOPES = new Set(
    API_SCOPES.flatMap(({ key, disabledActions }) =>
        API_KEY_CREATION_ACTIONS.filter((action) => !disabledActions?.includes(action)).map(
            (action) => `${key}:${action}`
        )
    )
)

// Actions the manual key-creation UI withholds from Personal API Keys
// (e.g. file_system:write, integration:write, user:write) — see `disabledActions`
// above.
export const API_KEY_CREATION_DISABLED_SCOPES = new Set(
    API_SCOPES.flatMap(({ key, disabledActions }) => (disabledActions ?? []).map((action) => `${key}:${action}`))
)

// A preset must not set a level the key picker cannot show, or the picker shows the level on a
// disabled segment. A write on a write-disabled object falls back to read, which write implies on the
// server anyway. A scope with no allowed level is dropped.
export const clampToKeyCreationScopes = (scopes: readonly string[]): string[] => [
    ...new Set(
        scopes.flatMap((scope) => {
            if (API_KEY_CREATION_RENDERABLE_SCOPES.has(scope)) {
                return [scope]
            }
            const [object, action] = scope.split(':')
            const read = `${object}:read`
            return action === 'write' && API_KEY_CREATION_RENDERABLE_SCOPES.has(read) ? [read] : []
        })
    ),
]

export const AGENT_CLI_API_KEY_SCOPES = clampToKeyCreationScopes(AGENT_USE_CASE_SCOPES)

export const API_KEY_SCOPE_PRESETS: {
    value: string
    label: string
    scopes: string[]
    access_type?: 'all' | 'organizations' | 'teams'
    isCloudOnly?: boolean
}[] = [
    { value: 'local_evaluation', label: 'Local feature flag evaluation', scopes: ['feature_flag:read'] },
    {
        value: 'source_map_upload',
        label: 'Source map upload',
        scopes: ['organization:read', 'error_tracking:write'],
    },
    {
        value: 'zapier',
        label: 'Zapier integration',
        scopes: ['action:read', 'query:read', 'project:read', 'organization:read', 'user:read', 'webhook:write'],
    },
    {
        value: 'n8n',
        label: 'n8n integration',
        scopes: ['action:read', 'query:read', 'project:read', 'organization:read', 'user:read', 'webhook:write'],
    },
    { value: 'analytics', label: 'Performing analytics queries', scopes: ['query:read'] },
    { value: 'endpoints', label: 'Endpoint execution', scopes: ['endpoint:read'] },
    {
        value: 'project_management',
        label: 'Project & user management',
        scopes: ['project:write', 'organization:read', 'organization_member:write'],
    },
    {
        value: 'mcp_server',
        label: 'MCP Server',
        // file_system is excluded because the MCP server doesn't request it, not because it's privileged.
        scopes: clampToKeyCreationScopes(
            API_SCOPES.filter(({ key, unprivilegedExcluded }) => !unprivilegedExcluded && key !== 'file_system').map(
                ({ key }) => `${key}:write`
            )
        ),
        access_type: 'all',
    },
    {
        value: 'agent_cli',
        label: 'Agent CLI',
        scopes: AGENT_CLI_API_KEY_SCOPES,
        access_type: 'all',
    },
    {
        value: 'read_only_access',
        label: 'Read-only access',
        scopes: clampToKeyCreationScopes(
            API_SCOPES.filter(({ unprivilegedExcluded }) => !unprivilegedExcluded).map(({ key }) => `${key}:read`)
        ),
    },
    { value: 'all_access', label: 'All access', scopes: ['*'] },
]

export const APIScopeActionLabels: Record<APIScopeAction, string> = {
    read: 'Read',
    write: 'Write',
}

export type ProjectSecretAPIKeyScopePreset = {
    value: string
    label: string
    scopes: string[]
    isCloudOnly?: boolean
}

export const PROJECT_SECRET_API_KEY_SCOPE_PRESETS: ProjectSecretAPIKeyScopePreset[] = [
    { value: 'endpoint_execution', label: 'Endpoint execution', scopes: ['endpoint:read'] },
    { value: 'local_evaluation', label: 'Local feature flag evaluation', scopes: ['feature_flag:read'] },
    { value: 'llm_gateway', label: 'AI gateway access', scopes: ['llm_gateway:read'] },
    { value: 'recipient_preferences', label: 'Set recipient preferences', scopes: ['messaging_preference:write'] },
    { value: 'transactional_email', label: 'Send transactional email', scopes: ['transactional_email:write'] },
]

// The product areas that the scope pickers use to group objects, in display order. Each scope object
// in `ScopeObjectEnumApi` is in exactly one group, except the OAuth-hidden ones, which no picker shows.
// scopes.test.ts fails until a new object has a group.
export type APIScopeGroup = {
    label: string
    objects: APIScopeObject[]
}

export const API_SCOPE_GROUPS: APIScopeGroup[] = [
    {
        label: 'Product analytics',
        objects: [
            'insight',
            'insight_variable',
            'dashboard',
            'dashboard_template',
            'cross_project_dashboard',
            'query',
            'notebook',
            'canvas',
            'subscription',
            'alert',
            'annotation',
            'export',
            'sharing_configuration',
        ],
    },
    {
        label: 'Web, marketing & revenue analytics',
        objects: ['web_analytics', 'marketing_analytics', 'revenue_analytics', 'heatmap', 'link'],
    },
    {
        label: 'Events, people & data model',
        objects: [
            'person',
            'group',
            'cohort',
            'action',
            'event_definition',
            'property_definition',
            'event_filter',
            'element',
        ],
    },
    {
        label: 'Session replay',
        objects: ['session_recording', 'session_recording_playlist', 'replay_scanner', 'vision_action', 'vision_alert'],
    },
    {
        label: 'Feature flags, experiments & surveys',
        objects: [
            'feature_flag',
            'experiment',
            'experiment_holdout',
            'experiment_saved_metric',
            'early_access_feature',
            'survey',
            'user_interview',
            'product_tour',
        ],
    },
    {
        label: 'Error tracking, logs & tracing',
        objects: ['error_tracking', 'logs', 'tracing', 'metrics'],
    },
    {
        label: 'Developer experience',
        objects: ['engineering_analytics', 'knowledge_writer', 'stamphog', 'visual_review'],
    },
    {
        label: 'LLM & MCP analytics',
        objects: [
            'llm_analytics',
            'llm_prompt',
            'llm_provider_key',
            'llm_skill',
            'llm_playground',
            'dataset',
            'evaluation',
            'offline_evaluation_ingestion',
            'tagger',
            'ai_observability_clusters',
            'mcp_analytics',
            'llm_gateway',
        ],
    },
    {
        label: 'Data warehouse & pipelines',
        objects: [
            'external_data_source',
            'external_data_schema',
            'warehouse_objects',
            'warehouse_table',
            'warehouse_view',
            'batch_export',
            'batch_import',
            'hog_function',
            'hog_flow',
            'endpoint',
            'streamlit_app',
            'webhook',
            'plugin',
        ],
    },
    {
        label: 'Messaging',
        objects: ['transactional_email'],
    },
    {
        label: 'AI & context management tools',
        objects: [
            'conversation',
            'business_knowledge',
            'data_catalog',
            'data_catalog_approval',
            'mcp_registry',
            'task',
            'inbox',
            'today',
            'loop',
            'signal_scout',
            'signal_usage',
            'review_hog',
            'approvals',
            'autoresearch',
            'field_note',
        ],
    },
    {
        label: 'Customers & support',
        objects: [
            'customer_analytics',
            'account',
            'customer_journey',
            'customer_task',
            'customer_profile_config',
            'usage_metric',
            'ticket',
            'support_ticket',
        ],
    },
    {
        label: 'Setup & data management',
        objects: [
            'toolbar',
            'live_debugger',
            'ingestion_warning',
            'health_issue',
            'data_deletion',
            'product_enablement',
            'integration',
            'organization_integration',
        ],
    },
    {
        label: 'Organization & account',
        objects: [
            'organization',
            'organization_member',
            'project',
            'workload_trust_policy',
            'workload_trust_policy_request',
            'user',
            'billing',
            'access_control',
            'activity_log',
            'comment',
            'legal_document',
            'uploaded_media',
            'file_system',
            'file_system_shortcut',
        ],
    },
]

export const OTHER_SCOPE_GROUP_LABEL = 'Other'

// An object that is in no group gets OTHER_SCOPE_GROUP_LABEL, so it still renders.
const SCOPE_GROUP_LABEL_BY_OBJECT: Record<string, string> = Object.fromEntries(
    API_SCOPE_GROUPS.flatMap(({ label, objects }) => objects.map((object) => [object, label]))
)

export const getScopeGroupLabel = (scopeObject: string): string =>
    SCOPE_GROUP_LABEL_BY_OBJECT[scopeObject] ?? OTHER_SCOPE_GROUP_LABEL

// The rows grouped by product area in API_SCOPE_GROUPS order. An object that is in no group goes in
// the "Other" group at the end, so it still shows. A group with no row is left out.
export const groupScopeRows = <Row extends ScopePickerRow>(rows: Row[]): ScopePickerGroup<Row>[] => {
    const rowsByLabel = new Map<string, Row[]>()
    for (const row of rows) {
        const label = getScopeGroupLabel(row.key)
        rowsByLabel.set(label, [...(rowsByLabel.get(label) ?? []), row])
    }
    return [...API_SCOPE_GROUPS.map(({ label }) => label), OTHER_SCOPE_GROUP_LABEL]
        .filter((label) => rowsByLabel.has(label))
        .map((label) => ({ label, rows: rowsByLabel.get(label) ?? [] }))
}

export type ScopeGroupSummary = { label: string; write: number; read: number }

// Counts the objects in each product area that a key can write, or only read, in API_SCOPE_GROUPS order.
// `insight:read` and `insight:write` together count once, as write.
export const summarizeScopesByGroup = (scopes: readonly string[]): ScopeGroupSummary[] => {
    const levelByObject = new Map<string, 'read' | 'write'>()
    for (const scope of scopes) {
        const [object, action] = scope.split(':')
        if (levelByObject.get(object) !== 'write') {
            levelByObject.set(object, action === 'write' ? 'write' : 'read')
        }
    }
    const summaryByLabel = new Map<string, ScopeGroupSummary>()
    for (const [object, level] of levelByObject) {
        const label = getScopeGroupLabel(object)
        const summary = summaryByLabel.get(label) ?? { label, write: 0, read: 0 }
        summary[level] += 1
        summaryByLabel.set(label, summary)
    }
    return [...API_SCOPE_GROUPS.map(({ label }) => label), OTHER_SCOPE_GROUP_LABEL].flatMap((label) => {
        const summary = summaryByLabel.get(label)
        return summary ? [summary] : []
    })
}

export const DEFAULT_OAUTH_SCOPES = ['openid', 'email', 'profile']

export const getScopeDescription = (scope: string): string | undefined => {
    if (scope === '*') {
        return 'Read and write access to all PostHog data'
    }

    if (scope === 'openid') {
        return 'View your User ID'
    }

    if (scope === 'email') {
        return 'View your email address'
    }

    if (scope === 'profile') {
        return 'View basic user account information'
    }

    if (scope === 'introspection') {
        // OAuth-internal scope — never shown to users; list call sites .filter(Boolean) it out.
        return undefined
    }

    const [object, action] = scope.split(':')

    if (!object || !action) {
        return scope
    }

    const actionWord = action === 'write' ? 'Write' : 'Read'

    const scopeObject = API_SCOPES.find((s) => s.key === object)
    if (!scopeObject) {
        // OAuth-hidden scope (e.g. wizard_session, query_performance) — absent from API_SCOPES,
        // so derive a readable label from the raw key rather than surfacing the raw identifier.
        return `${actionWord} access to ${object.replace(/_/g, ' ')}`
    }

    return `${actionWord} access to ${scopeObject.objectPlural}`
}

export const getMinimumEquivalentScopes = (scopes: string[]): string[] => {
    if (scopes.includes('*')) {
        return ['*']
    }

    const highestScopes: Record<string, string> = {}

    for (const scope of scopes) {
        if (['openid', 'email', 'profile'].includes(scope)) {
            highestScopes[scope] = 'default'
            continue
        }

        const [object, action] = scope.split(':')
        if (!object || !action) {
            continue
        }
        if (!highestScopes[object] || (action === 'write' && highestScopes[object] === 'read')) {
            highestScopes[object] = action
        }
    }

    return Object.entries(highestScopes).map(([object, action]) => {
        if (action === 'default') {
            return object
        }
        return `${object}:${action}`
    })
}

/** Convert scopes array format to object format for easier UI manipulation */
export const scopesArrayToObject = (scopes: string[]): Record<string, string> => {
    const result: Record<string, string> = {}
    scopes.forEach((scope) => {
        const [key, action] = scope.split(':')
        if (key && action) {
            result[key] = action
        }
    })
    return result
}

/** Convert scopes object format back to array format for API submission */
export const scopesObjectToArray = (scopesObj: Record<string, string>): string[] => {
    return Object.entries(scopesObj).map(([key, action]) => `${key}:${action}`)
}