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.

feat(auth): Log into prod via OAuth, desktop app-style (#63939)

Michael Matloka8fc65687edf9
diff --git a/frontend/snapshots.yml b/frontend/snapshots.yml
index e02edd81e63b..daa0935dd5f5 100644
--- a/frontend/snapshots.yml
+++ b/frontend/snapshots.yml
@@ -6467,33 +6467,33 @@ snapshots:
scenes-other-invitesignup--sso-enforced-saml--light:
hash: v1.k794b7964.54bf52e1d7ffe500b869f2ae87b2ff29c1299ea84da59935a543c1daa8d98074.Yu-XaNCXkf5Q0PHHHTt5R7nKuOotRDW0kEvHwSoSaQQ
scenes-other-login--cloud--dark:
- hash: v1.k794b7964.096249ded92e55a906cde7780fec0780aebb85a1f64072d6b83a47c0ade99cd9.EKtIqXk-0CLiwPNHXwhjDkrJSTaKDczbHxGmyrIr3cU
+ hash: v1.k794b7964.cdd658e4d6c52ca2444933d39e771b72a48ecdcf729ab389ee7d7c32707bab23.1NbY8c0663jyvJUIllazHirORzprk-jr4XtjzgTL9EQ
scenes-other-login--cloud--light:
- hash: v1.k794b7964.cdca32487a3bc830ab7967236377708a060c273216102930882b23aa1ffe73f2.hZQssozYM5A0Rs8Z8T7azrZ4CUGihJ8IYnoxhRHOqoE
+ hash: v1.k794b7964.cf01721b5633655bd733267b9438f9e15ee4cc0a4c091e80cccb7da4a8a90f0f.DEBosDg1IokgtM9LSOL_cZEY9DwolGirUzKL7mmhjlY
scenes-other-login--cloud-eu--dark:
- hash: v1.k794b7964.bc6970a3a1a688df7ed77e48177c232a90c58b15370223585c2bbc276558ba85.I05mJGIu5iLVEHiDnri_USh45MMz0qdU13LevNC08dY
+ hash: v1.k794b7964.b0d42e733b537012104323104769a11544b31699c85e4da2faffc1bdc324258a.yyCbpq2Uef-uVo2V29dY2jEH95se7i8MqvVVmaX0TDo
scenes-other-login--cloud-eu--light:
- hash: v1.k794b7964.cabe9ff66d45566922731ed5b40df4b9b1d6a874223ebc16df811dc7a90655dc.9KW2J9pX1QysmlB4QoaIQoVjwuzpTsf08I17tSTKoOk
+ hash: v1.k794b7964.ee3b048197e52b9bc01be2b2103bf5d7873338c43cf4ee5d42900688c391f16e.Qy2qcUJHJkN9-SiW8QIXL1CekO2z7Xu8HPq27jK8JtQ
scenes-other-login--cloud-with-google-login-enforcement--dark:
- hash: v1.k794b7964.a10d712ce02c714c49515dd59a23540a90f47f684c5c8619ad22bd15364cf27d.38Bs_hejj-HWbqhETzvh4gQa59tri4Kx2OyEaiUpRg0
+ hash: v1.k794b7964.e1869e974e5b204a27b924d5cf63e47f6757a957bc2f2a94caa9bd94a79de654.T9080txGwrDwBSNrOHscYmGxefVwdvlVUkYmavr-BeA
scenes-other-login--cloud-with-google-login-enforcement--light:
- hash: v1.k794b7964.0ff44d68c1579ab57eee9d339e6044e409ef5401b2b0ed86a1b7eaf9095d4e7e.0WUhtxd8w3iXWySuA18HcZTlzO__wDlo0GnBWBG3wGQ
+ hash: v1.k794b7964.416f990f167812f20bbbce2cc3df189ca598691aad1d2578e50e920eebfd9506.HXAlasWeU4f1VvhwHQWvtYuQd7SW9rlpmxC1iBuZ9FE
scenes-other-login--second-factor--dark:
hash: v1.k794b7964.aab7ee83a3f3091df75e64ff82771eae72b41cd14a08f6c9bf26b78c836e7d62.jWSH807x5U9Pw7-1WleNFPs2UcgcktqItu1x_iumnxo
scenes-other-login--second-factor--light:
hash: v1.k794b7964.cae5ac2439ccb084cc8a00b6a0c9460a6e9652af7c56c6b5ed450e6d7cc84adf.-3sEuShu3S7a7lJsYIpkvhnEsDlNh43FVc6KXT5MVRw
scenes-other-login--self-hosted--dark:
- hash: v1.k794b7964.23c635147cee19fe5c29cec52e7768bd0a52a8b5920b75c39336853c3a1b6f6c.NosxKBUJtEedndx6pDjIe7MSKOFOQE2VyC8EfuV0k38
+ hash: v1.k794b7964.f371511c872b29bd47249a1a0bb3afabeefc8fc86510b6e6dfc950334f24bc10.ykYCYArYCNW5B4HdA6BULPH6TTzQ-Phw5JlsxFPDGcE
scenes-other-login--self-hosted--light:
- hash: v1.k794b7964.2ea872bb3d1dc7851ce589692d40e543a1d573f6b36340e88a81c3ddc9b91ded.jLdcFWsKpa943jgC4_gCIlNACLCTV0Bmc_5SHJjh1As
+ hash: v1.k794b7964.e1032243da79841fdb90d496a74abb3a4ba96d2eeced7f68cad930b274297958.uAO8FjZLiz3jRgGCUwKLfDe2D5EwprZVGh8cN12gU8U
scenes-other-login--self-hosted-with-saml--dark:
- hash: v1.k794b7964.6fed44dadd2b1df54044208d679d7d8a55ef61af1851bfda1e0adc4d8df04d66.zUgkiYzaKEYvK1-sDMdBGtK_JkGAW_GboR3imXBvWCs
+ hash: v1.k794b7964.e1f7ef8e2d8bdedeb8ed76033f123f570e382714bf692a8127a99a04f86d3434.b-oa2DpM1XCCzW1n0VLB1Q85axf643MpgFq2DgxqjIg
scenes-other-login--self-hosted-with-saml--light:
- hash: v1.k794b7964.45d4188866323f82d7553e89b693c4cb8e22dcf04e3eb637a1f39d314d0330ba.inbY4qLocXPlHEPDfaw08vm_CUIBpZzrnXsF9wJAi6k
+ hash: v1.k794b7964.dc490b718a301adba24dc7019106ed2097a750fa49f27fbf947f41f42ac818a3.qu1IoxpXPNSmZV5nHCNwR68Hw9wBRXrDYi5bIwx-NJk
scenes-other-login--sso-error--dark:
- hash: v1.k794b7964.30246f37bec093282c28c4c2369664dbf97e256a3b7c4c635e63ca6f602e38a1.2HxEltsdIMc67gyXe563-b-N8rp-rat-FtoBkwJyx1w
+ hash: v1.k794b7964.b968f89fa4feb0d2f6423f2532399af248237d1ceb8e94eda93f073dd8e8dc1e.exPqCERSpsOhHCtSF-xAxQY9DGLRG54CVMgiIiyHkPU
scenes-other-login--sso-error--light:
- hash: v1.k794b7964.e3531f02585f69ca46e68222d24b33db7e853635b357d95b3c792b2b97f8a45b.P3WyrTpc-AkNiK9F-Tdx7dtDFZlRpeZi0q8ijJ2FuFI
+ hash: v1.k794b7964.bf726aafab909db5abef95ba50728a484226b67a14df698563c5b9c5cdd6be53.uxC2xUEzUsarK6a8Ryr0pQf2IqTCz0vb5y6e7jo2_nY
scenes-other-onboarding--ai-observability-sdk-install--dark:
hash: v1.k794b7964.4047bda2f11ee77266a5fe71ddd327f59693592d6f014ef7da83d624d446c990.6HFORXyzVSPnXIEmpUmqK9DOv0D6-Uux8j3FM_8OUG4
scenes-other-onboarding--ai-observability-sdk-install--light:
@@ -6699,17 +6699,17 @@ snapshots:
scenes-other-settings-organization-oauth-apps--with-apps--light:
hash: v1.k794b7964.960c9c5939030aa60f3d3054dc738b569ac92c34c1c70e56113fc0f1aede9622.-VLXqxvKDWROE70UKtYHE5yPgVD_3ZPzpqZIiRSmoS8
scenes-other-signup--cloud--dark:
- hash: v1.k794b7964.b99418db096e09f684bab6bb6c201709204f05c93adfde4c9bceae7e20eed68a.LctBd3f8UtoOKUmxdmKN61Xq4ZzL7teC_9OUrK8SRHw
+ hash: v1.k794b7964.3d0dd26f22947548ef4ea284f2b22dbc9e80bddae0d3d945b3b5f5859ae32cc3._C-x3R5ofRenZgjdqrYqSdUQfpzOb18NIpZDJd6GmJM
scenes-other-signup--cloud--light:
- hash: v1.k794b7964.3b3524dd9fe21b210d6b36e1e66d45059364a538358bd05f189e0590a38de25a.2a9SlBhCrHAoxzjwcr3CFIollheOQhIqprgvdGAsmkw
+ hash: v1.k794b7964.6d721ef0a12077fb29345f05f2cf52a1ae8c8c3ae714a9444afddd132fc3c869.aTjipnBzvq-KTrnFr_ubbEggS9lub0RebE9Z6ORp03M
scenes-other-signup--self-hosted--dark:
- hash: v1.k794b7964.e8c2fc989aed12988d2fb64c9669ceb8ee3ce7d426acc406a304accd8e857465.BVhvxueaSfpzjviOAP1FB_RM9VLHecMJQyg9FGtyQhI
+ hash: v1.k794b7964.ee08fe9764810e371bbcba07c87085b7d463c16df197c3744e7f4032d946715e.mnEe8Xdp7d6n60MsGRK-Dum7ka7LQ_BPStppJjQf9ss
scenes-other-signup--self-hosted--light:
- hash: v1.k794b7964.9f060d553e0c0170bfc6463550d73b6f7a30beeca9a1d5bcd3fec80ba2204b04.mT9uzuS8RFygU48VuQv3q3NpzrSX9m2jaSo590UhE1s
+ hash: v1.k794b7964.ca130e1914fbd4c76b9ef85fbc72baa8b701edef33e773bc03659486d29a9307.mOw-oIlJ96nkXOdbpL9cMUvAS9cxHuMSXr7-5E7GeeE
scenes-other-signup--self-hosted-sso--dark:
- hash: v1.k794b7964.e1a1515f53c51495a250c4c1b1b78c7392cd7df676ff04cc6b705ed6d5ab0b58.aOATg9hRkbsKnvePT2K6-t_mL1T1emEVWrVyc-5S3EI
+ hash: v1.k794b7964.8f9b22134a1e3aec6cc9af4bf2ed889a75c8ba6f1b8785c4a2eb7ead6b1dd723.mrVzttqS5I3RrlPieYKde3vwWVZX77WjTz9Dv-CsyXw
scenes-other-signup--self-hosted-sso--light:
- hash: v1.k794b7964.eb8517ec8c82aebfe58bbb37ff282957abb1b9b1dfcae0b31dd70a022d3b5b1e.ztjSnRxFqT-Rf255K8BnUJ0SaFFbHbIS9GKMMrDCCFU
+ hash: v1.k794b7964.122fe3ac14637eac99faba85b4c90824e587f3307eb66dfa41e4a4236cc46a38.JoIx42ofLcWG-woNh2fXJhNAf4a1K7hDj_j4ubPSGfY
scenes-other-toolbar--actions--dark:
hash: v1.k794b7964.2f7954382c0cf1488a0fdb039dbaf8f351b5ae143a405919c619e08a2af3740b.Tt41wY8CBczMxtTmjJfomteHN2yCeDFPPfAxgVaYNE8
scenes-other-toolbar--actions--light:
diff --git a/frontend/src/lib/api.ts b/frontend/src/lib/api.ts
index 98a3ff719b38..24bf17b71489 100644
--- a/frontend/src/lib/api.ts
+++ b/frontend/src/lib/api.ts
@@ -6,6 +6,7 @@ import { ApiError } from 'lib/api-error'
import { ActivityLogProps } from 'lib/components/ActivityLog/ActivityLog'
import { ActivityLogItem } from 'lib/components/ActivityLog/humanizeActivity'
import { apiStatusLogic } from 'lib/logic/apiStatusLogic'
+import { getBackendHost, getStoredSession, isOAuthMode, refreshAccessToken } from 'lib/oauth/oauthClient'
import { assertNotReadOnly } from 'lib/readOnlyGuard'
import { objectClean } from 'lib/utils/objects'
import { toParams } from 'lib/utils/url'
@@ -2041,6 +2042,14 @@ const normalizeUrl = (url: string): string => {
const prepareUrl = (url: string): string => {
let output = normalizeUrl(url)
+ // OAuth mode: route the data API to the selected region's host. Only `/api/*` is rewritten —
+ // it's what the cloud CORS allowlist covers. Other endpoints (e.g. `/_preflight/`) aren't
+ // cross-origin accessible, so they stay same-origin on the local instance.
+ const backendHost = getBackendHost()
+ if (backendHost && output.startsWith('/api/')) {
+ output = backendHost + output
+ }
+
const exporterContext = getCurrentExporterData()
if (exporterContext && exporterContext.accessToken) {
@@ -2055,6 +2064,33 @@ const prepareUrl = (url: string): string => {
return output
}
+/**
+ * Bearer auth header for standalone OAuth mode; empty when served by Django (session auth).
+ * Synchronous so requests still dispatch synchronously — an expired token is handled by the
+ * 401 → refresh → retry path in handleFetch.
+ */
+function oauthAuthHeaders(): Record<string, string> {
+ const session = getStoredSession()
+ return session ? { Authorization: `Bearer ${session.accessToken}` } : {}
+}
+
+/**
+ * PostHog session/distinct tracing headers. Omitted in OAuth mode because the cross-origin CORS
+ * allowlist (CORS_ALLOWED_TRACING_HEADERS) doesn't include them, so a preflight would fail —
+ * they're debugging aids, not functionally required.
+ */
+function tracingHeaders({ includeDistinctId = false } = {}): Record<string, string> {
+ if (isOAuthMode()) {
+ return {}
+ }
+ const sessionId = getSessionId()
+ const distinctId = includeDistinctId ? getDistinctId() : undefined
+ return {
+ ...(sessionId ? { 'X-POSTHOG-SESSION-ID': sessionId } : {}),
+ ...(distinctId ? { 'X-POSTHOG-DISTINCT-ID': distinctId } : {}),
+ }
+}
+
const PROJECT_ID_REGEX = /\/api\/(project|environment)s\/(\w+)(?:$|[/?#])/
const ensureProjectIdNotInvalid = (url: string): void => {
@@ -6766,13 +6802,13 @@ const api = {
authHeaders['Authorization'] = `Bearer ${exporterContext.shareToken}`
}
- return await handleFetch(url, 'GET', () => {
+ return await handleFetch(url, 'GET', async () => {
return fetch(url, {
signal: options?.signal,
headers: {
...objectClean(options?.headers ?? {}),
- ...(getSessionId() ? { 'X-POSTHOG-SESSION-ID': getSessionId() } : {}),
- ...(getDistinctId() ? { 'X-POSTHOG-DISTINCT-ID': getDistinctId() } : {}),
+ ...tracingHeaders({ includeDistinctId: true }),
+ ...oauthAuthHeaders(),
...authHeaders,
},
})
@@ -6797,7 +6833,8 @@ const api = {
...objectClean(options?.headers ?? {}),
...(isFormData ? {} : { 'Content-Type': 'application/json' }),
'X-CSRFToken': getCookie(CSRF_COOKIE_NAME) || '',
- ...(getSessionId() ? { 'X-POSTHOG-SESSION-ID': getSessionId() } : {}),
+ ...tracingHeaders(),
+ ...oauthAuthHeaders(),
},
body: isFormData ? data : JSON.stringify(data),
signal: options?.signal,
@@ -6826,14 +6863,15 @@ const api = {
assertNotReadOnly('POST', url)
const isFormData = data instanceof FormData
- return await handleFetch(url, 'POST', () =>
+ return await handleFetch(url, 'POST', async () =>
fetch(url, {
method: 'POST',
headers: {
...objectClean(options?.headers ?? {}),
...(isFormData ? {} : { 'Content-Type': 'application/json' }),
'X-CSRFToken': getCookie(CSRF_COOKIE_NAME) || '',
- ...(getSessionId() ? { 'X-POSTHOG-SESSION-ID': getSessionId() } : {}),
+ ...tracingHeaders(),
+ ...oauthAuthHeaders(),
},
body: data ? (isFormData ? data : JSON.stringify(data)) : undefined,
signal: options?.signal,
@@ -6845,13 +6883,14 @@ const api = {
url = prepareUrl(url)
ensureProjectIdNotInvalid(url)
assertNotReadOnly('DELETE', url)
- return await handleFetch(url, 'DELETE', () =>
+ return await handleFetch(url, 'DELETE', async () =>
fetch(url, {
method: 'DELETE',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'X-CSRFToken': getCookie(CSRF_COOKIE_NAME) || '',
- ...(getSessionId() ? { 'X-POSTHOG-SESSION-ID': getSessionId() } : {}),
+ ...tracingHeaders(),
+ ...oauthAuthHeaders(),
},
})
)
@@ -6906,7 +6945,7 @@ const api = {
headers: {
...(method === 'POST' ? { 'Content-Type': 'application/json' } : {}),
'X-CSRFToken': getCookie('posthog_csrftoken') || '',
- ...(getSessionId() ? { 'X-POSTHOG-SESSION-ID': getSessionId() } : {}),
+ ...tracingHeaders(),
...objectClean(headers ?? {}),
},
body: data !== undefined ? JSON.stringify(data) : undefined,
@@ -7102,7 +7141,12 @@ const api = {
const warnedSharedViewLeaks = new Set<string>()
-async function handleFetch(url: string, method: string, fetcher: () => Promise<Response>): Promise<Response> {
+async function handleFetch(
+ url: string,
+ method: string,
+ fetcher: () => Promise<Response>,
+ isRetry = false
+): Promise<Response> {
const startTime = new Date().getTime()
let response
@@ -7122,6 +7166,15 @@ async function handleFetch(url: string, method: string, fetcher: () => Promise<R
throw new ApiError(error as any, response?.status)
}
+ // Standalone OAuth mode: a 401 likely means the access token expired — refresh once and retry.
+ // The fetcher rebuilds its Authorization header on re-invocation, picking up the new token.
+ if (response.status === 401 && isOAuthMode() && !isRetry) {
+ const refreshed = await refreshAccessToken()
+ if (refreshed) {
+ return await handleFetch(url, method, fetcher, true)
+ }
+ }
+
if (!response.ok) {
const duration = new Date().getTime() - startTime
const pathname = new URL(url, location.origin).pathname
diff --git a/frontend/src/lib/components/DebugNotice.tsx b/frontend/src/lib/components/DebugNotice.tsx
index d3e9a64baa9a..137e4ec9d03e 100644
--- a/frontend/src/lib/components/DebugNotice.tsx
+++ b/frontend/src/lib/components/DebugNotice.tsx
@@ -1,3 +1,4 @@
+import clsx from 'clsx'
import { useState } from 'react'
import { IconCode, IconWarning, IconX } from '@posthog/icons'
@@ -6,6 +7,7 @@ import { Link, Tooltip } from '@posthog/lemon-ui'
import { useOnMountEffect } from 'lib/hooks/useOnMountEffect'
import { IconBranch } from 'lib/lemon-ui/icons'
import { LemonButton } from 'lib/lemon-ui/LemonButton'
+import { getRegionForHost, getStoredSession, OAUTH_REGIONS } from 'lib/oauth/oauthClient'
import { ButtonPrimitive } from 'lib/ui/Button/ButtonPrimitives'
export interface DebugNoticeProps {
@@ -35,6 +37,10 @@ export function DebugNotice({ isCollapsed }: DebugNoticeProps): JSX.Element | nu
return null
}
+ const oauthSession = getStoredSession()
+ const oauthRegion = oauthSession ? getRegionForHost(oauthSession.backendHost) : null
+ const modeLabel = oauthRegion ? `OAuth mode ${OAUTH_REGIONS[oauthRegion].flag}` : 'DEBUG mode'
+
if (isCollapsed) {
return (
<ButtonPrimitive
@@ -42,7 +48,7 @@ export function DebugNotice({ isCollapsed }: DebugNoticeProps): JSX.Element | nu
tooltip={
<div className="font-mono">
<div>
- <strong>DEBUG mode!</strong>
+ <strong>{modeLabel}!</strong>
</div>
<div>
Branch: <b>{debugInfo.branch}</b>
@@ -62,7 +68,24 @@ export function DebugNotice({ isCollapsed }: DebugNoticeProps): JSX.Element | nu
return (
<div className="border rounded bg-primary overflow-hidden w-full font-mono text-xs *:flex *:items-center *:gap-2 *:pl-2 *:pr-0.5 *:h-7 *:border-l-4">
<div className="border-brand-blue justify-between">
- <b>DEBUG mode</b>
+ <Tooltip
+ title={
+ oauthRegion
+ ? 'Due to intentional limitations of OAuth access, not everything may work'
+ : undefined
+ }
+ placement="top-start"
+ >
+ <div
+ className={clsx(
+ 'flex items-center gap-2 min-w-0 ',
+ oauthRegion ? 'cursor-help' : 'cursor-default'
+ )}
+ >
+ {oauthRegion && <IconWarning className="text-base" />}
+ <span className="font-bold">{modeLabel}</span>
+ </div>
+ </Tooltip>
<LemonButton
icon={<IconX />}
tooltip="Dismiss"
diff --git a/frontend/src/lib/lemon-ui/UploadedLogo/UploadedLogo.tsx b/frontend/src/lib/lemon-ui/UploadedLogo/UploadedLogo.tsx
index f7eeb50ba3b9..dfd8fdbe16ac 100644
--- a/frontend/src/lib/lemon-ui/UploadedLogo/UploadedLogo.tsx
+++ b/frontend/src/lib/lemon-ui/UploadedLogo/UploadedLogo.tsx
@@ -1,6 +1,8 @@
import clsx from 'clsx'
import React, { useState } from 'react'
+import { backendAssetUrl } from 'lib/utils/apiHost'
+
import { LemonSkeleton } from '../LemonSkeleton'
import { Lettermark } from '../Lettermark'
@@ -51,7 +53,7 @@ export const UploadedLogo = React.forwardRef<HTMLDivElement, UploadedLogoProps>(
{isLoadingImage && <LemonSkeleton className="absolute inset-0" />}
<img
className="size-full object-cover"
- src={mediaId.startsWith('data:') ? mediaId : `/uploaded_media/${mediaId}`}
+ src={mediaId.startsWith('data:') ? mediaId : backendAssetUrl(`/uploaded_media/${mediaId}`)}
alt="Uploaded logo"
onError={() => setIsLoadingImage(false)}
onLoad={() => setIsLoadingImage(false)}
diff --git a/frontend/src/lib/oauth/OAuthCallback.tsx b/frontend/src/lib/oauth/OAuthCallback.tsx
new file mode 100644
index 000000000000..2afea50a5cc5
--- /dev/null
+++ b/frontend/src/lib/oauth/OAuthCallback.tsx
@@ -0,0 +1,30 @@
+import { useValues } from 'kea'
+
+import { LemonButton } from 'lib/lemon-ui/LemonButton'
+import { SpinnerOverlay } from 'lib/lemon-ui/Spinner/Spinner'
+
+import { oauthLogic } from './oauthLogic'
+
+/**
+ * Rendered at /oauth/callback. The code→token exchange is kicked off by oauthLogic's
+ * urlToAction; this screen only reflects progress and surfaces any error.
+ */
+export function OAuthCallback(): JSX.Element {
+ const { loginError } = useValues(oauthLogic)
+
+ if (loginError) {
+ return (
+ <div className="flex min-h-screen flex-col items-center justify-center gap-4 p-4">
+ <div className="flex w-full max-w-md flex-col gap-3 rounded-lg border bg-surface-primary p-6 text-center shadow-sm">
+ <h2 className="m-0 text-lg font-bold">Sign-in failed</h2>
+ <p className="m-0 text-sm text-secondary">{loginError}</p>
+ <LemonButton type="primary" center fullWidth to="/login">
+ Back to sign in
+ </LemonButton>
+ </div>
+ </div>
+ )
+ }
+
+ return <SpinnerOverlay sceneLevel visible />
+}
diff --git a/frontend/src/lib/oauth/oauthClient.ts b/frontend/src/lib/oauth/oauthClient.ts
new file mode 100644
index 000000000000..9cbdf94a5989
--- /dev/null
+++ b/frontend/src/lib/oauth/oauthClient.ts
@@ -0,0 +1,206 @@
+// Token store + refresh for the standalone OAuth frontend. Plain TS (no kea) so that
+// `api.ts` and other non-React callers can read a valid bearer token directly.
+// `oauthLogic` wraps this for the login UI.
+
+import { Region } from '~/types'
+
+import { generateCodeChallenge } from './pkce'
+
+export interface OAuthRegionConfig {
+ key: Region.US | Region.EU
+ label: string
+ flag: string
+ host: string
+ clientId: string
+}
+
+// Registered public PKCE client IDs per cloud region (no OAuth for local/self-hosted).
+export const OAUTH_REGIONS: Record<Region.US | Region.EU, OAuthRegionConfig> = {
+ [Region.US]: {
+ key: Region.US,
+ label: 'US Cloud',
+ flag: '🇺🇸',
+ host: 'https://us.posthog.com',
+ clientId: '47rGkjTTMRvkbfU1sdSXsqOGLyJBlbMneRkFKhmO',
+ },
+ [Region.EU]: {
+ key: Region.EU,
+ label: 'EU Cloud',
+ flag: '🇪🇺',
+ host: 'https://eu.posthog.com',
+ clientId: 'VCRpJggenuNKqALWy2Um35S4mHbUcIPPg5hiA03K',
+ },
+}
+
+/** The region whose API host matches the given backend host, or null if none. */
+export function getRegionForHost(host: string): Region.US | Region.EU | null {
+ return Object.values(OAUTH_REGIONS).find((region) => region.host === host)?.key ?? null
+}
+
+/** Where the OAuth provider redirects back to — this frontend's own origin (e.g. http://localhost:8010). */
+function getRedirectUri(): string {
+ return `${window.location.origin}/oauth/callback`
+}
+
+const SESSION_KEY = 'ph_oauth_session'
+// Tokenless dev marker so the DEBUG-gated backend serves the SPA in OAuth mode (value = region).
+// NOT a secure cookie (client-set, forgeable, no httpOnly/Secure) — never gate production auth on
+// it. The backend only honors it under DEBUG (see login_required in posthog/views.py).
+const OAUTH_MODE_COOKIE = 'ph_oauth_mode'
+
+export interface OAuthSession {
+ backendHost: string
+ clientId: string
+ accessToken: string
+ refreshToken: string
+ /** Epoch ms when the access token expires. */
+ expiresAt: number
+}
+
+export interface PendingAuth {
+ backendHost: string
+ clientId: string
+ codeVerifier: string
+ state: string
+ /** In-app path to return to once the flow completes. */
+ returnTo: string
+}
+
+interface TokenResponse {
+ access_token: string
+ refresh_token: string
+ expires_in: number
+}
+
+/**
+ * OAuth mode is active when a cloud OAuth session is stored: the frontend then talks to the
+ * remote region with a bearer token instead of the local backend's session cookie.
+ */
+export function isOAuthMode(): boolean {
+ return !!getStoredSession()
+}
+
+export function getStoredSession(): OAuthSession | null {
+ try {
+ const raw = window.localStorage.getItem(SESSION_KEY)
+ return raw ? (JSON.parse(raw) as OAuthSession) : null
+ } catch {
+ return null
+ }
+}
+
+export function getBackendHost(): string | null {
+ return getStoredSession()?.backendHost ?? null
+}
+
+function storeSession(session: OAuthSession): void {
+ window.localStorage.setItem(SESSION_KEY, JSON.stringify(session))
+ // Persistent (400d cap) to track the localStorage session across browser restarts.
+ document.cookie = `${OAUTH_MODE_COOKIE}=${getRegionForHost(session.backendHost) ?? '1'}; path=/; Max-Age=34560000; SameSite=Lax`
+}
+
+export function clearSession(): void {
+ window.localStorage.removeItem(SESSION_KEY)
+ document.cookie = `${OAUTH_MODE_COOKIE}=; path=/; Max-Age=0; SameSite=Lax`
+}
+
+function sessionFromTokenResponse(backendHost: string, clientId: string, data: TokenResponse): OAuthSession {
+ return {
+ backendHost,
+ clientId,
+ accessToken: data.access_token,
+ refreshToken: data.refresh_token,
+ expiresAt: Date.now() + data.expires_in * 1000,
+ }
+}
+
+/** Full authorize URL for a flow; also computes the S256 challenge from the stored verifier. */
+export async function buildAuthorizeUrl(pending: PendingAuth): Promise<string> {
+ const codeChallenge = await generateCodeChallenge(pending.codeVerifier)
+ const url = new URL(`${pending.backendHost}/oauth/authorize`)
+ url.searchParams.set('client_id', pending.clientId)
+ url.searchParams.set('redirect_uri', getRedirectUri())
+ url.searchParams.set('response_type', 'code')
+ url.searchParams.set('code_challenge', codeChallenge)
+ url.searchParams.set('code_challenge_method', 'S256')
+ url.searchParams.set('scope', '*') // All scopes, just like the desktop app
+ url.searchParams.set('state', pending.state)
+ return url.toString()
+}
+
+/** Exchange the authorization code for tokens and persist the session. */
+export async function exchangeCodeForToken(pending: PendingAuth, code: string, state: string): Promise<OAuthSession> {
+ if (pending.state !== state) {
+ throw new Error('OAuth state mismatch — please start the login again.')
+ }
+ // Trailing slash is required: CORS_URLS_REGEX only grants CORS headers to `/oauth/token/`.
+ const response = await fetch(`${pending.backendHost}/oauth/token/`, {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({
+ grant_type: 'authorization_code',
+ code,
+ redirect_uri: getRedirectUri(),
+ client_id: pending.clientId,
+ code_verifier: pending.codeVerifier,
+ }),
+ })
+ if (!response.ok) {
+ throw new Error(`Token exchange failed: ${response.status} ${await response.text()}`)
+ }
+ const session = sessionFromTokenResponse(
+ pending.backendHost,
+ pending.clientId,
+ (await response.json()) as TokenResponse
+ )
+ storeSession(session)
+ return session
+}
+
+// Dedupe concurrent refreshes so a burst of 401s triggers a single token request.
+let refreshPromise: Promise<string | null> | null = null
+
+export function refreshAccessToken(): Promise<string | null> {
+ if (!refreshPromise) {
+ refreshPromise = doRefresh().finally(() => {
+ refreshPromise = null
+ })
+ }
+ return refreshPromise
+}
+
+async function doRefresh(): Promise<string | null> {
+ const session = getStoredSession()
+ if (!session) {
+ return null
+ }
+ let response: Response
+ try {
+ response = await fetch(`${session.backendHost}/oauth/token/`, {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({
+ grant_type: 'refresh_token',
+ refresh_token: session.refreshToken,
+ client_id: session.clientId,
+ }),
+ })
+ } catch {
+ // Network error — keep the session so a later request can retry.
+ return null
+ }
+ if (!response.ok) {
+ // A rejected refresh token is terminal: clear the session and force re-login.
+ if (response.status === 400 || response.status === 401) {
+ clearSession()
+ }
+ return null
+ }
+ const updated = sessionFromTokenResponse(
+ session.backendHost,
+ session.clientId,
+ (await response.json()) as TokenResponse
+ )
+ storeSession(updated)
+ return updated.accessToken
+}
diff --git a/frontend/src/lib/oauth/oauthLogic.ts b/frontend/src/lib/oauth/oauthLogic.ts
new file mode 100644
index 000000000000..0adf1c52697c
--- /dev/null
+++ b/frontend/src/lib/oauth/oauthLogic.ts
@@ -0,0 +1,102 @@
+import { actions, kea, listeners, path, reducers } from 'kea'
+import { urlToAction } from 'kea-router'
+
+import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'
+import { getRelativeNextPath } from 'lib/utils/url'
+
+import { Region } from '~/types'
+
+import { buildAuthorizeUrl, clearSession, exchangeCodeForToken, OAUTH_REGIONS, PendingAuth } from './oauthClient'
+import type { oauthLogicType } from './oauthLogicType'
+import { generateCodeVerifier, generateState } from './pkce'
+
+export const oauthLogic = kea<oauthLogicType>([
+ path(['lib', 'oauth', 'oauthLogic']),
+ actions({
+ beginLogin: (region: Region.US | Region.EU) => ({ region }),
+ handleCallback: (code: string, state: string) => ({ code, state }),
+ logout: true,
+ setLoginError: (error: string | null) => ({ error }),
+ setPendingAuth: (pending: PendingAuth) => ({ pending }),
+ clearPendingAuth: true,
+ }),
+ reducers({
+ // Persisted to survive the redirect out to the provider and back.
+ pendingAuth: [
+ null as PendingAuth | null,
+ { persist: true },
+ {
+ setPendingAuth: (_, { pending }) => pending,
+ clearPendingAuth: () => null,
+ },
+ ],
+ loginError: [
+ null as string | null,
+ {
+ setLoginError: (_, { error }) => error,
+ beginLogin: () => null,
+ handleCallback: () => null,
+ },
+ ],
+ loginInProgress: [
+ false,
+ {
+ beginLogin: () => true,
+ handleCallback: () => true,
+ setLoginError: () => false,
+ },
+ ],
+ }),
+ listeners(({ actions, values }) => ({
+ beginLogin: async ({ region }) => {
+ const config = OAUTH_REGIONS[region]
+ const pending: PendingAuth = {
+ backendHost: config.host,
+ clientId: config.clientId,
+ codeVerifier: generateCodeVerifier(),
+ state: generateState(),
+ returnTo: getRelativeNextPath(new URLSearchParams(window.location.search).get('next'), location) || '/',
+ }
+ actions.setPendingAuth(pending)
+ // the authorize URL targets the hardcoded OAUTH_REGIONS host, not user input
+ // nosemgrep: javascript.browser.security.open-redirect.js-open-redirect
+ window.location.href = await buildAuthorizeUrl(pending)
+ },
+ handleCallback: async ({ code, state }) => {
+ const { pendingAuth } = values
+ if (!pendingAuth) {
+ actions.setLoginError('No pending OAuth flow found — please start the login again.')
+ return
+ }
+ try {
+ await exchangeCodeForToken(pendingAuth, code, state)
+ actions.clearPendingAuth()
+ // Full navigation so the app re-bootstraps against the remote region with the new token.
+ // nosemgrep: javascript.browser.security.open-redirect.js-open-redirect
+ window.location.href = pendingAuth.returnTo || '/'
+ } catch (error) {
+ const message = error instanceof Error ? error.message : 'OAuth login failed.'
+ actions.setLoginError(message)
+ lemonToast.error(message)
+ }
+ },
+ logout: () => {
+ clearSession()
+ // Back to the local instance's login.
+ window.location.href = '/login'
+ },
+ })),
+ urlToAction(({ actions }) => ({
+ '/oauth/callback': (_, searchParams) => {
+ if (searchParams.error) {
+ actions.setLoginError(`OAuth error: ${searchParams.error_description || searchParams.error}`)
+ return
+ }
+ if (searchParams.code) {
+ actions.handleCallback(searchParams.code, searchParams.state)
+ } else if (!searchParams.error) {
+ actions.setLoginError('No authorization code received — please start the login again.')
+ }
+ },
+ })),
+])
diff --git a/frontend/src/lib/oauth/pkce.ts b/frontend/src/lib/oauth/pkce.ts
new file mode 100644
index 000000000000..1bc93ecc6789
--- /dev/null
+++ b/frontend/src/lib/oauth/pkce.ts
@@ -0,0 +1,31 @@
+// PKCE (RFC 7636) helpers for the OAuth authorization-code flow. Ported from the
+// PostHog Code desktop app, using the browser's Web Crypto API.
+
+function base64UrlEncode(bytes: Uint8Array): string {
+ let binary = ''
+ for (const byte of bytes) {
+ binary += String.fromCharCode(byte)
+ }
+ return btoa(binary).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '')
+}
+
+/** A high-entropy random string kept on the client and presented at token exchange. */
+export function generateCodeVerifier(): string {
+ const bytes = new Uint8Array(32)
+ window.crypto.getRandomValues(bytes)
+ return base64UrlEncode(bytes)
+}
+
+/** The S256 challenge derived from the verifier, sent on the authorize request. */
+export async function generateCodeChallenge(verifier: string): Promise<string> {
+ const data = new TextEncoder().encode(verifier)
+ const digest = await window.crypto.subtle.digest('SHA-256', data)
+ return base64UrlEncode(new Uint8Array(digest))
+}
+
+/** Opaque CSRF value round-tripped through the `state` param to bind the callback to this flow. */
+export function generateState(): string {
+ const bytes = new Uint8Array(16)
+ window.crypto.getRandomValues(bytes)
+ return base64UrlEncode(bytes)
+}
diff --git a/frontend/src/lib/utils/apiHost.ts b/frontend/src/lib/utils/apiHost.ts
index 00fce98eaab9..c009f5b76020 100644
--- a/frontend/src/lib/utils/apiHost.ts
+++ b/frontend/src/lib/utils/apiHost.ts
@@ -1,5 +1,21 @@
+import { getBackendHost } from 'lib/oauth/oauthClient'
+
import { getAppContext } from './getAppContext'
+/**
+ * Resolve a backend-served asset path (e.g. `/uploaded_media/<id>`) to a full URL. These resources
+ * live on the backend, not the SPA bundle's origin — so in OAuth mode, where the app runs against a
+ * remote region, prefix that region's host. Same-origin (session) mode returns the path unchanged.
+ * Already-absolute URLs and `data:` URIs pass through untouched.
+ */
+export function backendAssetUrl(path: string): string {
+ if (/^(https?:|data:)/.test(path)) {
+ return path
+ }
+ const backendHost = getBackendHost()
+ return backendHost ? `${backendHost}${path}` : path
+}
+
export function apiHostOrigin(): string {
const appOrigin = window.location.origin
if (appOrigin === 'https://us.posthog.com') {
diff --git a/frontend/src/lib/utils/getAppContext.ts b/frontend/src/lib/utils/getAppContext.ts
index 517b8427e35d..dc0900d6c3aa 100644
--- a/frontend/src/lib/utils/getAppContext.ts
+++ b/frontend/src/lib/utils/getAppContext.ts
@@ -1,3 +1,5 @@
+import { isOAuthMode } from 'lib/oauth/oauthClient'
+
import { AppContext, OrganizationType, PathType, TeamType, UserType } from '~/types'
declare global {
@@ -8,6 +10,11 @@ declare global {
}
export function getAppContext(): AppContext | undefined {
+ // When logged into a remote cloud region over OAuth, ignore the local backend's
+ // server-rendered context so the whole app bootstraps from the remote region instead.
+ if (isOAuthMode()) {
+ return undefined
+ }
return window.POSTHOG_APP_CONTEXT || undefined
}
diff --git a/frontend/src/loadPostHogJS.tsx b/frontend/src/loadPostHogJS.tsx
index 01f98aa8500e..b17cc8983a9d 100644
--- a/frontend/src/loadPostHogJS.tsx
+++ b/frontend/src/loadPostHogJS.tsx
@@ -2,6 +2,7 @@ import posthog, { BeforeSendFn, PostHogInterface, SessionRecordingOptions } from
import { sampleOnProperty } from 'posthog-js/lib/src/extensions/sampling'
import { FEATURE_FLAGS } from 'lib/constants'
+import { isOAuthMode } from 'lib/oauth/oauthClient'
import { inStorybook, inStorybookTestRunner } from 'lib/utils/dom'
import { startDetachedElementTracking } from './detachedElementTracker'
@@ -161,7 +162,10 @@ export function loadPostHogJS(options: LoadPostHogJSOptions = {}): void {
...options.sessionRecording,
},
person_profiles: 'always',
- tracing_headers: ['eu.posthog.com', 'us.posthog.com'],
+ // posthog-js patches fetch to add X-POSTHOG-* tracing headers to these hosts. In OAuth
+ // mode the app's own /api calls go cross-origin to one of them, where the cloud CORS
+ // allowlist rejects those headers — so disable the feature then.
+ tracing_headers: isOAuthMode() ? [] : ['eu.posthog.com', 'us.posthog.com'],
__preview_disable_xhr_credentials: true,
capture_performance: {
//disabling to investigate if this is associated with memory leak in the posthog app
diff --git a/frontend/src/scenes/App.tsx b/frontend/src/scenes/App.tsx
index ded273c5cbb0..ff85fb1bb93c 100644
--- a/frontend/src/scenes/App.tsx
+++ b/frontend/src/scenes/App.tsx
@@ -9,6 +9,8 @@ import { KeaDevtools } from 'lib/KeaDevTools'
import { ToastCloseButton } from 'lib/lemon-ui/LemonToast/LemonToast'
import { SpinnerOverlay } from 'lib/lemon-ui/Spinner/Spinner'
import { autofillReleaseLogic } from 'lib/memory/autofillReleaseLogic'
+import { OAuthCallback } from 'lib/oauth/OAuthCallback'
+import { oauthLogic } from 'lib/oauth/oauthLogic'
import { appLogic } from 'scenes/appLogic'
import { appScenes } from 'scenes/appScenes'
import { sceneLogic } from 'scenes/sceneLogic'
@@ -51,9 +53,18 @@ export function App(): JSX.Element | null {
useMountedLogic(sceneLogic({ scenes: appScenes }))
useMountedLogic(autofillReleaseLogic)
+ // Unconditional so /oauth/callback's urlToAction is registered before routing. Inert in prod
+ // (OAuth UI gated on preflight.is_debug); no timers/listeners, so cheap to always mount.
+ useMountedLogic(oauthLogic)
useThemedHtml()
+ // A cloud OAuth redirect lands at /oauth/callback on the local origin. Render the exchange
+ // screen here (oauthLogic's urlToAction performs the token exchange), before normal routing.
+ if (window.location.pathname === '/oauth/callback') {
+ return <OAuthCallback />
+ }
+
if (showApp) {
return (
<>
diff --git a/frontend/src/scenes/authentication/shared/RegionSelect.tsx b/frontend/src/scenes/authentication/shared/RegionSelect.tsx
index 3486926279d7..cdac4a45b453 100644
--- a/frontend/src/scenes/authentication/shared/RegionSelect.tsx
+++ b/frontend/src/scenes/authentication/shared/RegionSelect.tsx
@@ -1,12 +1,14 @@
-import { useValues } from 'kea'
+import clsx from 'clsx'
+import { useActions, useValues } from 'kea'
import { router } from 'kea-router'
import { useState } from 'react'
import { IconCheckCircle } from '@posthog/icons'
-import { LemonModal, LemonSelect } from '@posthog/lemon-ui'
+import { LemonModal, LemonSelect, LemonTag } from '@posthog/lemon-ui'
import { CLOUD_HOSTNAMES } from 'lib/constants'
import { LemonField } from 'lib/lemon-ui/LemonField'
+import { oauthLogic } from 'lib/oauth/oauthLogic'
import { preflightLogic } from 'scenes/PreflightCheck/preflightLogic'
import { Region } from '~/types'
@@ -67,10 +69,41 @@ function WhyCloudModal({ setOpen, open }: { setOpen: (open: boolean) => void; op
)
}
-const RegionSelect = (): JSX.Element | null => {
+export default function RegionSelect(): JSX.Element | null {
const { preflight } = useValues(preflightLogic)
+ const { loginInProgress } = useValues(oauthLogic)
+ const { beginLogin } = useActions(oauthLogic)
const [regionModalOpen, setRegionModalOpen] = useState(false)
+ // Local dev: offer signing into a remote cloud region over OAuth, styled like the PostHog Code
+ // desktop region picker. Keeping "Local" uses the usual session-cookie form below; picking
+ // US/EU kicks off the OAuth flow against that region.
+ if (preflight?.is_debug) {
+ return (
+ <div className="flex flex-col gap-2">
+ <div className="grid grid-cols-2 gap-2">
+ <RegionCard
+ flag="🇺🇸"
+ label="US Cloud"
+ hint="us.posthog.com"
+ isOAuth
+ disabled={loginInProgress}
+ onClick={() => beginLogin(Region.US)}
+ />
+ <RegionCard
+ flag="🇪🇺"
+ label="EU Cloud"
+ hint="eu.posthog.com"
+ isOAuth
+ disabled={loginInProgress}
+ onClick={() => beginLogin(Region.EU)}
+ />
+ </div>
+ <RegionCard flag="💻" label="Local (this instance)" hint="Log in with the form below" selected />
+ </div>
+ )
+ }
+
if (!preflight?.cloud || !preflight?.region) {
return null
}
@@ -107,4 +140,45 @@ const RegionSelect = (): JSX.Element | null => {
)
}
-export default RegionSelect
+function RegionCard({
+ flag,
+ label,
+ hint,
+ isOAuth,
+ selected = false,
+ disabled = false,
+ onClick,
+}: {
+ flag: string
+ label: string
+ hint: string
+ isOAuth?: boolean
+ selected?: boolean
+ disabled?: boolean
+ onClick?: () => void
+}): JSX.Element {
+ return (
+ <button
+ type="button"
+ aria-pressed={selected}
+ onClick={onClick}
+ disabled={disabled || selected}
+ className={clsx(
+ 'flex w-full flex-col items-start gap-0.5 rounded border px-3 py-2 text-left transition-colors',
+ selected ? 'border-accent bg-accent-highlight' : 'border-primary hover:border-accent',
+ disabled && !selected ? 'cursor-not-allowed opacity-60' : !selected && 'cursor-pointer'
+ )}
+ >
+ <div className="flex w-full items-center gap-2">
+ <span className="text-lg leading-none">{flag}</span>
+ <span className="text-sm font-semibold">{label}</span>
+ {isOAuth && (
+ <LemonTag type="primary" size="small" className="ml-auto">
+ OAuth
+ </LemonTag>
+ )}
+ </div>
+ <span className="pl-6.75 text-xs text-secondary">{hint}</span>
+ </button>
+ )
+}
diff --git a/frontend/src/scenes/experiments/ExperimentView/VariantScreenshot.tsx b/frontend/src/scenes/experiments/ExperimentView/VariantScreenshot.tsx
index 4e4033757244..ce914c98f844 100644
--- a/frontend/src/scenes/experiments/ExperimentView/VariantScreenshot.tsx
+++ b/frontend/src/scenes/experiments/ExperimentView/VariantScreenshot.tsx
@@ -14,6 +14,7 @@ import {
import { ZoomableImage } from 'lib/components/ZoomableImage/ZoomableImage'
import { useUploadFiles } from 'lib/hooks/useUploadFiles'
+import { backendAssetUrl } from 'lib/utils/apiHost'
import { experimentLogic } from '../experimentLogic'
import { VariantTag } from './VariantTag'
@@ -144,7 +145,7 @@ export function VariantScreenshot({
const widthClass = getThumbnailWidth()
const getMediaSrc = (mediaId: string): string =>
- mediaId.startsWith('data:') ? mediaId : `/uploaded_media/${mediaId}`
+ mediaId.startsWith('data:') ? mediaId : backendAssetUrl(`/uploaded_media/${mediaId}`)
const showPrevious = (): void =>
setSelectedImageIndex((prev) => (prev === null ? prev : (prev - 1 + mediaIds.length) % mediaIds.length))
diff --git a/frontend/src/scenes/product-tours/editor/StepScreenshotThumbnail.tsx b/frontend/src/scenes/product-tours/editor/StepScreenshotThumbnail.tsx
index 9c062c7055f1..812a9356493f 100644
--- a/frontend/src/scenes/product-tours/editor/StepScreenshotThumbnail.tsx
+++ b/frontend/src/scenes/product-tours/editor/StepScreenshotThumbnail.tsx
@@ -2,6 +2,8 @@ import { useState } from 'react'
import { LemonModal } from '@posthog/lemon-ui'
+import { backendAssetUrl } from 'lib/utils/apiHost'
+
export interface StepScreenshotThumbnailProps {
mediaId: string
}
@@ -22,7 +24,7 @@ export function StepScreenshotThumbnail({ mediaId }: StepScreenshotThumbnailProp
onClick={() => setShowScreenshotModal(true)}
>
<img
- src={`/uploaded_media/${mediaId}`}
+ src={backendAssetUrl(`/uploaded_media/${mediaId}`)}
alt="Element screenshot"
className="w-full h-full object-cover"
title="Click to view screenshot"
@@ -37,7 +39,7 @@ export function StepScreenshotThumbnail({ mediaId }: StepScreenshotThumbnailProp
>
<div className="flex flex-col items-center justify-center gap-4">
<img
- src={`/uploaded_media/${mediaId}`}
+ src={backendAssetUrl(`/uploaded_media/${mediaId}`)}
alt="Element screenshot"
className="max-w-full max-h-[70vh]"
/>
diff --git a/frontend/src/scenes/userLogic.ts b/frontend/src/scenes/userLogic.ts
index d53dda4789d5..fd59e37bca13 100644
--- a/frontend/src/scenes/userLogic.ts
+++ b/frontend/src/scenes/userLogic.ts
@@ -8,6 +8,7 @@ import api, { getCookie } from 'lib/api'
import { DashboardCompatibleScenes } from 'lib/components/SceneDashboardChoice/sceneDashboardChoiceModalLogic'
// eslint-disable-next-line import/no-cycle
import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'
+import { clearSession, isOAuthMode } from 'lib/oauth/oauthClient'
import { getAppContext } from 'lib/utils/getAppContext'
import { sidePanelStateLogic } from '~/layout/navigation-3000/sidepanel/sidePanelStateLogic'
@@ -260,6 +261,14 @@ export const userLogic = kea<userLogicType>([
cache.loggingOut = true
posthog.reset()
+ // OAuth mode: there's no local Django session to end — just drop the stored cloud
+ // token and return to the local login. (A cross-origin /logout POST would do nothing.)
+ if (isOAuthMode()) {
+ clearSession()
+ window.location.href = '/login'
+ return
+ }
+
const form = document.createElement('form')
form.method = 'POST'
form.action = '/logout'
diff --git a/posthog/urls.py b/posthog/urls.py
index 335d7dd94504..e1c565fa85b7 100644
--- a/posthog/urls.py
+++ b/posthog/urls.py
@@ -507,6 +507,9 @@ frontend_unauthenticated_routes = [
"unsubscribe",
"verify_email",
r"agentic/account-mismatch",
+ # OAuth redirect target when logging the local frontend into a remote cloud region;
+ # the SPA handles the code→token exchange client-side, so it must load without auth.
+ r"^oauth/callback",
]
for route in frontend_unauthenticated_routes:
urlpatterns.append(re_path(route, home))
diff --git a/posthog/views.py b/posthog/views.py
index 31183d778018..00bfcb40aedf 100644
--- a/posthog/views.py
+++ b/posthog/views.py
@@ -85,6 +85,10 @@ def login_required(view):
@wraps(view)
def handler(request, *args, **kwargs):
+ # Dev-only: in cloud-OAuth mode the session is client-side, so serve without a local login
+ # (the SPA uses its bearer token). DEBUG-gated, so prod gating is unchanged.
+ if settings.DEBUG and request.COOKIES.get("ph_oauth_mode"):
+ return view(request, *args, **kwargs)
if not User.objects.exists():
return redirect("/preflight")
elif not request.user.is_authenticated and settings.AUTO_LOGIN: