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.

3.0 KB
Raw Blame
import { POSTHOG_EU_BASE_URL, POSTHOG_US_BASE_URL } from '@/lib/constants'
import type { ClientMapping } from '@/lib/kv'
import { putClientMapping } from '@/lib/kv'

/**
 * Dynamic Client Registration (RFC 7591) — dual-register proxy.
 *
 * Registers the client on BOTH US and EU PostHog instances simultaneously,
 * then stores the mapping and returns a proxy client_id to the caller.
 *
 * The proxy client_id is the US client_id by convention — the mapping in KV
 * lets us translate to the EU client_id when needed.
 */
export async function handleRegister(request: Request, kv: KVNamespace): Promise<Response> {
    const body = await request.text()
    const headers = new Headers(request.headers)
    headers.delete('host')

    // Add proxy callback URL to redirect_uris so regional servers accept it
    // during the callback interception flow
    const proxyCallbackUrl = `${new URL(request.url).protocol}//${new URL(request.url).host}/oauth/callback/`
    let originalRedirectUris: string[] | undefined
    let registrationBody = body
    try {
        const json = JSON.parse(body) as Record<string, unknown>
        if (Array.isArray(json.redirect_uris)) {
            originalRedirectUris = json.redirect_uris as string[]
            json.redirect_uris = [...originalRedirectUris, proxyCallbackUrl]
            registrationBody = JSON.stringify(json)
        }
    } catch {
        // Not JSON — forward as-is
    }

    const [usResponse, euResponse] = await Promise.all([
        fetch(`${POSTHOG_US_BASE_URL}/oauth/register/`, {
            method: 'POST',
            headers,
            body: registrationBody,
        }),
        fetch(`${POSTHOG_EU_BASE_URL}/oauth/register/`, {
            method: 'POST',
            headers: new Headers(headers),
            body: registrationBody,
        }),
    ])

    const usData = await usResponse.json<Record<string, unknown>>()
    const euData = await euResponse.json<Record<string, unknown>>()

    if (!usResponse.ok || !euResponse.ok) {
        const failedResponse = !usResponse.ok ? usResponse : euResponse
        const failedData = !usResponse.ok ? usData : euData
        return new Response(JSON.stringify(failedData), {
            status: failedResponse.status,
            headers: { 'Content-Type': 'application/json' },
        })
    }

    const proxyClientId = usData.client_id as string

    const mapping: ClientMapping = {
        us_client_id: usData.client_id as string,
        eu_client_id: euData.client_id as string,
        redirect_uris: originalRedirectUris,
        created_at: Date.now(),
    }

    // Store client secrets for confidential clients
    if (usData.client_secret) {
        mapping.us_client_secret = usData.client_secret as string
    }
    if (euData.client_secret) {
        mapping.eu_client_secret = euData.client_secret as string
    }

    await putClientMapping(kv, proxyClientId, mapping)

    return new Response(JSON.stringify(usData), {
        status: 201,
        headers: { 'Content-Type': 'application/json' },
    })
}