: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.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
import { MakeLogicType, actions, afterMount, connect, kea, listeners, path, reducers, selectors } from 'kea'
import { loaders } from 'kea-loaders'
import { router, urlToAction } from 'kea-router'
import { LemonDialog, lemonToast } from '@posthog/lemon-ui'
import api, { ApiError, getCookie } from 'lib/api'
import { globalSetupLogic } from 'lib/components/ProductSetup'
import { FEATURE_FLAGS } from 'lib/constants'
import { buildGithubDisconnectDescription } from 'lib/integrations/githubDisconnectCopy'
import { describeGithubSetupError, GITHUB_INSTALL_PENDING_MESSAGE } from 'lib/integrations/githubSetupErrors'
import { describeScopeShortfall, getMissingScopes, requestedScopesForKind } from 'lib/integrations/integrationScopes'
import {
describeOAuthCallbackError,
INTEGRATION_ERROR_PARAM,
OAUTH_STATE_EXPIRED,
} from 'lib/integrations/oauthCallbackErrors'
import { FeatureFlagsSet, featureFlagLogic } from 'lib/logic/featureFlagLogic'
import { preflightLogic } from 'lib/logic/preflightLogic'
import { eventUsageLogic } from 'lib/utils/eventUsageLogic'
import { isKeyOf } from 'lib/utils/guards'
import { removeProjectIdIfPresent } from 'lib/utils/kea-router'
import { retryImport } from 'lib/utils/retryImport'
import { fromParamsGivenUrl } from 'lib/utils/url'
import { teamLogic } from 'scenes/teamLogic'
import { urls } from 'scenes/urls'
import { EmailIntegrationDomainGroupedType, IntegrationKind, IntegrationType } from '~/types'
import {
integrationsCreate,
integrationsGithubAvailableInstallationsRetrieve,
integrationsGithubReposRetrieve,
integrationsGithubLinkExistingCreate,
integrationsList,
integrationsRequestAccessCreate,
} from 'products/integrations/frontend/generated/api'
import type {
GitHubAvailableInstallationApi,
GitHubAvailableInstallationsResponseApi,
GitHubRepoApi,
InstallationStatusEnumApi,
IntegrationConfigApi,
IntegrationKindEnumApi,
} from 'products/integrations/frontend/generated/api.schemas'
import { ChannelType } from 'products/workflows/frontend/Channels/MessageChannels'
import type { AvailableSetupTaskIdsEnumApi } from '../../generated/core/api.schemas'
import type { PreflightStatus, UserBasicType } from '../../types'
import { ICONS, getIntegrationNameFromKind } from './utils'
const INTEGRATIONS_POLL_INTERVAL_MS = 30_000
function toastApiError(e: unknown): void {
const detail = e instanceof ApiError ? e.detail : null
lemonToast.error(detail || 'Something went wrong. Please try again.')
}
// The integration landing page (`/integrations/:slug`) and the data warehouse source wizard can
// both keep a failed connect on screen as a banner beside the connect button, so they take the
// reason in the URL instead of a toast that is gone by the time the user reads it. Everywhere
// else the toast is the only carrier.
function landsOnErrorAwarePage(pathname: string): boolean {
// Callers build ``next`` either from ``urls.integration(slug)`` or from the browser pathname,
// so the project prefix is there in some flows and not others.
const segments = removeProjectIdIfPresent(pathname).split('/').filter(Boolean)
if (segments.length === 2 && segments[0] === 'integrations') {
return true
}
return segments.length === 2 && segments[0] === 'data-warehouse' && segments[1] === 'new-source'
}
// The backend hex-encodes the state for a provider that does not return it verbatim (see
// `opaque_state` on OauthConfig). A plain state always holds `next=`, so it never matches.
function decodeOpaqueOAuthState(state: string | undefined): string | undefined {
if (!state || !/^(?:[0-9a-f]{2})+$/i.test(state)) {
return state
}
try {
return decodeURIComponent(state.replace(/../g, '%$&'))
} catch {
// A crafted hex state that is not valid UTF-8 carries no token, so the callback rejects it
// as an expired state instead of throwing before it can redirect.
return state
}
}
// Search param the OAuth callback appends with the id of the integration it just created, so the
// page the user lands back on can select the connection they authorized rather than guessing.
// pinned: URL search param — the callback redirect and the landing page both read it.
export const OAUTH_INTEGRATION_ID_PARAM = 'integration_id'
export function integrationAuthorizeUrl(params: Parameters<typeof api.integrations.authorizeUrl>[0]): string {
// nosemgrep: prefer-codegen-api-namespaced-integrations -- generated client does not support the authorize query parameters
return api.integrations.authorizeUrl(params)
}
/** Where an in-place reconnect returns to. Pages like the data warehouse source wizard keep their
* state in the query (`?kind=`), so a bare pathname drops the user somewhere else. The previous
* callback's result params are dropped because the new callback sets its own. */
export function reconnectReturnUrl(pathname: string, search: string): string {
const params = new URLSearchParams(search)
params.delete(OAUTH_INTEGRATION_ID_PARAM)
params.delete(INTEGRATION_ERROR_PARAM)
const query = params.toString()
return query ? `${pathname}?${query}` : pathname
}
// The Slack landing page offers the setup itself, so only the other entry points get the toast.
function offerSlackSetupAfterConnect(
integration: IntegrationType,
pathname: string,
{
currentTeamId,
initiatingTeamId,
setupEnabled,
}: { currentTeamId: number | null; initiatingTeamId: number | undefined; setupEnabled: boolean }
): void {
const landsOnSlackPage = removeProjectIdIfPresent(pathname) === urls.integration('slack')
const otherTeam = initiatingTeamId !== undefined && initiatingTeamId !== currentTeamId
if (integration.kind !== 'slack' || !setupEnabled || landsOnSlackPage || otherTeam || !currentTeamId) {
return
}
void retryImport(() => import('products/slack_app/frontend/workspace-setup/offerSlackWorkspaceSetup'))
.then(({ offerSlackWorkspaceSetup }) => offerSlackWorkspaceSetup(currentTeamId, integration.id, pathname))
.catch(() => {})
}
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface integrationsLogicValues {
featureFlags: FeatureFlagsSet // featureFlagLogic
preflight: PreflightStatus | null // preflightLogic
siteUrlMisconfigured: boolean // preflightLogic
currentProjectId: number | string // teamLogic
currentTeamId: number | null // teamLogic
accessRequest: IntegrationKind | null
accessRequestLoading: boolean
accessRequestReason: string
domainGroupedEmailIntegrations: EmailIntegrationDomainGroupedType[]
getGitHubRepositories: (integrationId: number) => string[]
getGitHubRepositoriesFull: (integrationId: number) => GitHubRepoApi[]
getGitHubRepositoriesTotal: (integrationId: number) => number | null
getIntegrationsByKind: (
kinds: (
| 'apns'
| 'apple-ads'
| 'aws-redshift'
| 'aws-s3'
| 'azure-blob'
| 'bing-ads'
| 'clickup'
| 'customerio-app'
| 'customerio-track'
| 'customerio-webhook'
| 'databricks'
| 'email'
| 'firebase'
| 'github'
| 'gitlab'
| 'google-ads'
| 'google-analytics'
| 'google-calendar'
| 'google-cloud-service-account'
| 'google-cloud-storage'
| 'google-pubsub'
| 'google-search-console'
| 'google-sheets'
| 'helpscout'
| 'hubspot'
| 'instagram'
| 'intercom'
| 'jira'
| 'linear'
| 'linkedin-ads'
| 'meta-ads'
| 'pardot'
| 'pinterest-ads'
| 'postgresql'
| 'reddit-ads'
| 's3-compatible'
| 'salesforce'
| 'slack'
| 'snapchat'
| 'snowflake'
| 'stripe'
| 'tiktok-ads'
| 'twilio'
| 'twitter-ads'
| 'vercel'
| 'youtube-analytics'
)[]
) => IntegrationType[]
githubAvailableInstallations: GitHubAvailableInstallationApi[] | null
githubAvailableInstallationsResponse: GitHubAvailableInstallationsResponseApi | null
githubAvailableInstallationsResponseLoading: boolean
githubDisconnecting: boolean
githubDiscoveryFailed: boolean
githubDiscoveryGeneration: number
githubDiscoveryProjectId: number | string | null
githubIntegrations: IntegrationType[]
githubPersonalConnected: boolean | null
githubRepositories: Record<number, GitHubRepoApi[]>
githubRepositoriesLoading: boolean
githubRepositoriesTotal: Record<number, number>
githubSuggestionSubscribers: number
integrations: IntegrationType[] | null
integrationsLoading: boolean
linearIntegrations: IntegrationType[]
linkedGithubInstallation: IntegrationConfigApi | null
linkedGithubInstallationLoading: boolean
newIntegrationModalId: string | null
newIntegrationModalKind: IntegrationKind | null
pollingSubscribers: number
providerIntegrations: IntegrationType[] | null
requestedAccessKinds: IntegrationKind[]
selectedIntegration: IntegrationType | null
setupModalOpen: boolean
setupModalType: ChannelType | null
slackAvailable: boolean | undefined
slackIntegrations: IntegrationType[] | undefined
}
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface integrationsLogicActions {
reportIntegrationConnectRejected: (
kind: string,
error: string
) => {
error: string
kind: string
} // eventUsageLogic
reportIntegrationScopeShortfallShown: (
kind: string,
missingScopes: string[]
) => {
kind: string
missingScopes: string[]
} // eventUsageLogic
markTaskAsCompleted: (taskIdOrIds: AvailableSetupTaskIdsEnumApi | AvailableSetupTaskIdsEnumApi[]) => {
taskIdOrIds: AvailableSetupTaskIdsEnumApi | AvailableSetupTaskIdsEnumApi[]
} // globalSetupLogic
loadCurrentTeamSuccess: (
currentTeam: null | import('~/types').TeamPublicType,
payload?: any
) => {
currentTeam: null | import('~/types').TeamPublicType
payload?: any
} // teamLogic
clearIntegrations: () => {
value: true
}
closeNewIntegrationModal: () => {
value: true
}
closeSetupModal: () => {
value: true
}
deleteIntegration: (id: number) => {
id: number
}
handleOauthCallback: (
kind: IntegrationKind,
searchParams: any
) => {
kind:
| 'apns'
| 'apple-ads'
| 'aws-redshift'
| 'aws-s3'
| 'azure-blob'
| 'bing-ads'
| 'clickup'
| 'customerio-app'
| 'customerio-track'
| 'customerio-webhook'
| 'databricks'
| 'email'
| 'firebase'
| 'github'
| 'gitlab'
| 'google-ads'
| 'google-analytics'
| 'google-calendar'
| 'google-cloud-service-account'
| 'google-cloud-storage'
| 'google-pubsub'
| 'google-search-console'
| 'google-sheets'
| 'helpscout'
| 'hubspot'
| 'instagram'
| 'intercom'
| 'jira'
| 'linear'
| 'linkedin-ads'
| 'meta-ads'
| 'pardot'
| 'pinterest-ads'
| 'postgresql'
| 'reddit-ads'
| 's3-compatible'
| 'salesforce'
| 'slack'
| 'snapchat'
| 'snowflake'
| 'stripe'
| 'tiktok-ads'
| 'twilio'
| 'twitter-ads'
| 'vercel'
| 'youtube-analytics'
searchParams: any
}
invalidateGithubSuggestions: () => {
value: true
}
linkExistingGithubInstallation: (installationId: string | undefined) => string | undefined
linkExistingGithubInstallationFailure: (
error: string,
errorObject?: any
) => {
error: string
errorObject?: any
}
linkExistingGithubInstallationSuccess: (
linkedGithubInstallation: IntegrationConfigApi | null,
payload?: string | undefined
) => {
linkedGithubInstallation: IntegrationConfigApi | null
payload?: string | undefined
}
loadGitHubRepositories: (integrationId: number) => {
integrationId: number
}
loadGitHubRepositoriesPage: (
integrationId: number,
offset: number
) => {
integrationId: number
offset: number
}
loadGitHubRepositoriesPageFailure: (integrationId: number) => {
integrationId: number
}
loadGitHubRepositoriesPageSuccess: (
integrationId: number,
repositories: GitHubRepoApi[],
hasMore: boolean,
total?: number | null
) => {
hasMore: boolean
integrationId: number
repositories: GitHubRepoApi[]
total: number | null
}
loadGithubAvailableInstallations: () => {
value: true
}
loadIntegrations: (_?: any) => any
loadIntegrationsFailure: (
error: string,
errorObject?: any
) => {
error: string
errorObject?: any
}
loadIntegrationsSuccess: (
integrations: IntegrationType[],
payload?: any
) => {
integrations: IntegrationType[]
payload?: any
}
newGoogleCloudKey: (
kind: string,
key: File,
callback?: (integration: IntegrationType) => void
) => {
callback: ((integration: IntegrationType) => void) | undefined
key: File
kind: string
}
newGoogleCloudKeyFailure: (
error: string,
errorObject?: any
) => {
error: string
errorObject?: any
}
newGoogleCloudKeySuccess: (
integrations: {
config: any
created_at: string
created_by?: UserBasicType | null | undefined
display_name: string
errors?: string | undefined
files_write_requestable?: boolean | undefined
icon_url: any
id: number
installation_shared?: boolean | null | undefined
installation_status?: InstallationStatusEnumApi | null | undefined
kind:
| 'apns'
| 'apple-ads'
| 'aws-redshift'
| 'aws-s3'
| 'azure-blob'
| 'bing-ads'
| 'clickup'
| 'customerio-app'
| 'customerio-track'
| 'customerio-webhook'
| 'databricks'
| 'email'
| 'firebase'
| 'github'
| 'gitlab'
| 'google-ads'
| 'google-analytics'
| 'google-calendar'
| 'google-cloud-service-account'
| 'google-cloud-storage'
| 'google-pubsub'
| 'google-search-console'
| 'google-sheets'
| 'helpscout'
| 'hubspot'
| 'instagram'
| 'intercom'
| 'jira'
| 'linear'
| 'linkedin-ads'
| 'meta-ads'
| 'pardot'
| 'pinterest-ads'
| 'postgresql'
| 'reddit-ads'
| 's3-compatible'
| 'salesforce'
| 'slack'
| 'snapchat'
| 'snowflake'
| 'stripe'
| 'tiktok-ads'
| 'twilio'
| 'twitter-ads'
| 'vercel'
| 'youtube-analytics'
needs_webhook_reconnect?: boolean | null | undefined
}[],
payload?: {
callback: ((integration: IntegrationType) => void) | undefined
key: File
kind: string
}
) => {
integrations: {
config: any
created_at: string
created_by?: UserBasicType | null | undefined
display_name: string
errors?: string | undefined
files_write_requestable?: boolean | undefined
icon_url: any
id: number
installation_shared?: boolean | null | undefined
installation_status?: InstallationStatusEnumApi | null | undefined
kind:
| 'apns'
| 'apple-ads'
| 'aws-redshift'
| 'aws-s3'
| 'azure-blob'
| 'bing-ads'
| 'clickup'
| 'customerio-app'
| 'customerio-track'
| 'customerio-webhook'
| 'databricks'
| 'email'
| 'firebase'
| 'github'
| 'gitlab'
| 'google-ads'
| 'google-analytics'
| 'google-calendar'
| 'google-cloud-service-account'
| 'google-cloud-storage'
| 'google-pubsub'
| 'google-search-console'
| 'google-sheets'
| 'helpscout'
| 'hubspot'
| 'instagram'
| 'intercom'
| 'jira'
| 'linear'
| 'linkedin-ads'
| 'meta-ads'
| 'pardot'
| 'pinterest-ads'
| 'postgresql'
| 'reddit-ads'
| 's3-compatible'
| 'salesforce'
| 'slack'
| 'snapchat'
| 'snowflake'
| 'stripe'
| 'tiktok-ads'
| 'twilio'
| 'twitter-ads'
| 'vercel'
| 'youtube-analytics'
needs_webhook_reconnect?: boolean | null | undefined
}[]
payload?: {
callback: ((integration: IntegrationType) => void) | undefined
key: File
kind: string
}
}
openNewIntegrationModal: (
kind: IntegrationKind,
id: string
) => {
id: string
kind:
| 'apns'
| 'apple-ads'
| 'aws-redshift'
| 'aws-s3'
| 'azure-blob'
| 'bing-ads'
| 'clickup'
| 'customerio-app'
| 'customerio-track'
| 'customerio-webhook'
| 'databricks'
| 'email'
| 'firebase'
| 'github'
| 'gitlab'
| 'google-ads'
| 'google-analytics'
| 'google-calendar'
| 'google-cloud-service-account'
| 'google-cloud-storage'
| 'google-pubsub'
| 'google-search-console'
| 'google-sheets'
| 'helpscout'
| 'hubspot'
| 'instagram'
| 'intercom'
| 'jira'
| 'linear'
| 'linkedin-ads'
| 'meta-ads'
| 'pardot'
| 'pinterest-ads'
| 'postgresql'
| 'reddit-ads'
| 's3-compatible'
| 'salesforce'
| 'slack'
| 'snapchat'
| 'snowflake'
| 'stripe'
| 'tiktok-ads'
| 'twilio'
| 'twitter-ads'
| 'vercel'
| 'youtube-analytics'
}
openSetupModal: (
integration?: IntegrationType,
channelType?: ChannelType
) => {
channelType: 'apns' | 'email' | 'firebase' | 'slack' | 'twilio' | undefined
integration: IntegrationType | undefined
}
requestIntegrationAccess: ({ kind }: { kind: IntegrationKind }) => {
kind: IntegrationKind
}
requestIntegrationAccessFailure: (
error: string,
errorObject?: any
) => {
error: string
errorObject?: any
}
requestIntegrationAccessSuccess: (
accessRequest:
| 'apns'
| 'apple-ads'
| 'aws-redshift'
| 'aws-s3'
| 'azure-blob'
| 'bing-ads'
| 'clickup'
| 'customerio-app'
| 'customerio-track'
| 'customerio-webhook'
| 'databricks'
| 'email'
| 'firebase'
| 'github'
| 'gitlab'
| 'google-ads'
| 'google-analytics'
| 'google-calendar'
| 'google-cloud-service-account'
| 'google-cloud-storage'
| 'google-pubsub'
| 'google-search-console'
| 'google-sheets'
| 'helpscout'
| 'hubspot'
| 'instagram'
| 'intercom'
| 'jira'
| 'linear'
| 'linkedin-ads'
| 'meta-ads'
| 'pardot'
| 'pinterest-ads'
| 'postgresql'
| 'reddit-ads'
| 's3-compatible'
| 'salesforce'
| 'slack'
| 'snapchat'
| 'snowflake'
| 'stripe'
| 'tiktok-ads'
| 'twilio'
| 'twitter-ads'
| 'vercel'
| 'youtube-analytics',
payload?: {
kind: IntegrationKind
}
) => {
accessRequest:
| 'apns'
| 'apple-ads'
| 'aws-redshift'
| 'aws-s3'
| 'azure-blob'
| 'bing-ads'
| 'clickup'
| 'customerio-app'
| 'customerio-track'
| 'customerio-webhook'
| 'databricks'
| 'email'
| 'firebase'
| 'github'
| 'gitlab'
| 'google-ads'
| 'google-analytics'
| 'google-calendar'
| 'google-cloud-service-account'
| 'google-cloud-storage'
| 'google-pubsub'
| 'google-search-console'
| 'google-sheets'
| 'helpscout'
| 'hubspot'
| 'instagram'
| 'intercom'
| 'jira'
| 'linear'
| 'linkedin-ads'
| 'meta-ads'
| 'pardot'
| 'pinterest-ads'
| 'postgresql'
| 'reddit-ads'
| 's3-compatible'
| 'salesforce'
| 'slack'
| 'snapchat'
| 'snowflake'
| 'stripe'
| 'tiktok-ads'
| 'twilio'
| 'twitter-ads'
| 'vercel'
| 'youtube-analytics'
payload?: {
kind: IntegrationKind
}
}
setAccessRequestReason: (reason: string) => {
reason: string
}
setGithubDisconnecting: (disconnecting: boolean) => {
disconnecting: boolean
}
setGithubDiscovery: (
response: GitHubAvailableInstallationsResponseApi | null,
projectId: number | string,
failed: boolean
) => {
failed: boolean
projectId: number | string
response: GitHubAvailableInstallationsResponseApi | null
}
startPolling: () => {
value: true
}
stopPolling: () => {
value: true
}
subscribeGithubSuggestions: () => {
value: true
}
unsubscribeGithubSuggestions: () => {
value: true
}
}
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface integrationsLogicMeta {
__keaTypeGenInternalSelectorTypes: {
providerIntegrations: (integrations: IntegrationType[] | null) => IntegrationType[] | null
slackIntegrations: (providerIntegrations: IntegrationType[] | null) => IntegrationType[] | undefined
githubIntegrations: (providerIntegrations: IntegrationType[] | null) => IntegrationType[]
linearIntegrations: (providerIntegrations: IntegrationType[] | null) => IntegrationType[]
githubAvailableInstallations: (
githubAvailableInstallationsResponse: GitHubAvailableInstallationsResponseApi | null,
githubDiscoveryProjectId: number | string | null,
currentProjectId: number | string
) => GitHubAvailableInstallationApi[] | null
githubPersonalConnected: (
githubAvailableInstallationsResponse: GitHubAvailableInstallationsResponseApi | null
) => boolean | null
getIntegrationsByKind: (
providerIntegrations: IntegrationType[] | null
) => (
kinds: (
| 'apns'
| 'apple-ads'
| 'aws-redshift'
| 'aws-s3'
| 'azure-blob'
| 'bing-ads'
| 'clickup'
| 'customerio-app'
| 'customerio-track'
| 'customerio-webhook'
| 'databricks'
| 'email'
| 'firebase'
| 'github'
| 'gitlab'
| 'google-ads'
| 'google-analytics'
| 'google-calendar'
| 'google-cloud-service-account'
| 'google-cloud-storage'
| 'google-pubsub'
| 'google-search-console'
| 'google-sheets'
| 'helpscout'
| 'hubspot'
| 'instagram'
| 'intercom'
| 'jira'
| 'linear'
| 'linkedin-ads'
| 'meta-ads'
| 'pardot'
| 'pinterest-ads'
| 'postgresql'
| 'reddit-ads'
| 's3-compatible'
| 'salesforce'
| 'slack'
| 'snapchat'
| 'snowflake'
| 'stripe'
| 'tiktok-ads'
| 'twilio'
| 'twitter-ads'
| 'vercel'
| 'youtube-analytics'
)[]
) => IntegrationType[]
slackAvailable: (preflight: PreflightStatus | null) => boolean | undefined
getGitHubRepositories: (
githubRepositories: Record<number, GitHubRepoApi[]>
) => (integrationId: number) => string[]
getGitHubRepositoriesFull: (
githubRepositories: Record<number, GitHubRepoApi[]>
) => (integrationId: number) => GitHubRepoApi[]
getGitHubRepositoriesTotal: (
githubRepositoriesTotal: Record<number, number>
) => (integrationId: number) => number | null
domainGroupedEmailIntegrations: (integrations: IntegrationType[] | null) => EmailIntegrationDomainGroupedType[]
}
}
export type integrationsLogicType = MakeLogicType<
integrationsLogicValues,
integrationsLogicActions,
Record<string, any>,
integrationsLogicMeta
>
export const integrationsLogic = kea<integrationsLogicType>([
path(['lib', 'integrations', 'integrationsLogic']),
connect(() => ({
values: [
preflightLogic,
['siteUrlMisconfigured', 'preflight'],
teamLogic,
['currentProjectId', 'currentTeamId'],
featureFlagLogic,
['featureFlags'],
],
actions: [
globalSetupLogic,
['markTaskAsCompleted'],
eventUsageLogic,
['reportIntegrationConnectRejected', 'reportIntegrationScopeShortfallShown'],
teamLogic,
['loadCurrentTeamSuccess'],
],
})),
actions({
handleOauthCallback: (kind: IntegrationKind, searchParams: any) => ({ kind, searchParams }),
newGoogleCloudKey: (kind: string, key: File, callback?: (integration: IntegrationType) => void) => ({
kind,
key,
callback,
}),
deleteIntegration: (id: number) => ({ id }),
invalidateGithubSuggestions: true,
setGithubDisconnecting: (disconnecting: boolean) => ({ disconnecting }),
loadGithubAvailableInstallations: true,
setGithubDiscovery: (
response: GitHubAvailableInstallationsResponseApi | null,
projectId: number | string,
failed: boolean
) => ({ response, projectId, failed }),
openNewIntegrationModal: (kind: IntegrationKind, id: string) => ({ kind, id }),
closeNewIntegrationModal: true,
openSetupModal: (integration?: IntegrationType, channelType?: ChannelType) => ({ integration, channelType }),
closeSetupModal: true,
loadGitHubRepositories: (integrationId: number) => ({ integrationId }),
loadGitHubRepositoriesPage: (integrationId: number, offset: number) => ({ integrationId, offset }),
loadGitHubRepositoriesPageSuccess: (
integrationId: number,
repositories: GitHubRepoApi[],
hasMore: boolean,
total: number | null = null
) => ({
integrationId,
repositories,
hasMore,
total,
}),
loadGitHubRepositoriesPageFailure: (integrationId: number) => ({ integrationId }),
setAccessRequestReason: (reason: string) => ({ reason }),
startPolling: true,
stopPolling: true,
subscribeGithubSuggestions: true,
unsubscribeGithubSuggestions: true,
clearIntegrations: true,
}),
reducers({
integrations: [null as IntegrationType[] | null, { clearIntegrations: () => null }],
githubDisconnecting: [false, { setGithubDisconnecting: (_, { disconnecting }) => disconnecting }],
githubDiscoveryGeneration: [
0,
{
invalidateGithubSuggestions: (state) => state + 1,
loadGithubAvailableInstallations: (state) => state + 1,
},
],
githubDiscoveryProjectId: [
null as number | string | null,
{ setGithubDiscovery: (_, { projectId }) => projectId },
],
githubAvailableInstallationsResponse: [
null as GitHubAvailableInstallationsResponseApi | null,
{
invalidateGithubSuggestions: () => null,
setGithubDiscovery: (_, { response }) => response,
},
],
githubAvailableInstallationsResponseLoading: [
false,
{
invalidateGithubSuggestions: () => true,
loadGithubAvailableInstallations: () => true,
setGithubDiscovery: () => false,
},
],
githubDiscoveryFailed: [
false,
{
loadGithubAvailableInstallations: () => false,
invalidateGithubSuggestions: () => false,
setGithubDiscovery: (_, { failed }) => failed,
},
],
newIntegrationModalId: [
null as string | null,
{
openNewIntegrationModal: (_, { id }: { id: string }) => id,
closeNewIntegrationModal: () => null,
},
],
newIntegrationModalKind: [
null as IntegrationKind | null,
{
openNewIntegrationModal: (_, { kind }: { kind: IntegrationKind }) => kind,
closeNewIntegrationModal: () => null,
},
],
setupModalOpen: [
false,
{
openSetupModal: () => true,
closeSetupModal: () => false,
},
],
setupModalType: [
null as ChannelType | null,
{
openSetupModal: (_, { channelType }) => channelType ?? null,
closeSetupModal: () => null,
},
],
selectedIntegration: [
null as IntegrationType | null,
{
openSetupModal: (_, { integration }) => integration ?? null,
closeSetupModal: () => null,
},
],
githubRepositories: [
{} as Record<number, GitHubRepoApi[]>,
{
loadGitHubRepositories: (state, { integrationId }) => ({
...state,
[integrationId]: [],
}),
loadGitHubRepositoriesPageSuccess: (state, { integrationId, repositories }) => {
const existing = state[integrationId] || []
const seenIds = new Set(existing.map((r) => r.id))
const newRepos = repositories.filter((r) => !seenIds.has(r.id))
return { ...state, [integrationId]: [...existing, ...newRepos] }
},
},
],
githubRepositoriesLoading: [
false,
{
loadGitHubRepositories: () => true,
loadGitHubRepositoriesPageSuccess: (_, { hasMore }) => hasMore,
loadGitHubRepositoriesPageFailure: () => false,
},
],
githubRepositoriesTotal: [
{} as Record<number, number>,
{
// Clear the cached total when a reload starts so a scope change can't briefly (or, on a
// slow/failed refetch, indefinitely) show the previous selection's count.
loadGitHubRepositories: (state, { integrationId }) => {
if (!(integrationId in state)) {
return state
}
const next = { ...state }
delete next[integrationId]
return next
},
loadGitHubRepositoriesPageSuccess: (state, { integrationId, total }) =>
total == null ? state : { ...state, [integrationId]: total },
},
],
pollingSubscribers: [
0,
{
startPolling: (state) => state + 1,
stopPolling: (state) => Math.max(0, state - 1),
},
],
githubSuggestionSubscribers: [
0,
{
subscribeGithubSuggestions: (state) => state + 1,
unsubscribeGithubSuggestions: (state) => Math.max(0, state - 1),
},
],
requestedAccessKinds: [
[] as IntegrationKind[],
{
requestIntegrationAccessSuccess: (state, { accessRequest }) =>
accessRequest && !state.includes(accessRequest) ? [...state, accessRequest] : state,
},
],
accessRequestReason: [
'',
{
setAccessRequestReason: (_, { reason }) => reason,
requestIntegrationAccessSuccess: () => '',
},
],
}),
loaders(({ actions, values, cache }) => ({
integrations: [
null as IntegrationType[] | null,
{
loadIntegrations: async (_ = undefined, breakpoint) => {
const projectId = values.currentProjectId
const integrations: IntegrationType[] = []
let offset = 0
let hasNext = true
while (hasNext) {
const res = await integrationsList(String(projectId), { limit: 100, offset })
await breakpoint()
for (const integration of res.results) {
// The API serves kinds this union does not name yet, and consumers such as
// PosthogConnect read them, so every result is kept and only the icon is optional.
const kind = integration.kind as IntegrationKind
integrations.push({
...integration,
kind,
config: integration.config ?? {},
created_by: integration.created_by
? {
id: integration.created_by.id,
uuid: integration.created_by.uuid,
distinct_id: integration.created_by.distinct_id ?? '',
first_name: integration.created_by.first_name ?? '',
last_name: integration.created_by.last_name,
email: integration.created_by.email,
is_email_verified: integration.created_by.is_email_verified,
role_at_organization: integration.created_by.role_at_organization,
}
: integration.created_by,
// TODO: Make the icons endpoint independent of hog functions
icon_url: ICONS[kind],
})
}
offset += res.results.length
hasNext = !!res.next && res.results.length > 0
}
return integrations
},
newGoogleCloudKey: async ({ kind, key, callback }) => {
try {
const formData = new FormData()
formData.append('kind', kind)
formData.append('key', key)
const response = await api.integrations.create(formData)
const responseWithIcon = {
...response,
icon_url: isKeyOf(kind, ICONS) ? ICONS[kind] : ICONS['google-pubsub'],
}
// run onChange after updating the integrations loader
window.setTimeout(() => callback?.(responseWithIcon), 0)
if (
values.integrations?.find(
(x) => x.kind === kind && x.display_name === response.display_name
)
) {
lemonToast.success('Google Cloud key updated.')
return values.integrations.map((x) =>
x.kind === kind && x.display_name === response.display_name ? responseWithIcon : x
)
}
lemonToast.success('Google Cloud key created.')
return [...(values.integrations ?? []), responseWithIcon]
} catch (e) {
lemonToast.error('Failed to upload Google Cloud key.')
throw e
}
},
},
],
linkedGithubInstallation: [
null as IntegrationConfigApi | null,
{
// Reuse a GitHub App installation already connected to another project in the same
// org. A GitHub App installs once per org, so a second project can't reinstall; this
// links the existing install without the fragile GitHub setup redirect roundtrip.
// When the org has more than one installation the caller passes the chosen
// installationId, since the backend can't auto-resolve between them.
linkExistingGithubInstallation: async (installationId: string | undefined, breakpoint) => {
// The global kea-loaders failure handler shows the API detail. Do not add a
// local toast here because the rejected loader would then show both messages.
const projectGeneration = cache.githubProjectGeneration
const discoveryId = values.githubAvailableInstallationsResponse?.discovery_id
const projectId = values.currentProjectId
actions.invalidateGithubSuggestions()
let integration
try {
integration = await integrationsGithubLinkExistingCreate(String(projectId), {
installation_id: installationId,
discovery_id: discoveryId,
})
} catch (error) {
await breakpoint()
if (
values.currentProjectId !== projectId ||
cache.githubProjectGeneration !== projectGeneration
) {
return values.linkedGithubInstallation
}
throw error
} finally {
if (
values.currentProjectId === projectId &&
cache.githubProjectGeneration === projectGeneration
) {
actions.loadGithubAvailableInstallations()
}
}
await breakpoint()
if (values.currentProjectId !== projectId || cache.githubProjectGeneration !== projectGeneration) {
return values.linkedGithubInstallation
}
lemonToast.success('Linked the existing GitHub installation to this project.')
actions.loadIntegrations()
return integration
},
},
],
accessRequest: [
null as IntegrationKind | null,
{
requestIntegrationAccess: async ({ kind }: { kind: IntegrationKind }) => {
try {
await integrationsRequestAccessCreate(String(values.currentProjectId), {
kind: kind as IntegrationKindEnumApi,
reason: values.accessRequestReason.trim(),
})
lemonToast.success('Request sent! Your project admins have been notified.')
return kind
} catch (e) {
toastApiError(e)
throw e
}
},
},
],
})),
listeners(({ actions, values, cache }) => ({
loadCurrentTeamSuccess: () => {
if (cache.githubProjectId === values.currentProjectId) {
return
}
cache.githubProjectId = values.currentProjectId
cache.githubProjectGeneration = (cache.githubProjectGeneration ?? 0) + 1
actions.linkExistingGithubInstallationSuccess(null)
cache.githubConnectionFingerprint = undefined
// Clear only on a project switch: same-project team refreshes keep the connected integrations.
actions.clearIntegrations()
actions.invalidateGithubSuggestions()
actions.loadIntegrations()
if (values.githubSuggestionSubscribers > 0) {
actions.loadGithubAvailableInstallations()
}
},
loadGithubAvailableInstallations: async () => {
if (values.githubDisconnecting) {
return
}
const projectId = values.currentProjectId
const generation = values.githubDiscoveryGeneration
try {
const response = await integrationsGithubAvailableInstallationsRetrieve(String(projectId))
if (projectId === values.currentProjectId && generation === values.githubDiscoveryGeneration) {
actions.setGithubDiscovery(response, projectId, false)
}
} catch {
if (projectId === values.currentProjectId && generation === values.githubDiscoveryGeneration) {
actions.setGithubDiscovery(null, projectId, true)
}
}
},
loadIntegrationsSuccess: ({ integrations }) => {
const fingerprint = JSON.stringify(
integrations
?.filter((row) => row.kind === 'github')
.map((row) => [row.id, row.config?.installation_id, row.config?.account, row.installation_status])
)
if (
cache.githubConnectionFingerprint !== undefined &&
cache.githubConnectionFingerprint !== fingerprint &&
values.githubSuggestionSubscribers > 0
) {
actions.loadGithubAvailableInstallations()
}
cache.githubConnectionFingerprint = fingerprint
},
loadGitHubRepositories: ({ integrationId }) => {
actions.loadGitHubRepositoriesPage(integrationId, 0)
},
loadGitHubRepositoriesPageSuccess: ({ integrationId, hasMore }) => {
if (hasMore) {
const currentRepos = values.githubRepositories[integrationId] || []
actions.loadGitHubRepositoriesPage(integrationId, currentRepos.length)
}
},
loadGitHubRepositoriesPage: async ({ integrationId, offset }, breakpoint) => {
try {
const response = await integrationsGithubReposRetrieve(String(values.currentProjectId), integrationId, {
limit: 100,
offset,
})
await breakpoint()
// An "all repositories" installation is summarized by its total, so one page is enough.
const integration = values.integrations?.find((x) => x.id === integrationId)
const summarizedByTotal = integration?.config?.repository_selection === 'all'
actions.loadGitHubRepositoriesPageSuccess(
integrationId,
response.repositories,
summarizedByTotal ? false : response.has_more,
response.total ?? null
)
} catch {
actions.loadGitHubRepositoriesPageFailure(integrationId)
}
},
startPolling: () => {
if (cache.disposables.registry.has('poll')) {
return
}
cache.disposables.add(() => {
const pollTimer = window.setInterval(() => actions.loadIntegrations(), INTEGRATIONS_POLL_INTERVAL_MS)
return () => clearInterval(pollTimer)
}, 'poll')
cache.disposables.add(
() => {
const onFocus = (): void => {
actions.loadIntegrations()
if (values.githubSuggestionSubscribers > 0) {
actions.loadGithubAvailableInstallations()
}
}
window.addEventListener('focus', onFocus)
return () => window.removeEventListener('focus', onFocus)
},
'focusRefetch',
{ pauseOnPageHidden: false }
)
},
subscribeGithubSuggestions: () => {
if (values.githubSuggestionSubscribers === 1) {
actions.loadGithubAvailableInstallations()
}
},
stopPolling: () => {
if (values.pollingSubscribers > 0) {
return
}
cache.disposables.dispose('poll')
cache.disposables.dispose('focusRefetch')
},
handleOauthCallback: async ({ kind, searchParams }) => {
if (kind === 'twitter-ads') {
// The server binds the temporary token to the initiating user and project instead of a state cookie.
let replaceUrl = urls.settings('project-integrations')
try {
if (searchParams.denied) {
lemonToast.info('X Ads connection cancelled.')
} else {
const parsedTeamId = Number(getCookie('ph_twitter_ads_team_id'))
const projectId =
Number.isFinite(parsedTeamId) && parsedTeamId > 0
? String(parsedTeamId)
: String(values.currentProjectId)
const integration = await integrationsCreate(projectId, {
kind,
config: {
oauth_token: searchParams.oauth_token,
oauth_verifier: searchParams.oauth_verifier,
},
})
const nextUrl =
typeof integration.config === 'object' &&
integration.config !== null &&
'next' in integration.config &&
typeof integration.config.next === 'string'
? integration.config.next
: replaceUrl
const url = new URL(nextUrl, window.location.origin)
url.searchParams.set(OAUTH_INTEGRATION_ID_PARAM, String(integration.id))
replaceUrl = url.pathname + url.search + url.hash
actions.loadIntegrations()
lemonToast.success('Integration successful.')
}
} catch (e) {
toastApiError(e)
} finally {
router.actions.replace(replaceUrl)
}
return
}
const { code, error, stripe_user_id, account_id, user_id } = searchParams
const state = decodeOpaqueOAuthState(searchParams.state)
const { next, token, source, server_id, team_id } = fromParamsGivenUrl(state ?? '')
const resolvedKind = kind
let replaceUrl: string = next || urls.settings('project-integrations')
if (error) {
actions.reportIntegrationConnectRejected(resolvedKind, String(error))
const url = new URL(replaceUrl, window.location.origin)
if (landsOnErrorAwarePage(url.pathname)) {
url.searchParams.set(INTEGRATION_ERROR_PARAM, String(error))
replaceUrl = url.pathname + url.search + url.hash
} else {
lemonToast.error(describeOAuthCallbackError(String(error), resolvedKind))
}
router.actions.replace(replaceUrl)
return
}
// Stripe marketplace installs redirect here without a PostHog-minted state, so we
// can't verify the callback against a CSRF cookie. Without that, an attacker could
// capture their own Connect-OAuth callback URL and trick a logged-in PostHog admin
// into visiting it, silently linking the attacker's Stripe account to the victim's
// team. Redirect to a confirmation page that shows the user the Stripe account
// they're about to link, and only POST to /integrations/ on explicit confirm.
// resolvedKind is typed as IntegrationKind which doesn't list 'stripe' in the enum,
// but the URL route (`/integrations/:kind/callback`) passes it through verbatim.
const isStripeMarketplaceInstall =
(resolvedKind as string) === 'stripe' && !state && !!stripe_user_id && !!code
if (isStripeMarketplaceInstall) {
const params = new URLSearchParams({
code: String(code),
stripe_user_id: String(stripe_user_id),
})
if (account_id) {
params.set('account_id', String(account_id))
}
if (user_id) {
params.set('user_id', String(user_id))
}
router.actions.replace(`${urls.stripeConfirmInstall()}?${params.toString()}`)
return
}
// The CSRF state cookie only lives for a few minutes (see ph_oauth_state max_age). If the
// authorization round-trip outlived it, or the browser dropped the cookie, the token won't
// match. That's recoverable by simply retrying, so say so instead of surfacing the generic
// "Something went wrong" that a thrown error would fall back to.
if (token !== getCookie('ph_oauth_state')) {
const url = new URL(replaceUrl, window.location.origin)
if (landsOnErrorAwarePage(url.pathname)) {
url.searchParams.set(INTEGRATION_ERROR_PARAM, OAUTH_STATE_EXPIRED)
router.actions.replace(url.pathname + url.search + url.hash)
} else {
lemonToast.error(describeOAuthCallbackError(OAUTH_STATE_EXPIRED, resolvedKind))
router.actions.replace(replaceUrl)
}
return
}
try {
if (source === 'mcp_store') {
replaceUrl += `${replaceUrl.includes('?') ? '&' : '?'}code=${encodeURIComponent(code)}&server_id=${encodeURIComponent(server_id)}&state_token=${encodeURIComponent(token)}`
lemonToast.success('Authorization successful.')
} else {
// The callback URL is not project-scoped, so after this full-page round-trip
// the SPA may have re-resolved to the user's default team. Target the team
// that started the flow (carried through the OAuth state) so the integration
// lands on the project the user actually chose.
const parsedTeamId = Number(team_id)
const initiatingTeamId = Number.isFinite(parsedTeamId) ? parsedTeamId : undefined
const integration = await api.integrations.create(
{
kind: resolvedKind,
config: { state, code },
},
initiatingTeamId
)
// Add the integration ID to the replaceUrl so that the landing page can use it
const url = new URL(replaceUrl, window.location.origin)
url.searchParams.set(OAUTH_INTEGRATION_ID_PARAM, String(integration.id))
replaceUrl = url.pathname + url.search + url.hash
actions.loadIntegrations()
const missingScopes = getMissingScopes(
integration,
requestedScopesForKind(integration.kind, values.preflight)
)
if (missingScopes.length > 0) {
actions.reportIntegrationScopeShortfallShown(integration.kind, missingScopes)
lemonToast.warning(describeScopeShortfall(integration.kind, missingScopes), {
autoClose: false,
})
} else {
lemonToast.success(`Integration successful.`)
}
offerSlackSetupAfterConnect(integration, url.pathname, {
currentTeamId: values.currentTeamId,
initiatingTeamId,
setupEnabled: !!values.featureFlags[FEATURE_FLAGS.SLACK_APP_WORKSPACE_SETUP],
})
}
} catch (e) {
toastApiError(e)
} finally {
router.actions.replace(replaceUrl)
}
},
deleteIntegration: async ({ id }) => {
const integration = values.integrations?.find((x) => x.id === id)
if (!integration) {
return
}
const integrationName = getIntegrationNameFromKind(integration.kind)
LemonDialog.open({
title: `Disconnect ${integrationName}?`,
description:
integration.kind === 'github'
? buildGithubDisconnectDescription(
integration.config?.account?.name || integrationName,
!!integration.installation_shared
)
: 'This cannot be undone. PostHog resources configured to use this integration will remain but will stop working.',
primaryButton: {
children: 'Disconnect',
status: 'danger',
onClick: async () => {
if (integration.kind === 'github') {
actions.setGithubDisconnecting(true)
actions.invalidateGithubSuggestions()
}
try {
await api.integrations.delete(id)
actions.loadIntegrations()
} catch (e) {
if (e instanceof ApiError && e.status === 404) {
lemonToast.info('Already disconnected.')
actions.loadIntegrations()
} else {
toastApiError(e)
}
} finally {
if (integration.kind === 'github') {
actions.setGithubDisconnecting(false)
actions.loadGithubAvailableInstallations()
}
}
},
},
secondaryButton: {
children: 'Cancel',
},
})
},
})),
afterMount(({ actions, values, cache }) => {
cache.githubProjectId = values.currentProjectId
actions.loadIntegrations()
const params = new URLSearchParams(window.location.search)
if (params.has('github_setup_error')) {
const reason = params.get('github_setup_error')
const detail = params.get('error_message')
lemonToast.error(describeGithubSetupError(reason, detail))
} else if (params.has('github_install_pending')) {
lemonToast.info(GITHUB_INSTALL_PENDING_MESSAGE)
}
}),
urlToAction(({ actions }) => ({
'/integrations/:kind/callback': ({ kind = '' }, searchParams) => {
actions.handleOauthCallback(kind as IntegrationKind, searchParams)
},
})),
selectors({
// The list also has the rows where data warehouse sources keep their typed-in credentials. Such a
// row has a provider kind (`github`, `slack`), but it is not a connection of that provider. Code
// that picks a connection by its kind reads this list.
providerIntegrations: [
(s) => [s.integrations],
(integrations: IntegrationType[] | null): IntegrationType[] | null =>
integrations?.filter((integration) => !integration.config?.warehouse_source_type) ?? null,
],
slackIntegrations: [
(s) => [s.providerIntegrations],
(providerIntegrations: IntegrationType[] | null) => {
return providerIntegrations?.filter((x) => x.kind == 'slack')
},
],
githubIntegrations: [
(s) => [s.providerIntegrations],
(providerIntegrations: IntegrationType[] | null): IntegrationType[] => {
return providerIntegrations?.filter((x) => x.kind === 'github') ?? []
},
],
linearIntegrations: [
(s) => [s.providerIntegrations],
(providerIntegrations: IntegrationType[] | null): IntegrationType[] => {
return providerIntegrations?.filter((x) => x.kind === 'linear') ?? []
},
],
githubAvailableInstallations: [
(s) => [s.githubAvailableInstallationsResponse, s.githubDiscoveryProjectId, s.currentProjectId],
(
response: GitHubAvailableInstallationsResponseApi | null,
projectId: number | string | null,
currentProjectId: number | string
): GitHubAvailableInstallationApi[] | null => {
return projectId === currentProjectId ? (response?.installations ?? null) : null
},
],
githubPersonalConnected: [
(s) => [s.githubAvailableInstallationsResponse],
(response: GitHubAvailableInstallationsResponseApi | null): boolean | null => {
return response ? response.personal_github_connected : null
},
],
getIntegrationsByKind: [
(s) => [s.providerIntegrations],
(providerIntegrations: IntegrationType[] | null) => {
return (kinds: IntegrationKind[]) => providerIntegrations?.filter((i) => kinds.includes(i.kind)) || []
},
],
slackAvailable: [
(s) => [s.preflight],
(preflight: null | import('~/types').PreflightStatus) => {
// TODO: Change this to be based on preflight or something
return preflight?.slack_service?.available
},
],
getGitHubRepositories: [
(s) => [s.githubRepositories],
(githubRepositories: Record<number, GitHubRepoApi[]>) => {
return (integrationId: number) => (githubRepositories[integrationId] || []).map((r) => r.name)
},
],
getGitHubRepositoriesFull: [
(s) => [s.githubRepositories],
(githubRepositories: Record<number, GitHubRepoApi[]>) => {
return (integrationId: number): GitHubRepoApi[] => githubRepositories[integrationId] || []
},
],
getGitHubRepositoriesTotal: [
(s) => [s.githubRepositoriesTotal],
(githubRepositoriesTotal: Record<number, number>) => {
return (integrationId: number): number | null => githubRepositoriesTotal[integrationId] ?? null
},
],
domainGroupedEmailIntegrations: [
(s) => [s.integrations],
(integrations: IntegrationType[] | null): EmailIntegrationDomainGroupedType[] => {
const domainGroupedIntegrations: Record<string, EmailIntegrationDomainGroupedType> = {}
integrations
?.filter((x) => x.kind === 'email')
.forEach((integration) => {
const domain = integration.config.domain
if (!domainGroupedIntegrations[domain]) {
domainGroupedIntegrations[domain] = {
domain,
integrations: [],
}
}
domainGroupedIntegrations[domain].integrations.push(integration)
})
return Object.values(domainGroupedIntegrations)
},
],
}),
])