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.

5.9 KB
Raw Blame
import { type Region, baseUrlForRegion } from '@/lib/constants'
import {
    type ClientMapping,
    getClientMapping,
    putCallbackRedirectUri,
    putPendingCallback,
    putRegionSelection,
} from '@/lib/kv'
import { type ValidationError, errorResponse } from '@/lib/validation'

import REGION_PICKER_HTML from '../static/region-picker.html'

const REGION_PICKER_HEADERS: Record<string, string> = {
    'Content-Type': 'text/html; charset=utf-8',
    // Bundled at deploy time; identical for all OAuth flows until the next deploy.
    'Cache-Control': 'public, max-age=3600, s-maxage=86400, stale-while-revalidate=604800',
    'X-Frame-Options': 'DENY',
    'X-Content-Type-Options': 'nosniff',
    'Referrer-Policy': 'no-referrer',
}

// Prevent open redirects: for clients registered through the proxy (which have
// stored redirect_uris), the requested redirect_uri must be one of them. Legacy
// clients without stored redirect_uris fall through to regional server validation.
function validateRegisteredRedirectUri(
    redirectUri: string | null,
    mapping: ClientMapping | null
): ValidationError | null {
    if (mapping?.redirect_uris && redirectUri && !mapping.redirect_uris.includes(redirectUri)) {
        return {
            error: 'invalid_request',
            error_description: 'redirect_uri is not registered for this client',
        }
    }
    return null
}

/**
 * OAuth Authorization — region picker + redirect.
 *
 * When the MCP client (or any OAuth client) sends the user to /oauth/authorize/,
 * we show a region picker page. After the user selects their region, we:
 * 1. Store the region selection in KV (for the token exchange step)
 * 2. Translate the proxy client_id to the regional client_id
 * 3. Redirect the user to the correct regional /oauth/authorize/ with all params
 */
export async function handleAuthorize(request: Request, kv: KVNamespace): Promise<Response> {
    const url = new URL(request.url)

    // If region is already selected (via query param from the picker page),
    // redirect to the regional authorize endpoint
    const selectedRegion = url.searchParams.get('_region') as Region | null
    if (selectedRegion === 'us' || selectedRegion === 'eu') {
        return redirectToRegionalAuthorize(url, selectedRegion, kv)
    }

    const liveRegion = soleLiveRegion(request.headers.get('Cookie'))
    if (liveRegion) {
        return redirectToRegionalAuthorize(url, liveRegion, kv)
    }

    // Show the region picker page (JS reads query params from window.location.search)
    return new Response(REGION_PICKER_HTML, { headers: REGION_PICKER_HEADERS })
}

/**
 * Reads `SameSite=Lax` cookies, which is the only kind that survives the cross-site top-level
 * navigation an OAuth client sends the visitor here with. `ph_current_instance` and the other
 * `Strict` cookies are withheld on that hop and never reach this code.
 */
function soleLiveRegion(cookieHeader: string | null): Region | null {
    if (!cookieHeader) {
        return null
    }
    const names = new Set(cookieHeader.split(';').map((c) => c.trim().split('=')[0]))
    const [sole, second] = (['us', 'eu'] as const).filter((region) => names.has(`ph_authenticated_${region}`))
    return sole && !second ? sole : null
}

async function redirectToRegionalAuthorize(url: URL, region: Region, kv: KVNamespace): Promise<Response> {
    const clientId = url.searchParams.get('client_id')
    const state = url.searchParams.get('state')
    const originalRedirectUri = url.searchParams.get('redirect_uri')
    let regionalClientId = clientId
    let mapping: ClientMapping | null = null

    // Translate proxy client_id to regional client_id if we have a mapping
    if (clientId) {
        mapping = await getClientMapping(kv, clientId)
        if (mapping) {
            regionalClientId = region === 'eu' ? mapping.eu_client_id : mapping.us_client_id
        }
    }

    const redirectUriError = validateRegisteredRedirectUri(originalRedirectUri, mapping)
    if (redirectUriError) {
        return errorResponse(redirectUriError)
    }

    const kvWrites: Promise<void>[] = []
    if (clientId) {
        kvWrites.push(putRegionSelection(kv, clientId, region))
    }

    // Only proxy-registered clients have the proxy callback in their registered redirect_uris.
    let nonce: string | null = null
    if (mapping?.redirect_uris && originalRedirectUri) {
        // A proxy nonce keys the record so knowing the client's state cannot overwrite it.
        nonce = crypto.randomUUID()
        kvWrites.push(putPendingCallback(kv, nonce, { redirect_uri: originalRedirectUri, state: state ?? null }))
        if (clientId) {
            kvWrites.push(putCallbackRedirectUri(kv, clientId, originalRedirectUri))
        }
    }

    await Promise.all(kvWrites)

    // Build the regional authorize URL with all original params
    const regionalBase = baseUrlForRegion(region)
    const regionalUrl = new URL('/oauth/authorize/', regionalBase)

    // Replace redirect_uri with proxy's own callback so the client always
    // talks back to the proxy (not directly to the regional server).
    // Only for proxy-registered clients where the proxy callback is a registered URI.
    const proxyCallbackUrl = `${url.protocol}//${url.host}/oauth/callback/`

    // Copy all params except our internal _region param
    for (const [key, value] of url.searchParams.entries()) {
        if (key === '_region') {
            continue
        }
        if (key === 'state' && nonce) {
            continue
        }
        if (key === 'client_id' && regionalClientId) {
            regionalUrl.searchParams.set(key, regionalClientId)
        } else if (key === 'redirect_uri' && mapping?.redirect_uris) {
            regionalUrl.searchParams.set(key, proxyCallbackUrl)
        } else {
            regionalUrl.searchParams.set(key, value)
        }
    }
    if (nonce) {
        regionalUrl.searchParams.set('state', nonce)
    }

    return Response.redirect(regionalUrl.toString(), 302)
}