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.

22.3 KB
Raw Blame
import { isFreeEmail } from 'bloommx'
import { MakeLogicType, actions, afterMount, connect, kea, listeners, path, reducers, selectors } from 'kea'
import { forms } from 'kea-forms'
import type { DeepPartial, DeepPartialMap, FieldName, ValidationErrorType } from 'kea-forms'
import { loaders } from 'kea-loaders'

import { LemonDialog } from '@posthog/lemon-ui'

import { SetupTaskId } from 'lib/components/ProductSetup'
import { globalSetupLogic } from 'lib/components/ProductSetup/globalSetupLogic'
import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'
import { apiHostOrigin } from 'lib/utils/apiHost'
import { isDomain } from 'lib/utils/url'
import { organizationLogic } from 'scenes/organizationLogic'
import { userLogic } from 'scenes/userLogic'

import { UserType } from '~/types'

import {
    proxyRecordsCreate,
    proxyRecordsDestroy,
    proxyRecordsDiagnoseCreate,
    proxyRecordsList,
    proxyRecordsPartialUpdate,
    proxyRecordsRetryCreate,
} from 'products/platform_features/frontend/generated/api'
import type {
    DiagnosticCheckResultApi,
    DiagnosticCheckResultStatusEnumApi,
    DiagnosticReportApi,
    DiagnosticReportSummaryStatusEnumApi,
    DiagnosticRemediationApi,
    DiagnosticRemediationTypeEnumApi,
    ProxyRecordApi,
    ProxyRecordListResponseApi,
    ProxyRecordStatusEnumApi,
} from 'products/platform_features/frontend/generated/api.schemas'

export type ProxyRecord = ProxyRecordApi

export type FormState = 'collapsed' | 'active'

export type DiagnosticCheckStatus = DiagnosticCheckResultStatusEnumApi
export type DiagnosticSummaryStatus = DiagnosticReportSummaryStatusEnumApi
export type DiagnosticRemediationType = DiagnosticRemediationTypeEnumApi
export type DiagnosticRemediation = DiagnosticRemediationApi
export type DiagnosticCheckResult = DiagnosticCheckResultApi
export type DiagnosticReport = DiagnosticReportApi

export function canConfigureRootRedirect(proxyRecord: ProxyRecord): boolean {
    return proxyRecord.root_redirect_supported && (proxyRecord.status === 'valid' || proxyRecord.status === 'warning')
}

export function domainFor(proxyRecord: ProxyRecord | undefined): string {
    if (!proxyRecord) {
        return apiHostOrigin()
    }

    let domain = proxyRecord.domain
    if (!domain.startsWith('https://')) {
        domain = `https://${domain}`
    }

    return domain
}

const RISKY_DOMAIN_PATTERNS = /\bph\.|posthog|analytics|tracking|tracker|pixel|telemetry|measure|collect|beacon/i

function isRiskyDomain(domain: string): boolean {
    return RISKY_DOMAIN_PATTERNS.test(domain)
}

const AVAILABLE_SUGGESTIONS_SUBDOMAIN = ['b', 'd', 'f', 'g', 'j', 'k', 'm', 'n', 'p', 'r', 's', 't', 'v', 'z']

// Suggesting a domain based on the user's email domain, but only if it's not a free email provider (e.g. Gmail, Outlook, etc.)
// since this only makes sense for users with a custom email domain who likely also have a custom domain they can use for the proxy
function initialDomainFor(user: UserType | null): string {
    if (!user?.email) {
        return ''
    }

    const isFree = isFreeEmail(user.email)
    if (isFree) {
        return ''
    }

    const lastIndex = user.email.lastIndexOf('@')
    if (lastIndex === -1 || lastIndex === user.email.length - 1) {
        return ''
    }

    const domain = user.email.substring(lastIndex + 1, user.email.length)
    const subdomain =
        AVAILABLE_SUGGESTIONS_SUBDOMAIN[Math.floor(Math.random() * AVAILABLE_SUGGESTIONS_SUBDOMAIN.length)]
    return `${subdomain}.${domain}`
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface proxyLogicValues {
    currentOrganizationId: string // organizationLogic
    user: UserType | null // userLogic
    cloudflareOptInAcknowledged: boolean
    cloudflareOptInChecked: boolean
    createRecord: {
        domain: string
    }
    createRecordAllErrors: Record<string, any>
    createRecordChanged: boolean
    createRecordErrors: DeepPartialMap<
        {
            domain: string
        },
        ValidationErrorType
    >
    createRecordHasErrors: boolean
    createRecordManualErrors: Record<string, any>
    createRecordTouched: boolean
    createRecordTouches: Record<string, boolean>
    createRecordValidationErrors: DeepPartialMap<
        {
            domain: string
        },
        ValidationErrorType
    >
    diagnoseLoadingIds: string[]
    diagnosticReports: Record<string, DiagnosticReport>
    expandedRecordIds: string[]
    formState: FormState
    isCreateRecordSubmitting: boolean
    isCreateRecordValid: boolean
    maxProxyRecords: number
    proxyRecords: ProxyRecord[]
    proxyRecordsLoaded: boolean
    proxyRecordsLoading: boolean
    recordActiveTabs: Record<string, string>
    rootRedirectDrafts: Record<string, string>
    shouldRefreshRecords: boolean
    shouldShowCloudflareOptIn: boolean
    showCreateRecordErrors: boolean
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface proxyLogicActions {
    acknowledgeCloudflareOptIn: () => {
        value: true
    }
    clearDiagnosticReport: (id: ProxyRecord['id']) => {
        id: string
    }
    collapseForm: () => {
        value: true
    }
    createRecord: ({ domain }: { domain: string }) => {
        domain: string
    }
    createRecordFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    createRecordSuccess: (
        proxyRecords: ProxyRecordApi[],
        payload?: {
            domain: string
        }
    ) => {
        proxyRecords: ProxyRecordApi[]
        payload?: {
            domain: string
        }
    }
    deleteRecord: (id: ProxyRecord['id']) => ProxyRecord[]
    deleteRecordFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    deleteRecordSuccess: (
        proxyRecords: {
            created_at: string
            created_by: number
            domain: string
            id: string
            message: string | null
            root_redirect_supported: boolean
            root_redirect_url: string | null
            status: ProxyRecordStatusEnumApi
            target_cname: string
            updated_at: string
        }[],
        payload?: ProxyRecord[]
    ) => {
        proxyRecords: {
            created_at: string
            created_by: number
            domain: string
            id: string
            message: string | null
            root_redirect_supported: boolean
            root_redirect_url: string | null
            status: ProxyRecordStatusEnumApi
            target_cname: string
            updated_at: string
        }[]
        payload?: ProxyRecord[]
    }
    diagnose: (id: ProxyRecord['id']) => {
        id: string
    }
    diagnoseFailure: (
        id: ProxyRecord['id'],
        error: string
    ) => {
        error: string
        id: string
    }
    diagnoseSuccess: (
        id: ProxyRecord['id'],
        report: DiagnosticReport
    ) => {
        id: string
        report: DiagnosticReportApi
    }
    loadRecords: () => any
    loadRecordsFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    loadRecordsSuccess: (
        proxyRecords: ProxyRecordApi[],
        payload?: any
    ) => {
        proxyRecords: ProxyRecordApi[]
        payload?: any
    }
    maybeRefreshRecords: () => {
        value: true
    }
    resetCreateRecord: (values?: { domain: string }) => {
        values?: {
            domain: string
        }
    }
    retryRecord: (id: ProxyRecord['id']) => ProxyRecord[]
    retryRecordFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    retryRecordSuccess: (
        proxyRecords: ProxyRecordApi[],
        payload?: ProxyRecord[]
    ) => {
        proxyRecords: ProxyRecordApi[]
        payload?: ProxyRecord[]
    }
    setCloudflareOptInChecked: (checked: boolean) => {
        checked: boolean
    }
    setCreateRecordManualErrors: (errors: Record<string, any>) => {
        errors: Record<string, any>
    }
    setCreateRecordValue: (
        key: FieldName,
        value: any
    ) => {
        name: FieldName
        value: any
    }
    setCreateRecordValues: (
        values: DeepPartial<{
            domain: string
        }>
    ) => {
        values: DeepPartial<{
            domain: string
        }>
    }
    setMaxProxyRecords: (maxProxyRecords: number) => {
        maxProxyRecords: number
    }
    setRecordActiveTab: (
        id: ProxyRecord['id'],
        tab: string
    ) => {
        id: string
        tab: string
    }
    setRecordExpanded: (
        id: ProxyRecord['id'],
        expanded: boolean
    ) => {
        expanded: boolean
        id: string
    }
    setRootRedirectDraft: (
        id: ProxyRecord['id'],
        rootRedirectUrl: string
    ) => {
        id: string
        rootRedirectUrl: string
    }
    showForm: () => {
        value: true
    }
    submitCreateRecord: () => {
        value: boolean
    }
    submitCreateRecordFailure: (
        error: Error,
        errors: Record<string, any>
    ) => {
        error: Error
        errors: Record<string, any>
    }
    submitCreateRecordRequest: (createRecord: { domain: string }) => {
        createRecord: {
            domain: string
        }
    }
    submitCreateRecordSuccess: (createRecord: { domain: string }) => {
        createRecord: {
            domain: string
        }
    }
    touchCreateRecordField: (key: string) => {
        key: string
    }
    updateRootRedirect: ({ id, rootRedirectUrl }: { id: string; rootRedirectUrl: string }) => {
        id: string
        rootRedirectUrl: string
    }
    updateRootRedirectFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    updateRootRedirectSuccess: (
        proxyRecords: ProxyRecordApi[],
        payload?: {
            id: string
            rootRedirectUrl: string
        }
    ) => {
        proxyRecords: ProxyRecordApi[]
        payload?: {
            id: string
            rootRedirectUrl: string
        }
    }
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface proxyLogicMeta {
    __keaTypeGenInternalSelectorTypes: {
        shouldRefreshRecords: (proxyRecords: ProxyRecordApi[]) => boolean
        shouldShowCloudflareOptIn: (
            cloudflareOptInAcknowledged: boolean,
            proxyRecordsLoaded: boolean,
            proxyRecords: ProxyRecordApi[],
            user: UserType | null
        ) => boolean
    }
}

export type proxyLogicType = MakeLogicType<proxyLogicValues, proxyLogicActions, Record<string, any>, proxyLogicMeta>

export const proxyLogic = kea<proxyLogicType>([
    path(['scenes', 'project', 'Settings', 'proxyLogic']),
    connect(() => ({
        values: [organizationLogic, ['currentOrganizationId'], userLogic, ['user']],
    })),
    actions(() => ({
        collapseForm: true,
        showForm: true,
        maybeRefreshRecords: true,
        acknowledgeCloudflareOptIn: true,
        setCloudflareOptInChecked: (checked: boolean) => ({ checked }),
        setMaxProxyRecords: (maxProxyRecords: number) => ({ maxProxyRecords }),
        diagnose: (id: ProxyRecord['id']) => ({ id }),
        diagnoseSuccess: (id: ProxyRecord['id'], report: DiagnosticReport) => ({ id, report }),
        diagnoseFailure: (id: ProxyRecord['id'], error: string) => ({ id, error }),
        clearDiagnosticReport: (id: ProxyRecord['id']) => ({ id }),
        setRecordExpanded: (id: ProxyRecord['id'], expanded: boolean) => ({ id, expanded }),
        setRecordActiveTab: (id: ProxyRecord['id'], tab: string) => ({ id, tab }),
        setRootRedirectDraft: (id: ProxyRecord['id'], rootRedirectUrl: string) => ({ id, rootRedirectUrl }),
    })),
    reducers(() => ({
        formState: ['collapsed' as FormState, { showForm: () => 'active', collapseForm: () => 'collapsed' }],
        cloudflareOptInAcknowledged: [
            false,
            { persist: true },
            {
                acknowledgeCloudflareOptIn: () => true,
                // Existing proxy records imply the org already consented previously — persist that so the
                // banner doesn't flash on browsers where localStorage was cleared after records were created.
                loadRecordsSuccess: (state, { proxyRecords }) => state || proxyRecords.length > 0,
            },
        ],
        proxyRecordsLoaded: [
            false,
            {
                loadRecordsSuccess: () => true,
                loadRecordsFailure: () => true,
            },
        ],
        cloudflareOptInChecked: [
            false,
            {
                setCloudflareOptInChecked: (_, { checked }) => checked,
                acknowledgeCloudflareOptIn: () => false, // Reset when acknowledged
            },
        ],
        maxProxyRecords: [
            2 as number, // default matching backend DEFAULT_MAX_PROXY_RECORDS
            {
                setMaxProxyRecords: (_, { maxProxyRecords }) => maxProxyRecords,
            },
        ],
        diagnosticReports: [
            {} as Record<string, DiagnosticReport>,
            {
                diagnoseSuccess: (state, { id, report }) => ({ ...state, [id]: report }),
                clearDiagnosticReport: (state, { id }) => {
                    const { [id]: _removed, ...rest } = state
                    return rest
                },
            },
        ],
        diagnoseLoadingIds: [
            [] as string[],
            {
                diagnose: (state, { id }) => (state.includes(id) ? state : [...state, id]),
                diagnoseSuccess: (state, { id }) => state.filter((existingId) => existingId !== id),
                diagnoseFailure: (state, { id }) => state.filter((existingId) => existingId !== id),
            },
        ],
        expandedRecordIds: [
            [] as string[],
            {
                setRecordExpanded: (state, { id, expanded }) => {
                    if (expanded) {
                        return state.includes(id) ? state : [...state, id]
                    }
                    return state.filter((existingId) => existingId !== id)
                },
                clearDiagnosticReport: (state, { id }) => state.filter((existingId) => existingId !== id),
            },
        ],
        recordActiveTabs: [
            {} as Record<string, string>,
            {
                setRecordActiveTab: (state, { id, tab }) => ({ ...state, [id]: tab }),
                clearDiagnosticReport: (state, { id }) => {
                    const { [id]: _removed, ...rest } = state
                    return rest
                },
            },
        ],
        rootRedirectDrafts: [
            {} as Record<string, string>,
            {
                setRootRedirectDraft: (state, { id, rootRedirectUrl }) => ({ ...state, [id]: rootRedirectUrl }),
                updateRootRedirectSuccess: (state, { payload }) =>
                    payload ? { ...state, [payload.id]: payload.rootRedirectUrl } : state,
            },
        ],
    })),
    loaders(({ values, actions }) => ({
        proxyRecords: {
            __default: [] as ProxyRecord[],
            loadRecords: async () => {
                // drf-spectacular correctly describes this custom list response as an object, but
                // Orval still applies its list-action array heuristic to the generated function.
                const response = (await proxyRecordsList(
                    values.currentOrganizationId
                )) as unknown as ProxyRecordListResponseApi
                actions.setMaxProxyRecords(response.max_proxy_records)
                return response.results
            },
            createRecord: async ({ domain }: { domain: string }) => {
                const response = await proxyRecordsCreate(values.currentOrganizationId, { domain })
                lemonToast.success('Record created')
                actions.collapseForm()
                return [response, ...values.proxyRecords]
            },
            deleteRecord: async (id: ProxyRecord['id']) => {
                await proxyRecordsDestroy(values.currentOrganizationId, id)
                const newRecords = [...values.proxyRecords].map((r) => ({
                    ...r,
                    status: r.id === id ? 'deleting' : r.status,
                }))
                return newRecords
            },
            retryRecord: async (id: ProxyRecord['id']) => {
                await proxyRecordsRetryCreate(values.currentOrganizationId, id)
                lemonToast.success('Retry initiated')
                return values.proxyRecords.map((r) => ({
                    ...r,
                    status: r.id === id ? 'waiting' : r.status,
                    message: r.id === id ? undefined : r.message,
                })) as ProxyRecord[]
            },
            updateRootRedirect: async ({ id, rootRedirectUrl }: { id: string; rootRedirectUrl: string }) => {
                const updatedRecord = await proxyRecordsPartialUpdate(values.currentOrganizationId, id, {
                    root_redirect_url: rootRedirectUrl || null,
                })
                lemonToast.success(rootRedirectUrl ? 'Root redirect updated' : 'Root redirect removed')
                return values.proxyRecords.map((record) => (record.id === id ? updatedRecord : record))
            },
        },
    })),
    selectors(() => ({
        shouldRefreshRecords: [
            (s) => [s.proxyRecords],
            (proxyRecords: ProxyRecord[]) => {
                return proxyRecords.some((r) => ['waiting', 'issuing', 'deleting'].includes(r.status))
            },
        ],
        shouldShowCloudflareOptIn: [
            (s) => [s.cloudflareOptInAcknowledged, s.proxyRecordsLoaded, s.proxyRecords, s.user],
            (acknowledged: boolean, recordsLoaded: boolean, records: ProxyRecord[], user: UserType | null): boolean => {
                if (acknowledged) {
                    return false
                }
                if (user?.is_impersonated) {
                    return false
                }
                // Wait for the initial records fetch — otherwise the banner flashes during the API call
                // for orgs that already have proxy records, which is the visible symptom of #59549.
                if (!recordsLoaded) {
                    return false
                }
                if (records.length > 0) {
                    return false
                }
                return true
            },
        ],
    })),
    listeners(({ actions, values }) => ({
        collapseForm: () => actions.loadRecords(),
        deleteRecordFailure: () => actions.loadRecords(),
        retryRecordFailure: () => actions.loadRecords(),
        loadRecordsSuccess: ({ proxyRecords }) => {
            // Mark the reverse proxy setup task as completed if any proxy is valid
            const hasValidProxy = proxyRecords.some((r) => r.status === 'valid')
            if (hasValidProxy) {
                globalSetupLogic.findMounted()?.actions.markTaskAsCompleted(SetupTaskId.SetUpReverseProxy)
            }
        },
        maybeRefreshRecords: () => {
            if (values.shouldRefreshRecords) {
                actions.loadRecords()
            }
        },
        diagnose: async ({ id }) => {
            try {
                const report = await proxyRecordsDiagnoseCreate(values.currentOrganizationId, id)
                actions.diagnoseSuccess(id, report)
            } catch (e) {
                const message = e instanceof Error ? e.message : String(e)
                actions.diagnoseFailure(id, message)
                lemonToast.error(`Diagnose failed: ${message}`)
            }
        },
        diagnoseSuccess: ({ id }) => {
            // Auto-expand the row and switch to the Diagnosis tab so the user sees the report immediately.
            actions.setRecordExpanded(id, true)
            actions.setRecordActiveTab(id, 'diagnosis')
        },
    })),
    forms(({ actions, values }) => ({
        createRecord: {
            defaults: { domain: initialDomainFor(values.user) },
            errors: ({ domain }: { domain: string }) => ({
                domain:
                    domain === ''
                        ? 'Domain is required'
                        : domain.includes('*')
                          ? 'Domains cannot include wildcards'
                          : !isDomain('http://' + domain)
                            ? 'Do not include the protocol e.g. https://'
                            : !domain.match(/^[a-z0-9](?:[a-z0-9.-]*[a-z0-9])?$/)
                              ? "Invalid domain. Please provide a lowercase RFC 1123 subdomain. It must consist of lower case alphanumeric characters, '-' or '.', and must start and end with an alphanumeric character"
                              : undefined,
            }),
            submit: ({ domain }) => {
                const doSubmit = (): void => {
                    actions.createRecord({ domain })
                    actions.resetCreateRecord()
                }

                if (isRiskyDomain(domain)) {
                    LemonDialog.open({
                        title: 'This domain may be blocked by ad-blockers',
                        width: '25rem',
                        content: `The domain "${domain}" contains a word commonly associated with tracking or analytics. Ad-blockers are likely to block requests to this domain, which will cause data loss. Are you sure you want to proceed?`,
                        primaryButton: {
                            status: 'danger',
                            children: 'Proceed anyway',
                            onClick: doSubmit,
                        },
                        secondaryButton: {
                            children: 'Choose a different domain',
                        },
                    })
                    return
                }

                doSubmit()
            },
        },
    })),
    afterMount(({ actions, values, cache }) => {
        // Only fetch when authenticated and the org is loaded — otherwise the GET fires without a
        // valid session and 401s, polluting error tracking.
        if (values.user && values.currentOrganizationId) {
            actions.loadRecords()
        }
        cache.disposables.add(() => {
            const timerId = setInterval(() => actions.maybeRefreshRecords(), 5000)
            return () => clearInterval(timerId)
        }, 'refreshInterval')
    }),
])