: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
feat(oauth): frame login and signup around a pending OAuth connection (#98561)
Rafael Audibert9aec9db7bc98
diff --git a/docs/published/handbook/engineering/oauth-development-guide.md b/docs/published/handbook/engineering/oauth-development-guide.mdindex 57caaf4d7227..29f6606b091d 100644--- a/docs/published/handbook/engineering/oauth-development-guide.md+++ b/docs/published/handbook/engineering/oauth-development-guide.md@@ -322,6 +322,21 @@ tokens = token_response.json()print(tokens)```+## Signed-out visitors++`/oauth/authorize/` needs a session. A visitor without one is redirected to `/login?next=<the authorize URL>`. The login, signup, and email verification screens keep `next`, so the visitor lands on the consent screen once they have a session, and `/oauth` paths are exempt from the onboarding redirect.++The redirect also sets the `ph_pending_oauth_connection` cookie so those screens can name the application:++- Value: percent-encoded JSON with `client_name` and `client_id`, plus `logo_uri` and `redirect_host` (host of the registered redirect URI, web redirects only) when known. It holds public application metadata only, the same the consent screen shows.+- Scope: `Domain=posthog.com` on PostHog Cloud, so the website can read it too. Host-only on any other host. `SameSite=Lax`, readable by JavaScript, lifetime 60 minutes.+- Cleared when the person grants or denies the authorization.+- A CIMD client seen for the first time has no application row yet, so the cookie carries the host of its `client_id` URL as the name.++While the cookie is present, the signup form pins the data region to the region the form is served from. An OAuth client is registered in one region only, so an account created in the other region could not finish the connection.++Analytics: the frontend captures `oauth pending connection viewed` with a `screen` property (`login`, `signup`, or `verify_email`). `user signed up` carries `signup_oauth_client_name` and `signup_oauth_client_id`, which are also set as person properties, so a signup can be traced back to the application that started it.+## Endpoints- **Authorization**: `/oauth/authorize/`diff --git a/frontend/src/lib/components/SignupReferralSource.tsx b/frontend/src/lib/components/SignupReferralSource.tsxindex 201ec897231c..7a470c908248 100644--- a/frontend/src/lib/components/SignupReferralSource.tsx+++ b/frontend/src/lib/components/SignupReferralSource.tsx@@ -1,4 +1,4 @@-import { useState } from 'react'+import { Field as KeaField } from 'kea-forms'import { LemonInput } from '@posthog/lemon-ui'@@ -75,8 +75,6 @@ const AI_REFERRAL_PATTERNS = [const AI_REFERRAL_PATTERN = new RegExp(`\\b(${AI_REFERRAL_PATTERNS.join('|')})\\b`, 'i')export default function SignupReferralSource({ disabled }: { disabled: boolean }): JSX.Element {- const [showAIPrompt, setShowAIPrompt] = useState(false)-return (<><LemonField name="referral_source" label="Where did you hear about us?" showOptional>@@ -87,28 +85,31 @@ export default function SignupReferralSource({ disabled }: { disabled: boolean }placeholder=""disabled={disabled}value={value ?? ''}- onChange={(val: string) => {- onChange(val)- setShowAIPrompt(AI_REFERRAL_PATTERN.test(val))- }}+ onChange={onChange}/>)}</LemonField>- <AnimatedCollapsible collapsed={!showAIPrompt}>- <LemonField- name="referral_source_ai_prompt"- label="What prompt or search led you to PostHog?"- help="Paste the prompt or search queries if you remember, even roughly"- showOptional- >- <LemonInput- className="ph-ignore-input"- data-attr="signup-referral-source-ai-prompt"- placeholder="e.g. Product analytics tool with error tracking"- disabled={disabled}- />- </LemonField>- </AnimatedCollapsible>+ {/* Subscribing here rather than in the parent keeps a keystroke from re-rendering the+ whole signup panel. */}+ <KeaField name="referral_source" noStyle>+ {({ value }) => (+ <AnimatedCollapsible collapsed={!AI_REFERRAL_PATTERN.test(value ?? '')}>+ <LemonField+ name="referral_source_ai_prompt"+ label="What prompt or search led you to PostHog?"+ help="Paste the prompt or search queries if you remember, even roughly"+ showOptional+ >+ <LemonInput+ className="ph-ignore-input"+ data-attr="signup-referral-source-ai-prompt"+ placeholder="e.g. Product analytics tool with error tracking"+ disabled={disabled}+ />+ </LemonField>+ </AnimatedCollapsible>+ )}+ </KeaField></>)}diff --git a/frontend/src/scenes/authentication/invite-signup/inviteSignupLogic.ts b/frontend/src/scenes/authentication/invite-signup/inviteSignupLogic.tsindex 8b885389cde6..e1346c4abaea 100644--- a/frontend/src/scenes/authentication/invite-signup/inviteSignupLogic.ts+++ b/frontend/src/scenes/authentication/invite-signup/inviteSignupLogic.ts@@ -3,11 +3,12 @@ import { MakeLogicType, actions, kea, listeners, path, reducers, selectors } froimport { forms } from 'kea-forms'import type { DeepPartial, DeepPartialMap, FieldName, ValidationErrorType } from 'kea-forms'import { loaders } from 'kea-loaders'-import { urlToAction } from 'kea-router'+import { router, urlToAction } from 'kea-router'import posthog from 'posthog-js'import api from 'lib/api'import { ValidatedPasswordResult, validatePassword } from 'lib/components/PasswordStrength'+import { getRelativeNextPath } from 'lib/utils/url'import { getPasskeyErrorMessage } from 'scenes/settings/user/passkeys/utils'import type { RegistrationBeginResponse } from 'scenes/settings/user/passkeySettingsLogic'@@ -312,6 +313,11 @@ export const inviteSignupLogic = kea<inviteSignupLogicType>([submitPayload.challenge_nonce = values.challengeNonce}+ const nextUrl = getRelativeNextPath(router.values.searchParams['next'], location)+ if (nextUrl) {+ submitPayload.next_url = nextUrl+ }+const res = await api.create(`api/signup/${values.invite.id}/`, submitPayload)location.href = res.redirect_url || '/' // hard refresh because the current_organization changed} catch (e) {diff --git a/frontend/src/scenes/authentication/login/Login.stories.tsx b/frontend/src/scenes/authentication/login/Login.stories.tsxindex b37a7eb3d110..cd3aa16b40bc 100644--- a/frontend/src/scenes/authentication/login/Login.stories.tsx+++ b/frontend/src/scenes/authentication/login/Login.stories.tsx@@ -1,3 +1,8 @@+import {+ PENDING_OAUTH_CONNECTION_FIXTURE,+ setPendingOAuthConnectionCookie,+} from 'scenes/authentication/shared/pendingOAuthConnection.mock'+import type { Meta, StoryFn } from '@storybook/react'import { useEffect } from 'react'@@ -16,6 +21,7 @@ type StoryArgs = {samlAvailable: booleanssoEnforcement: 'none' | 'google-oauth2' | 'github' | 'gitlab' | 'saml'generalError: 'none' | 'invalid_credentials' | 'code_based_verification_sent'+ pendingOAuthConnection: boolean}const meta: Meta<StoryArgs> = {@@ -42,6 +48,7 @@ const meta: Meta<StoryArgs> = {name: 'General error',options: ['none', 'invalid_credentials', 'code_based_verification_sent'],},+ pendingOAuthConnection: { control: 'boolean', name: 'Pending OAuth connection' },},args: {cloud: true,@@ -52,6 +59,7 @@ const meta: Meta<StoryArgs> = {samlAvailable: false,ssoEnforcement: 'none',generalError: 'none',+ pendingOAuthConnection: false,},}export default meta@@ -65,8 +73,11 @@ const Template: StoryFn<StoryArgs> = ({samlAvailable,ssoEnforcement,generalError,+ pendingOAuthConnection,}) => {const enforcement = ssoEnforcement === 'none' ? null : ssoEnforcement+ // Set synchronously: the scene reads the cookie while it mounts during this same render.+ setPendingOAuthConnectionCookie(pendingOAuthConnection ? PENDING_OAUTH_CONNECTION_FIXTURE : null)useStorybookMocks({get: {@@ -129,5 +140,9 @@ SAMLAvailable.args = { samlAvailable: true }export const LoginError: StoryFn<StoryArgs> = Template.bind({})LoginError.args = { generalError: 'invalid_credentials' }+export const PendingOAuthConnection: StoryFn<StoryArgs> = Template.bind({})+PendingOAuthConnection.storyName = 'Pending OAuth connection'+PendingOAuthConnection.args = { pendingOAuthConnection: true }+export const EmailVerification: StoryFn<StoryArgs> = Template.bind({})EmailVerification.args = { generalError: 'code_based_verification_sent' }diff --git a/frontend/src/scenes/authentication/login/Login.tsx b/frontend/src/scenes/authentication/login/Login.tsxindex 32c0ae443294..676345d10b79 100644--- a/frontend/src/scenes/authentication/login/Login.tsx+++ b/frontend/src/scenes/authentication/login/Login.tsx@@ -3,6 +3,7 @@ import { useEffect } from 'react'import { loginTelemetryLogic } from 'scenes/authentication/shared/loginTelemetryLogic'import { passkeyLogic } from 'scenes/authentication/shared/passkeyLogic'+import { pendingOAuthConnectionLogic } from 'scenes/authentication/shared/pendingOAuthConnectionLogic'import { SceneExport } from 'scenes/sceneTypes'import { LoginForm } from './LoginForm'@@ -16,6 +17,8 @@ export const scene: SceneExport = {export function Login(): JSX.Element {// Mounted here so the login funnel is only reported from the auth scenesuseMountedLogic(loginTelemetryLogic)+ // Mounted at the scene root so the cookie is read once, not on every form state change+ useMountedLogic(pendingOAuthConnectionLogic)const { startConditionalPasskeyLogin } = useActions(passkeyLogic)// WebKit (Safari/iOS) can't open the passkey modal without a user gesture, so we showdiff --git a/frontend/src/scenes/authentication/login/LoginForm.tsx b/frontend/src/scenes/authentication/login/LoginForm.tsxindex 09f392c3fc59..067ec3221343 100644--- a/frontend/src/scenes/authentication/login/LoginForm.tsx+++ b/frontend/src/scenes/authentication/login/LoginForm.tsx@@ -22,6 +22,7 @@ import { AuthScene, AuthSceneCard } from 'scenes/authentication/shared/authSceneimport { RegionField } from 'scenes/authentication/shared/authScene/RegionField'import { ERROR_MESSAGES } from 'scenes/authentication/shared/loginErrorMessages'import { OtherRegionHint } from 'scenes/authentication/shared/OtherRegionHint'+import { pendingOAuthConnectionLogic, reviewAccessCopy } from 'scenes/authentication/shared/pendingOAuthConnectionLogic'import { RedirectIfLoggedInOtherInstance } from 'scenes/authentication/shared/RedirectToLoggedInInstance'import { isValidVerificationCode, normalizeVerificationCode } from 'scenes/authentication/shared/verificationCode'import { VerificationCodeInput } from 'scenes/authentication/shared/VerificationCodeInput'@@ -120,6 +121,7 @@ export function LoginForm(): JSX.Element {availableLoginMethods,} = useValues(loginLogic)const { preflight } = useValues(preflightLogic)+ const { pendingConnection } = useValues(pendingOAuthConnectionLogic({ screen: 'login' }))const isPasswordHidden = !!precheckResponse.sso_enforcement || isPasswordLoginUnavailableconst isCodeSent = codeVerificationRequired@@ -162,9 +164,9 @@ export function LoginForm(): JSX.Element {<>{/* This whole fragment is deleted when the title flips to the code-sentstring, so even the separator space lives inside an element */}- <span>{'Log in to '}</span>+ <span>{pendingConnection ? 'Log in to connect ' : 'Log in to '}</span><span className="px-1 rounded-md bg-[color-mix(in_srgb,var(--color-blue-500)_10%,transparent)] text-[var(--color-blue-500)]">- @PostHog+ {pendingConnection ? pendingConnection.clientName : '@PostHog'}</span></>)@@ -175,6 +177,8 @@ export function LoginForm(): JSX.Element {For your security, we've emailed a 6-digit verification code to{' '}<strong>{codeVerificationEmail}</strong>.</>+ ) : pendingConnection ? (+ reviewAccessCopy(pendingConnection, 'After you log in')) : ("Welcome back. Let's go ship something.")diff --git a/frontend/src/scenes/authentication/shared/authScene/AuthScene.tsx b/frontend/src/scenes/authentication/shared/authScene/AuthScene.tsxindex a3624a195bff..82331b3e52d3 100644--- a/frontend/src/scenes/authentication/shared/authScene/AuthScene.tsx+++ b/frontend/src/scenes/authentication/shared/authScene/AuthScene.tsx@@ -1,11 +1,14 @@import './AuthScene.scss'+import { useValues } from 'kea'import { type ReactNode } from 'react'import { Logo } from 'lib/brand'import { cn } from 'lib/utils/css-classes'+import { pendingOAuthConnectionLogic } from '../pendingOAuthConnectionLogic'import { DevLoginPanel } from './DevLoginPanel'+import { PendingOAuthConnectionLogos } from './PendingOAuthConnectionLogos'import { Typewriter } from './Typewriter'export function AuthScene({ notes, children }: { notes: string[]; children: ReactNode }): JSX.Element {@@ -32,14 +35,18 @@ export function AuthSceneCard({footer?: ReactNodechildren: ReactNode}): JSX.Element {+ const { pendingConnection } = useValues(pendingOAuthConnectionLogic)+return (<>- {top === undefined ? (+ {top !== undefined ? (+ top+ ) : pendingConnection ? (+ <PendingOAuthConnectionLogos connection={pendingConnection} />+ ) : (<span className="AuthScene__logo block mb-4"><Logo variant="gradient" size="lg" /></span>- ) : (- top)}<div className="AuthScene__card w-full pt-8 px-5 sm:px-9 pb-8">{children}</div>{footer}diff --git a/frontend/src/scenes/authentication/shared/authScene/PendingOAuthConnectionLogos.tsx b/frontend/src/scenes/authentication/shared/authScene/PendingOAuthConnectionLogos.tsxnew file mode 100644index 000000000000..e8bb7f3e3bda--- /dev/null+++ b/frontend/src/scenes/authentication/shared/authScene/PendingOAuthConnectionLogos.tsx@@ -0,0 +1,36 @@+import { useState } from 'react'++import { IconPlug } from '@posthog/icons'++import { Logomark } from 'lib/brand'++import type { PendingOAuthConnection } from '../pendingOAuthConnectionLogic'++export function PendingOAuthConnectionLogos({ connection }: { connection: PendingOAuthConnection }): JSX.Element {+ const [logoFailed, setLogoFailed] = useState(false)+ const logoUri = logoFailed ? null : connection.logoUri++ return (+ <div className="flex items-center justify-center gap-3 mb-4" data-attr="pending-oauth-connection-logos">+ <span className="flex items-center justify-center w-12 h-12 p-2.5 rounded-full border border-border bg-bg-light">+ <Logomark variant="gradient" size="sm" />+ </span>+ <IconPlug className="text-secondary text-lg shrink-0" aria-hidden />+ <span className="flex items-center justify-center w-12 h-12 rounded-full border border-border bg-bg-light overflow-hidden">+ {logoUri ? (+ <img+ src={logoUri}+ alt={`${connection.clientName} logo`}+ className="w-8 h-8 object-contain"+ referrerPolicy="no-referrer"+ onError={() => setLogoFailed(true)}+ />+ ) : (+ <span className="text-lg font-semibold text-primary" aria-hidden>+ {connection.clientName.charAt(0).toUpperCase()}+ </span>+ )}+ </span>+ </div>+ )+}diff --git a/frontend/src/scenes/authentication/shared/authScene/RegionField.tsx b/frontend/src/scenes/authentication/shared/authScene/RegionField.tsxindex e536d19d087c..e5e5ef6cbe2b 100644--- a/frontend/src/scenes/authentication/shared/authScene/RegionField.tsx+++ b/frontend/src/scenes/authentication/shared/authScene/RegionField.tsx@@ -7,6 +7,7 @@ import { LemonLabel, LemonModal, LemonSelect, LemonSelectOptions } from '@posthoimport { CLOUD_HOSTNAMES } from 'lib/constants'import { countryCodeToFlag } from 'lib/utils/country'+import { pendingOAuthConnectionLogic } from 'scenes/authentication/shared/pendingOAuthConnectionLogic'import { preflightLogic } from 'scenes/PreflightCheck/preflightLogic'import { Region } from '~/types'@@ -84,6 +85,7 @@ const REGIONS: { value: Region; label: string }[] = [export function RegionField(): JSX.Element | null {const { preflight } = useValues(preflightLogic)+ const { pendingConnection } = useValues(pendingOAuthConnectionLogic)const [devRegion, setDevRegion] = useState<Region>(Region.US)const [modalOpen, setModalOpen] = useState(false)@@ -105,6 +107,12 @@ export function RegionField(): JSX.Element | null {setDevRegion(region)}+ // An OAuth client is registered in one region only, so an account created elsewhere could+ // never finish the connection that brought the person here.+ const pinnedReason = pendingConnection+ ? `This connection started in the ${REGIONS.find((r) => r.value === activeRegion)?.label ?? activeRegion} region. To use another region, start again from ${pendingConnection.clientName}.`+ : undefined+const options: LemonSelectOptions<Region> = REGIONS.map((region) => ({value: region.value,label: (@@ -124,6 +132,7 @@ export function RegionField(): JSX.Element | null {value={activeRegion}options={options}fullWidth+ disabledReason={pinnedReason}onChange={(value) => value && selectRegion(value)}renderButtonContent={(leaf) => {const region = leaf?.value ?? activeRegion@@ -135,6 +144,7 @@ export function RegionField(): JSX.Element | null {)}}/>+ {pinnedReason && <p className="m-0 text-xs text-secondary">{pinnedReason}</p>}</div></>)diff --git a/frontend/src/scenes/authentication/shared/pendingOAuthConnection.mock.ts b/frontend/src/scenes/authentication/shared/pendingOAuthConnection.mock.tsnew file mode 100644index 000000000000..b7f8ab3d43b4--- /dev/null+++ b/frontend/src/scenes/authentication/shared/pendingOAuthConnection.mock.ts@@ -0,0 +1,19 @@+import { PENDING_OAUTH_CONNECTION_COOKIE } from './pendingOAuthConnectionLogic'++export const PENDING_OAUTH_CONNECTION_FIXTURE = {+ client_name: 'Claude',+ client_id: 'https://claude.example.com/.well-known/oauth-client',+ logo_uri: 'https://claude.example.com/logo.png',+ redirect_host: 'claude.example.com',+}++/** A string is written raw, so a test can pass a malformed value. An object is encoded the way+ * the backend encodes it. */+export function setPendingOAuthConnectionCookie(connection: object | string | null): void {+ if (connection === null) {+ document.cookie = `${PENDING_OAUTH_CONNECTION_COOKIE}=; max-age=0; path=/`+ return+ }+ const raw = typeof connection === 'string' ? connection : encodeURIComponent(JSON.stringify(connection))+ document.cookie = `${PENDING_OAUTH_CONNECTION_COOKIE}=${raw}; path=/`+}diff --git a/frontend/src/scenes/authentication/shared/pendingOAuthConnectionLogic.test.ts b/frontend/src/scenes/authentication/shared/pendingOAuthConnectionLogic.test.tsnew file mode 100644index 000000000000..c7aba995ef9d--- /dev/null+++ b/frontend/src/scenes/authentication/shared/pendingOAuthConnectionLogic.test.ts@@ -0,0 +1,95 @@+import { setPendingOAuthConnectionCookie as setCookie } from './pendingOAuthConnection.mock'++import { router } from 'kea-router'+import { expectLogic } from 'kea-test-utils'+import posthog from 'posthog-js'++import { initKeaTests } from '~/test/init'++import { pendingOAuthConnectionLogic, readPendingOAuthConnection } from './pendingOAuthConnectionLogic'++jest.mock('posthog-js')++const CLIENT_ID = 'https://claude.example.com/.well-known/oauth-client'++function encoded(payload: unknown): string {+ return encodeURIComponent(JSON.stringify(payload))+}++describe('pendingOAuthConnectionLogic', () => {+ beforeEach(() => {+ initKeaTests()+ setCookie(null)+ jest.mocked(posthog.capture).mockClear()+ })++ it('reads the cookie the authorize endpoint set and reports which screen showed it', async () => {+ setCookie({+ client_name: 'Claude & Co',+ client_id: CLIENT_ID,+ logo_uri: 'https://claude.example.com/logo.png',+ redirect_host: 'claude.example.com',+ })+ router.actions.push('/login')+ const logic = pendingOAuthConnectionLogic()+ logic.mount()++ await expectLogic(logic).toMatchValues({+ pendingConnection: {+ clientName: 'Claude & Co',+ clientId: CLIENT_ID,+ logoUri: 'https://claude.example.com/logo.png',+ redirectHost: 'claude.example.com',+ },+ })+ expect(posthog.capture).toHaveBeenCalledTimes(1)+ expect(posthog.capture).toHaveBeenCalledWith('oauth pending connection viewed', {+ screen: 'login',+ client_name: 'Claude & Co',+ client_id: CLIENT_ID,+ })+ })++ it('reports nothing when no connection is pending', async () => {+ router.actions.push('/signup')+ const logic = pendingOAuthConnectionLogic()+ logic.mount()++ await expectLogic(logic).toMatchValues({ pendingConnection: null })+ expect(posthog.capture).not.toHaveBeenCalled()+ })++ it('reports nothing from a screen outside the auth flow', async () => {+ setCookie({ client_name: 'Claude', client_id: CLIENT_ID })+ router.actions.push('/organization/confirm-creation')+ const logic = pendingOAuthConnectionLogic()+ logic.mount()++ await expectLogic(logic).toMatchValues({+ pendingConnection: expect.objectContaining({ clientName: 'Claude' }),+ })+ expect(posthog.capture).not.toHaveBeenCalled()+ })++ it.each([+ ['not JSON', 'nope'],+ ['not an object', encoded([])],+ ['missing client_id', encoded({ client_name: 'Claude' })],+ ['empty client_name', encoded({ client_name: '', client_id: CLIENT_ID })],+ ])('treats a cookie that is %s as no pending connection', (_name, raw) => {+ setCookie(raw)++ expect(readPendingOAuthConnection()).toBeNull()+ })++ it('keeps the connection but drops a logo that is not an https URL', () => {+ setCookie(encoded({ client_name: 'Cursor', client_id: 'cursor', logo_uri: 'data:image/png;base64,AAAA' }))++ expect(readPendingOAuthConnection()).toEqual({+ clientName: 'Cursor',+ clientId: 'cursor',+ logoUri: null,+ redirectHost: null,+ })+ })+})diff --git a/frontend/src/scenes/authentication/shared/pendingOAuthConnectionLogic.ts b/frontend/src/scenes/authentication/shared/pendingOAuthConnectionLogic.tsnew file mode 100644index 000000000000..d29033009f61--- /dev/null+++ b/frontend/src/scenes/authentication/shared/pendingOAuthConnectionLogic.ts@@ -0,0 +1,125 @@+import { decode } from 'he'+import { LogicWrapper, MakeLogicType, actions, afterMount, kea, path, reducers } from 'kea'+import { router } from 'kea-router'+import posthog from 'posthog-js'++import { getCookie } from 'lib/api'+import { tryJsonParse } from 'lib/utils/json'+import { urls } from 'scenes/urls'++// pinned: the backend sets this cookie (posthog/helpers/oauth_pending_connection.py) and the website reads it+export const PENDING_OAUTH_CONNECTION_COOKIE = 'ph_pending_oauth_connection'++// pinned: analytics property value on `oauth pending connection viewed`+export type PendingOAuthConnectionScreen = 'login' | 'signup' | 'verify_email'++/** The OAuth application a signed-out visitor was asked to authorize before they reached login or signup. */+export interface PendingOAuthConnection {+ clientName: string+ clientId: string+ logoUri: string | null+ /** Host the person returns to when the connection completes, when the client registered a web redirect. */+ redirectHost: string | null+}++function optionalString(value: unknown): string | null {+ return typeof value === 'string' && value ? value : null+}++export function readPendingOAuthConnection(): PendingOAuthConnection | null {+ const raw = getCookie(PENDING_OAUTH_CONNECTION_COOKIE)+ if (!raw) {+ return null+ }+ const parsed = tryJsonParse(raw, null)+ if (!parsed || typeof parsed !== 'object') {+ return null+ }+ const payload = parsed as Record<string, unknown>+ const clientName = optionalString(payload.client_name)+ const clientId = optionalString(payload.client_id)+ if (!clientName || !clientId) {+ return null+ }+ const logoUri = optionalString(payload.logo_uri)+ return {+ // The name is HTML-escaped at ingestion (posthog/api/oauth/client_name.py). Decode it so+ // React's own output escaping renders "&" instead of "&".+ clientName: decode(clientName),+ clientId,+ // Only a web image can render on an https page, so data: and http: URIs are dropped.+ logoUri: logoUri?.startsWith('https://') ? logoUri : null,+ redirectHost: optionalString(payload.redirect_host),+ }+}++/** `lead` opens the sentence, for example "After you log in". */+export function reviewAccessCopy(connection: PendingOAuthConnection, lead: string): string {+ const back = connection.redirectHost ? `, then go back to ${connection.redirectHost}` : ''+ return `${lead}, you'll review what ${connection.clientName} can access${back}.`+}++/** Taken from the path so that a component mounting this logic outside the three auth screens+ * cannot label the event as one of them. */+function screenForPath(pathname: string): PendingOAuthConnectionScreen | null {+ if (pathname === urls.login()) {+ return 'login'+ }+ if (pathname === urls.signup()) {+ return 'signup'+ }+ if (pathname.startsWith(urls.verifyEmail())) {+ return 'verify_email'+ }+ return null+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface pendingOAuthConnectionLogicValues {+ pendingConnection: PendingOAuthConnection | null+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface pendingOAuthConnectionLogicActions {+ setPendingConnection: (pendingConnection: PendingOAuthConnection) => {+ pendingConnection: PendingOAuthConnection+ }+}++export type pendingOAuthConnectionLogicType = MakeLogicType<+ pendingOAuthConnectionLogicValues,+ pendingOAuthConnectionLogicActions+>++/** One instance for the whole auth flow, so a panel change inside a scene does not re-read the+ * cookie or report the view again. */+export const pendingOAuthConnectionLogic: LogicWrapper<pendingOAuthConnectionLogicType> =+ kea<pendingOAuthConnectionLogicType>([+ path(['scenes', 'authentication', 'shared', 'pendingOAuthConnectionLogic']),+ actions({+ setPendingConnection: (pendingConnection: PendingOAuthConnection) => ({ pendingConnection }),+ }),+ reducers({+ pendingConnection: [+ null as PendingOAuthConnection | null,+ {+ setPendingConnection: (_, { pendingConnection }) => pendingConnection,+ },+ ],+ }),+ afterMount(({ actions }) => {+ const pendingConnection = readPendingOAuthConnection()+ if (!pendingConnection) {+ return+ }+ actions.setPendingConnection(pendingConnection)+ const screen = screenForPath(router.values.location.pathname)+ if (screen) {+ posthog.capture('oauth pending connection viewed', {+ screen,+ client_name: pendingConnection.clientName,+ client_id: pendingConnection.clientId,+ })+ }+ }),+ ])diff --git a/frontend/src/scenes/authentication/signup/Signup.stories.tsx b/frontend/src/scenes/authentication/signup/Signup.stories.tsxindex f93a838d1363..1339c1fe3e8d 100644--- a/frontend/src/scenes/authentication/signup/Signup.stories.tsx+++ b/frontend/src/scenes/authentication/signup/Signup.stories.tsx@@ -1,3 +1,8 @@+import {+ PENDING_OAUTH_CONNECTION_FIXTURE,+ setPendingOAuthConnectionCookie,+} from 'scenes/authentication/shared/pendingOAuthConnection.mock'+import type { Meta, StoryFn } from '@storybook/react'import { HttpResponse, delay } from 'msw'import { useEffect } from 'react'@@ -26,6 +31,7 @@ type StoryArgs = {github: booleangitlab: booleanpanel: PanelOption+ pendingOAuthConnection: boolean}const meta: Meta<StoryArgs> = {@@ -57,6 +63,7 @@ const meta: Meta<StoryArgs> = {name: 'Step',options: ['1: Email', '2: Password', '3: Profile'] satisfies PanelOption[],},+ pendingOAuthConnection: { control: 'boolean', name: 'Pending OAuth connection' },},args: {cloud: true,@@ -65,12 +72,23 @@ const meta: Meta<StoryArgs> = {github: true,gitlab: true,panel: '1: Email',+ pendingOAuthConnection: false,},}export default meta-const Template: StoryFn<StoryArgs> = ({ cloud, region, googleOAuth, github, gitlab, panel: panelOption }) => {+const Template: StoryFn<StoryArgs> = ({+ cloud,+ region,+ googleOAuth,+ github,+ gitlab,+ panel: panelOption,+ pendingOAuthConnection,+}) => {const panel = PANEL_INDEX[panelOption]+ // Set synchronously: the scene reads the cookie while it mounts during this same render.+ setPendingOAuthConnectionCookie(pendingOAuthConnection ? PENDING_OAUTH_CONNECTION_FIXTURE : null)useStorybookMocks({get: {'/_preflight': {@@ -112,3 +130,7 @@ PasswordStep.args = { panel: '2: Password' }export const ProfileStep: StoryFn<StoryArgs> = Template.bind({})ProfileStep.args = { panel: '3: Profile' }++export const PendingOAuthConnection: StoryFn<StoryArgs> = Template.bind({})+PendingOAuthConnection.storyName = 'Pending OAuth connection'+PendingOAuthConnection.args = { pendingOAuthConnection: true }diff --git a/frontend/src/scenes/authentication/signup/Signup.tsx b/frontend/src/scenes/authentication/signup/Signup.tsxindex df9a045b82db..4d7153bd231a 100644--- a/frontend/src/scenes/authentication/signup/Signup.tsx+++ b/frontend/src/scenes/authentication/signup/Signup.tsx@@ -1,4 +1,4 @@-import { useActions, useValues } from 'kea'+import { useActions, useMountedLogic, useValues } from 'kea'import { Form } from 'kea-forms'import { useState } from 'react'@@ -16,6 +16,7 @@ import { Link } from 'lib/lemon-ui/Link'import { AuthCardTitle } from 'scenes/authentication/shared/authScene/AuthCardTitle'import { AuthScene, AuthSceneCard } from 'scenes/authentication/shared/authScene/AuthScene'import { RegionField } from 'scenes/authentication/shared/authScene/RegionField'+import { pendingOAuthConnectionLogic, reviewAccessCopy } from 'scenes/authentication/shared/pendingOAuthConnectionLogic'import { TurnstileChallenge } from 'scenes/authentication/signup/signupForm/TurnstileChallenge'import { preflightLogic } from 'scenes/PreflightCheck/preflightLogic'import { SceneExport } from 'scenes/sceneTypes'@@ -43,6 +44,7 @@ function SignupEmailPanel(): JSX.Element {const { isSignupPanelEmailSubmitting, signupPanelEmailManualErrors, pendingInvite, loginUrl, emailCaseNotice } =useValues(signupLogic)const { preflight } = useValues(preflightLogic)+ const { pendingConnection } = useValues(pendingOAuthConnectionLogic)const [showJoinOrg, setShowJoinOrg] = useState(false)const lastLoginMethod = getCookie('ph_last_login_method') as LoginMethod | nullconst accountExists = !!signupPanelEmailManualErrors?.email@@ -66,7 +68,16 @@ function SignupEmailPanel(): JSX.Element {return (<AuthSceneCard footer={footer}>- <AuthCardTitle title="Get started" sub="Make your product self-driving." />+ <AuthCardTitle+ title={+ pendingConnection ? `Create your account to connect ${pendingConnection.clientName}` : 'Get started'+ }+ sub={+ pendingConnection+ ? reviewAccessCopy(pendingConnection, 'Once your account is ready')+ : 'Make your product self-driving.'+ }+ /><Form logic={signupLogic} formKey="signupPanelEmail" enableFormOnSubmit className="flex flex-col gap-4"><RegionField /><LemonField@@ -469,6 +480,8 @@ function SignupProfilePanel(): JSX.Element {export function Signup(): JSX.Element | null {const { user } = useValues(userLogic)const { panel } = useValues(signupLogic)+ // Mounted at the scene root so the cookie is read once, not on every panel change+ useMountedLogic(pendingOAuthConnectionLogic)if (user) {return nulldiff --git a/frontend/src/scenes/authentication/signup/signupForm/signupLogic.test.ts b/frontend/src/scenes/authentication/signup/signupForm/signupLogic.test.tsindex cdcebf5b6783..f7c9627b2f97 100644--- a/frontend/src/scenes/authentication/signup/signupForm/signupLogic.test.ts+++ b/frontend/src/scenes/authentication/signup/signupForm/signupLogic.test.ts@@ -1,3 +1,5 @@+import { setPendingOAuthConnectionCookie } from 'scenes/authentication/shared/pendingOAuthConnection.mock'+import { router } from 'kea-router'import { expectLogic } from 'kea-test-utils'@@ -346,3 +348,25 @@ describe('signupLogic — name handling', () => {expect(logic.values.panel).toBe(2)})})++describe('signupLogic - pending OAuth connection', () => {+ afterEach(() => {+ setPendingOAuthConnectionCookie(null)+ })++ it.each([+ ['prefills the referral source with the client name', 'Claude', 'Claude'],+ ['leaves the referral source empty without a connection', null, ''],+ ])('%s', async (_name, clientName, expected) => {+ setPendingOAuthConnectionCookie(clientName ? { client_name: clientName, client_id: 'client' } : null)+ initKeaTests()+ router.actions.push('/signup')+ const logic = signupLogic()+ logic.mount()++ await expectLogic(logic).toMatchValues({+ signupPanelOnboarding: expect.objectContaining({ referral_source: expected }),+ })+ logic.unmount()+ })+})diff --git a/frontend/src/scenes/authentication/signup/signupForm/signupLogic.ts b/frontend/src/scenes/authentication/signup/signupForm/signupLogic.tsindex e4cd28cfd14c..ca850a874784 100644--- a/frontend/src/scenes/authentication/signup/signupForm/signupLogic.ts+++ b/frontend/src/scenes/authentication/signup/signupForm/signupLogic.ts@@ -13,6 +13,7 @@ import { CLOUD_HOSTNAMES, FEATURE_FLAGS } from 'lib/constants'import { featureFlagLogic } from 'lib/logic/featureFlagLogic'import { splitFullName } from 'lib/utils/strings'import { getRelativeNextPath } from 'lib/utils/url'+import { readPendingOAuthConnection } from 'scenes/authentication/shared/pendingOAuthConnectionLogic'import {clearPendingVerificationEmail,setPendingVerificationEmail,@@ -485,7 +486,8 @@ export const signupLogic = kea<signupLogicType>([name: '',organization_name: '',role_at_organization: '',- referral_source: '',+ // The partner that started the OAuth connection is where this person heard about PostHog+ referral_source: readPendingOAuthConnection()?.clientName ?? '',referral_source_ai_prompt: '',} as SignupPanelOnboardingForm,errors: ({ name, role_at_organization }) => ({diff --git a/frontend/src/scenes/authentication/verify-email/VerifyEmail.tsx b/frontend/src/scenes/authentication/verify-email/VerifyEmail.tsxindex 9d753566fc4a..764394b78c93 100644--- a/frontend/src/scenes/authentication/verify-email/VerifyEmail.tsx+++ b/frontend/src/scenes/authentication/verify-email/VerifyEmail.tsx@@ -1,3 +1,6 @@+import { useMountedLogic } from 'kea'++import { pendingOAuthConnectionLogic } from 'scenes/authentication/shared/pendingOAuthConnectionLogic'import { SceneExport } from 'scenes/sceneTypes'import { VerifyEmailForm } from './VerifyEmailForm'@@ -9,5 +12,7 @@ export const scene: SceneExport = {}export function VerifyEmail(): JSX.Element {+ // Mounted at the scene root so the cookie is read once, not on every view change+ useMountedLogic(pendingOAuthConnectionLogic)return <VerifyEmailForm />}diff --git a/frontend/src/scenes/authentication/verify-email/VerifyEmailForm.tsx b/frontend/src/scenes/authentication/verify-email/VerifyEmailForm.tsxindex 7565d9cda9f8..951e7604457d 100644--- a/frontend/src/scenes/authentication/verify-email/VerifyEmailForm.tsx+++ b/frontend/src/scenes/authentication/verify-email/VerifyEmailForm.tsx@@ -11,6 +11,7 @@ import { LemonBanner } from 'lib/lemon-ui/LemonBanner'import { LemonButton } from 'lib/lemon-ui/LemonButton'import { Link } from 'lib/lemon-ui/Link'import { AuthScene, AuthSceneCard } from 'scenes/authentication/shared/authScene/AuthScene'+import { pendingOAuthConnectionLogic, reviewAccessCopy } from 'scenes/authentication/shared/pendingOAuthConnectionLogic'import { getPendingVerificationEmail, isValidVerificationCode } from 'scenes/authentication/shared/verificationCode'import { VerificationCodeInput } from 'scenes/authentication/shared/VerificationCodeInput'import { urls } from 'scenes/urls'@@ -169,6 +170,7 @@ function VerificationCodeEntry(): JSX.Element {function CheckYourInbox(): JSX.Element {const { uuid, user, reason, verificationEmailSent } = useValues(verifyEmailLogic)+ const { pendingConnection } = useValues(pendingOAuthConnectionLogic)// The address that received the code. This is the new address if an email change is pending,// else the account address. Without a session, for example on a fresh signup, the page uses the@@ -204,6 +206,11 @@ function CheckYourInbox(): JSX.Element {<>We sent you a 6-digit code. It's valid for 30 minutes.</>)}</p>+ {pendingConnection && (+ <p className="AuthScene__sub -mt-2 mb-4 text-sm text-secondary text-center text-pretty">+ {reviewAccessCopy(pendingConnection, 'After you verify')}+ </p>+ )}<VerificationCodeEntry /><div className="mt-3"><NotSeeingIt />@@ -214,6 +221,7 @@ function CheckYourInbox(): JSX.Element {export function VerifyEmailForm(): JSX.Element {const { view, verificationEmailSent } = useValues(verifyEmailLogic)+ const { pendingConnection } = useValues(pendingOAuthConnectionLogic)const { openSupportForm } = useActions(supportLogic)const noteKey = view === 'pending' && !verificationEmailSent ? 'send_failed' : (view ?? 'pending')@@ -226,10 +234,12 @@ export function VerifyEmailForm(): JSX.Element {<div className="flex flex-col items-center text-center"><HedgehogExplorer className="block w-auto mx-auto h-32" /><h1 className="m-0 mt-3 font-title text-2xl font-extrabold leading-tight text-primary text-center tracking-tight">- You're verified, go explore!+ {pendingConnection ? "You're verified" : "You're verified, go explore!"}</h1><p className="AuthScene__sub mt-2 mb-5 text-sm text-secondary text-center text-pretty">- Email confirmed. Next up: a quick setup. Your org, your team, your first events.+ {pendingConnection+ ? `Email confirmed. Next, review what ${pendingConnection.clientName} can access.`+ : 'Email confirmed. Next up: a quick setup. Your org, your team, your first events.'}</p><div className="AuthScene__progress mb-4 w-full h-1.5 overflow-hidden bg-[#e0e1d9] rounded-sm"><div className="AuthScene__progress-fill w-full h-full bg-warning rounded-sm" />diff --git a/frontend/src/scenes/organization/ConfirmOrganization/confirmOrganizationLogic.ts b/frontend/src/scenes/organization/ConfirmOrganization/confirmOrganizationLogic.tsindex c71353fff064..06d4ad6faa80 100644--- a/frontend/src/scenes/organization/ConfirmOrganization/confirmOrganizationLogic.ts+++ b/frontend/src/scenes/organization/ConfirmOrganization/confirmOrganizationLogic.ts@@ -6,6 +6,7 @@ import { urlToAction } from 'kea-router'import api from 'lib/api'import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'import { getRelativeNextPath } from 'lib/utils/url'+import { readPendingOAuthConnection } from 'scenes/authentication/shared/pendingOAuthConnectionLogic'export interface ConfirmOrganizationFormValues {organization_name?: string@@ -85,7 +86,6 @@ export type confirmOrganizationLogicType = MakeLogicType<export const confirmOrganizationLogic = kea<confirmOrganizationLogicType>([path(['scenes', 'organization', 'confirmOrganizationLogic']),-actions({setEmail: (email: string) => ({email,@@ -110,7 +110,10 @@ export const confirmOrganizationLogic = kea<confirmOrganizationLogicType>([forms(() => ({confirmOrganization: {- defaults: {} as ConfirmOrganizationFormValues,+ defaults: {+ // The partner that started the OAuth connection is where this person heard about PostHog+ referral_source: readPendingOAuthConnection()?.clientName ?? '',+ } as ConfirmOrganizationFormValues,errors: ({ organization_name, first_name }) => ({first_name: !first_name ? 'Please enter your name' : undefined,organization_name: !organization_name ? 'Please enter your organization name' : undefined,diff --git a/frontend/src/scenes/sceneLogic.tsx b/frontend/src/scenes/sceneLogic.tsxindex a48ee8bafbda..b409afc3895f 100644--- a/frontend/src/scenes/sceneLogic.tsx+++ b/frontend/src/scenes/sceneLogic.tsx@@ -794,11 +794,11 @@ export const sceneLogic = kea<sceneLogicType>([if (user) {// If user is already logged in, redirect away from unauthenticated-only routes (e.g. /signup)if (sceneConfig.onlyUnauthenticated) {- if (sceneId === Scene.Login) {- handleLoginRedirect()- } else {- router.actions.replace(urls.default())- }+ // `next` is where the person needs to end up, whichever screen they landed on:+ // an OAuth partner sends them to /signup?next=/oauth/authorize?... just as+ // `login_required` sends them to /login?next=... . With no `next` this lands on+ // the app root, so it covers the plain case too.+ handleLoginRedirect()return}diff --git a/posthog/api/oauth/test_views.py b/posthog/api/oauth/test_views.pyindex 0e91e3b995d2..2c8513e4cf45 100644--- a/posthog/api/oauth/test_views.py+++ b/posthog/api/oauth/test_views.py@@ -31,6 +31,11 @@ from posthog.api.oauth import OAuthAuthorizationSerializerfrom posthog.api.oauth.cimd import CIMD_SUPPORTED_AUTH_METHODSfrom posthog.api.oauth.client_assertion import CLIENT_ASSERTION_TYPE_JWT_BEARERfrom posthog.api.oauth.views import OAuthTokenView, OAuthValidator, _token_error_code+from posthog.helpers.oauth_pending_connection import (+ PENDING_OAUTH_CONNECTION_COOKIE,+ PENDING_OAUTH_CONNECTION_MAX_AGE_SECONDS,+ PendingOAuthConnection,+)from posthog.models.oauth import (OAuthAccessToken,OAuthApplication,@@ -187,6 +192,56 @@ class TestOAuthAPI(APIBaseTest):self.assertEqual(response.status_code, status.HTTP_302_FOUND)self.assertIn(f"/login?next=/oauth/authorize/", response["Location"])+ cookie = response.cookies[PENDING_OAUTH_CONNECTION_COOKIE]+ self.assertEqual(cookie["max-age"], PENDING_OAUTH_CONNECTION_MAX_AGE_SECONDS)+ self.assertEqual(cookie["samesite"], "Lax")+ self.assertFalse(cookie["httponly"])+ self.assertEqual(+ PendingOAuthConnection.from_cookie_value(cookie.value),+ PendingOAuthConnection(+ client_name="Test Confidential App",+ client_id="test_confidential_client_id",+ redirect_host="example.com",+ ),+ )++ @parameterized.expand(+ [+ ("unregistered_client_id", "no_such_client", None),+ (+ "unregistered_cimd_client_id",+ "https://client.example.com/.well-known/oauth-client",+ "client.example.com",+ ),+ ]+ )+ def test_authorize_login_redirect_cookie_for_unknown_client(self, _name, client_id, expected_client_name):+ self.client.logout()+ url = self.replace_param_in_url(self.base_authorization_url, "client_id", client_id)++ response = self.client.get(url)++ self.assertEqual(response.status_code, status.HTTP_302_FOUND)+ cookie = response.cookies.get(PENDING_OAUTH_CONNECTION_COOKIE)+ if expected_client_name is None:+ self.assertIsNone(cookie)+ return+ assert cookie is not None+ connection = PendingOAuthConnection.from_cookie_value(cookie.value)+ assert connection is not None+ self.assertEqual(connection.client_name, expected_client_name)+ # The redirect_uri in the query is unverified without an application row.+ self.assertIsNone(connection.redirect_host)++ @parameterized.expand([("granted", True), ("denied", False)])+ def test_authorize_decision_clears_pending_connection_cookie(self, _name, allow):+ self.client.cookies[PENDING_OAUTH_CONNECTION_COOKIE] = "stale"++ response = self.client.post("/oauth/authorize/", {**self.base_authorization_post_body, "allow": allow})++ self.assertEqual(response.status_code, status.HTTP_200_OK)+ self.assertEqual(response.cookies[PENDING_OAUTH_CONNECTION_COOKIE]["max-age"], 0)+def test_authorize_successful_with_required_params(self):response = self.client.get(self.base_authorization_url)self.assertEqual(response.status_code, status.HTTP_200_OK)@@ -237,12 +292,14 @@ class TestOAuthAPI(APIBaseTest):)url = self.replace_param_in_url(self.base_authorization_url, "client_id", first_party_app.client_id)+ self.client.cookies[PENDING_OAUTH_CONNECTION_COOKIE] = "stale"response = self.client.get(url)self.assertEqual(response.status_code, status.HTTP_302_FOUND)location = response["Location"]self.assertIn("code=", location)+ self.assertEqual(response.cookies[PENDING_OAUTH_CONNECTION_COOKIE]["max-age"], 0)code = parse_qs(urlparse(location).query)["code"][0]grant = OAuthGrant.objects.get(code=code)diff --git a/posthog/api/oauth/views.py b/posthog/api/oauth/views.pyindex 9af542415977..d15178b6d401 100644--- a/posthog/api/oauth/views.py+++ b/posthog/api/oauth/views.py@@ -4,6 +4,7 @@ import hashlibimport calendarfrom collections.abc import Iterablefrom datetime import datetime, timedelta+from functools import wrapsfrom typing import TypedDict, castfrom urllib.parse import parse_qs, urlparse@@ -61,6 +62,11 @@ from posthog.api.oauth.client_assertion import (from posthog.api.oauth.client_auth import verify_client_secretfrom posthog.api.oauth.mcp_resource_scopes import build_oauth_mcp_consent_contextfrom posthog.helpers.impersonation import get_original_user_from_session, is_impersonated_session+from posthog.helpers.oauth_pending_connection import (+ PendingOAuthConnection,+ clear_pending_oauth_connection_cookie,+ set_pending_oauth_connection_cookie,+)from posthog.llm.wizard_blocklist import GATEWAY_BEARING_SCOPES, WIZARD_BLOCKED_DETAIL, wizard_identity_blockedfrom posthog.middleware import is_read_only_impersonationfrom posthog.models import OAuthAccessToken, OAuthApplication, Organization, Team, User@@ -87,7 +93,7 @@ from posthog.scopes import ()from posthog.security.url_validation import has_ambiguous_authorityfrom posthog.user_permissions import UserPermissions-from posthog.utils import absolute_uri, render_template+from posthog.utils import absolute_uri, get_instance_region, render_templatefrom posthog.views import login_requiredlogger = structlog.get_logger(__name__)@@ -122,13 +128,18 @@ _IMPERSONATOR_CACHE_UNSET: object = object()STANDARD_TOKEN_ENDPOINT_PATHS = ("/oauth/token/", "/oauth/token")+def cloud_region() -> str | None:+ """`US` or `EU` when running on PostHog Cloud, else None."""+ cloud = get_instance_region()+ return cloud if cloud in ("US", "EU") else None++def get_region_info() -> dict | None:"""Return region metadata if running on PostHog Cloud US/EU, else None."""- cloud = getattr(settings, "CLOUD_DEPLOYMENT", None)- if cloud in ("US", "EU"):- region = cloud.lower()- return {"posthog_region": region, "posthog_base_url": settings.SITE_URL}- return None+ region = cloud_region()+ if region is None:+ return None+ return {"posthog_region": region.lower(), "posthog_base_url": settings.SITE_URL}# The host the other PostHog Cloud region answers on, so an unknown client_id can name it.@@ -151,13 +162,13 @@ def unknown_client_id_description(client_id: str | None) -> str:"Check that the URL is reachable over HTTPS and returns valid client metadata.")- cloud = getattr(settings, "CLOUD_DEPLOYMENT", None)- other_host = _OTHER_CLOUD_REGION_HOST.get(cloud or "")+ region = cloud_region()+ other_host = _OTHER_CLOUD_REGION_HOST.get(region or "")if other_host is None:return "No OAuth application is registered with this client_id. Check the client_id, or register the application again."return (- f"No OAuth application is registered with this client_id in the {cloud} region. "+ f"No OAuth application is registered with this client_id in the {region} region. "f"An application belongs to the region it was created in. If you created it on {other_host}, "f"send the authorization request to {other_host} instead. Otherwise check the client_id.")@@ -1245,6 +1256,62 @@ class OAuthValidator(OAuth2Validator):return scoped_teams, scoped_organizations+def _pending_connection_for_request(request) -> PendingOAuthConnection | None:+ """Public metadata of the application an unauthenticated authorize request names.++ The application row is the source when it exists. A CIMD client seen for the first time+ has no row yet, because the validator creates it after login, so the host of its+ client_id URL stands in for the name until then. Any other unknown client_id yields+ nothing, since the request fails after login anyway. The return host is taken only from+ a redirect URI the application registered, never from the raw query.+ """+ client_id = request.GET.get("client_id")+ if not client_id:+ return None++ application = (+ OAuthApplication.objects.only("name", "client_id", "logo_uri", "redirect_uris")+ .filter(client_id=client_id)+ .first()+ )+ if application is None:+ if not is_cimd_client_id(client_id):+ return None+ return PendingOAuthConnection(client_name=urlparse(client_id).hostname or client_id, client_id=client_id)++ redirect_host: str | None = None+ redirect_uri = request.GET.get("redirect_uri")+ if redirect_uri and application.redirect_uri_allowed(redirect_uri):+ parsed_redirect = urlparse(redirect_uri)+ if parsed_redirect.scheme in ("http", "https"):+ redirect_host = parsed_redirect.hostname++ return PendingOAuthConnection(+ client_name=application.name,+ client_id=application.client_id,+ logo_uri=application.logo_uri or None,+ redirect_host=redirect_host,+ )+++def _login_required_with_pending_connection(view):+ """`login_required` that also sets the pending-connection cookie on the login redirect,+ so the login, signup and verification screens can name the application."""+ base_handler = login_required(view)++ @wraps(view)+ def handler(request, *args, **kwargs):+ response = base_handler(request, *args, **kwargs)+ is_login_redirect = response.status_code == 302 and getattr(response, "url", "").startswith(settings.LOGIN_URL)+ if is_login_redirect:+ connection = _pending_connection_for_request(request)+ if connection is not None:+ set_pending_oauth_connection_cookie(request, response, connection)+ return response++ return handler++class OAuthAuthorizationView(OAuthLibMixin, APIView):"""This view handles incoming requests to /authorize.@@ -1357,7 +1424,7 @@ class OAuthAuthorizationView(OAuthLibMixin, APIView):},)- @method_decorator(login_required)+ @method_decorator(_login_required_with_pending_connection)def get(self, request, *args, **kwargs):# Rate-limit new CIMD application creation by IP.# Must happen here (not in the OAuthValidator) because the validator@@ -1457,7 +1524,7 @@ class OAuthAuthorizationView(OAuthLibMixin, APIView):)self._capture_scopes_clamped(request, application, scope_str)self._capture_authorization_granted(request, application, scope_str, "first_party", uri)- return self.redirect(uri, application)+ return self._redirect_and_finish_connection(request, uri, application)except OAuthToolkitError as error:return self.error_response(error, application, state=request.query_params.get("state"))@@ -1491,7 +1558,7 @@ class OAuthAuthorizationView(OAuthLibMixin, APIView):)self._capture_scopes_clamped(request, application, scope_str)self._capture_authorization_granted(request, application, scope_str, "auto_approval", uri)- return self.redirect(uri, application)+ return self._redirect_and_finish_connection(request, uri, application)except OAuthToolkitError as error:return self.error_response(error, application, state=request.query_params.get("state"))@@ -1652,9 +1719,11 @@ class OAuthAuthorizationView(OAuthLibMixin, APIView):**(get_region_info() or {}),},)- return self.error_response(+ response = self.error_response(error, application, no_redirect=True, state=serializer.validated_data.get("state"))+ clear_pending_oauth_connection_cookie(request, response)+ return responselogger.debug("Success url for the request: %s", uri)@@ -1664,12 +1733,14 @@ class OAuthAuthorizationView(OAuthLibMixin, APIView):self._capture_scopes_clamped(request, application, scopes)self._capture_authorization_granted(request, application, scopes, "consent", uri)- return Response(- {- "redirect_to": redirect.url,- },- status=status.HTTP_200_OK,- )+ response = Response({"redirect_to": redirect.url}, status=status.HTTP_200_OK)+ clear_pending_oauth_connection_cookie(request, response)+ return response++ def _redirect_and_finish_connection(self, request, uri: str, application: OAuthApplication) -> HttpResponse:+ response = self.redirect(uri, application)+ clear_pending_oauth_connection_cookie(request, response)+ return responsedef redirect(self, redirect_to, application: OAuthApplication | None):if application is None:diff --git a/posthog/api/signup.py b/posthog/api/signup.pyindex 7b9002ebcc34..2632cc758c91 100644--- a/posthog/api/signup.py+++ b/posthog/api/signup.py@@ -33,6 +33,7 @@ from posthog.email import is_email_availablefrom posthog.event_usage import alias_invite_id, report_user_joined_organization, report_user_signed_upfrom posthog.exceptions_capture import capture_exceptionfrom posthog.helpers.email_utils import EmailValidationHelper, reject_plus_addressed_email, validate_display_name+from posthog.helpers.oauth_pending_connection import read_pending_oauth_connectionfrom posthog.helpers.verified_domain_enforcement import resolve_login_organizationfrom posthog.models import InviteExpiredException, Organization, OrganizationDomain, OrganizationInvite, Team, Userfrom posthog.models.identity_provider_config import ConfigScope, IdentityProviderConfig@@ -65,6 +66,15 @@ def verify_email_or_login(request: Request, user: User) -> None:login(request, user, backend="django.contrib.auth.backends.ModelBackend")+def requested_next_url(request) -> str | None:+ """The `next_url` the client asked to land on, or None.++ Only a relative url is honored, so a signup response cannot redirect away from this domain.+ """+ next_url = request.data.get("next_url") if request and request.data else None+ return next_url if next_url and is_relative_url(next_url) else None++def get_redirect_url(uuid: str, is_email_verified: bool, next_url: str | None = None) -> str:user = User.objects.get(uuid=uuid)@@ -305,6 +315,7 @@ class SignupSerializer(serializers.Serializer):role_at_organization=role_at_organization,referral_source=referral_source,referral_source_ai_prompt=referral_source_ai_prompt,+ oauth_connection=read_pending_oauth_connection(request),)# Fire-and-forget real-time enrichment for onboarding routing. Fully guarded and@@ -350,12 +361,7 @@ class SignupSerializer(serializers.Serializer):return Team.objects.create_with_data(initiating_user=user, organization=organization)def to_representation(self, instance) -> dict:- request = self.context.get("request")- next_url = request.data.get("next_url") if request and request.data else None- # We only want to redirect to a relative url so that we don't redirect away from the current domain- if next_url and not is_relative_url(next_url):- next_url = None-+ next_url = requested_next_url(self.context.get("request"))data = UserBasicSerializer(instance=instance).datadata["redirect_url"] = get_redirect_url(data["uuid"], data["is_email_verified"], next_url)return data@@ -475,11 +481,13 @@ class InviteSignupSerializer(serializers.Serializer):return validate_display_name(value)def to_representation(self, instance):- data = UserBasicSerializer(instance=instance).data- # Setup-delegation invites hand off onboarding to the invitee — route them straight into+ next_url = requested_next_url(self.context.get("request"))+ # Setup-delegation invites hand off onboarding to the invitee - route them straight into# onboarding instead of the default post-signup landing page, otherwise the sceneLogic# redirect race can drop them on the homepage.- next_url = "/onboarding" if self.context.get("delegated_onboarding") else None+ if self.context.get("delegated_onboarding"):+ next_url = "/onboarding"+ data = UserBasicSerializer(instance=instance).datadata["redirect_url"] = get_redirect_url(data["uuid"], data["is_email_verified"], next_url)return data@@ -666,6 +674,7 @@ class InviteSignupSerializer(serializers.Serializer):user_analytics_metadata=user.get_analytics_metadata(),org_analytics_metadata=user.organization.get_analytics_metadata() if user.organization else None,role_at_organization=role_at_organization,+ oauth_connection=read_pending_oauth_connection(request),referral_source="signed up from invite link",)@@ -1109,6 +1118,7 @@ def social_create_user(user_analytics_metadata=user.get_analytics_metadata(),org_analytics_metadata=user.organization.get_analytics_metadata() if user.organization else None,referral_source="social signup - no info",+ oauth_connection=read_pending_oauth_connection(request),)return {"is_new": True, "user": user}diff --git a/posthog/api/test/test_signup.py b/posthog/api/test/test_signup.pyindex 3237f48239d7..c3cb40382606 100644--- a/posthog/api/test/test_signup.py+++ b/posthog/api/test/test_signup.py@@ -22,6 +22,7 @@ from rest_framework import statusfrom posthog.api.signup import _save_session_with_recovery, lookup_invite_for_saml, process_social_invite_signupfrom posthog.cloud_utils import TEST_clear_instance_license_cachefrom posthog.constants import AvailableFeature+from posthog.helpers.oauth_pending_connection import PENDING_OAUTH_CONNECTION_COOKIE, PendingOAuthConnectionfrom posthog.models import Organization, Team, Userfrom posthog.models.identity_provider_config import IdentityProviderConfigfrom posthog.models.instance_setting import override_instance_config@@ -1537,6 +1538,29 @@ class TestSignupAPI(APIBaseTest):)mock_email_verifier.assert_called_once_with(user)+ @patch("posthoganalytics.capture")+ def test_api_sign_up_reports_the_pending_oauth_connection(self, mock_capture):+ self.client.cookies[PENDING_OAUTH_CONNECTION_COOKIE] = PendingOAuthConnection(+ client_name="Claude", client_id="https://claude.example.com/.well-known/oauth-client"+ ).to_cookie_value()++ response = self.client.post(+ "/api/signup/",+ {+ "first_name": "Jane",+ "email": "[email protected]",+ "password": VALID_TEST_PASSWORD,+ "role_at_organization": "product",+ },+ )+ self.assertEqual(response.status_code, status.HTTP_201_CREATED)++ signup_calls = [c for c in mock_capture.call_args_list if c.kwargs.get("event") == "user signed up"]+ properties = signup_calls[0].kwargs["properties"]+ self.assertEqual(properties["signup_oauth_client_name"], "Claude")+ self.assertEqual(properties["signup_oauth_client_id"], "https://claude.example.com/.well-known/oauth-client")+ self.assertEqual(properties["$set"]["signup_oauth_client_name"], "Claude")+@pytest.mark.skip_on_multitenancy@patch("posthog.utils.get_ip_address", return_value="192.168.1.100")def test_signup_rate_limit_by_ip(self, mock_get_ip):@@ -2248,6 +2272,24 @@ class TestInviteSignupAPI(APIBaseTest):# Signup (using invite)+ def test_api_invite_sign_up_preserves_next_param(self):+ invite: OrganizationInvite = OrganizationInvite.objects.create(+ target_email="[email protected]", organization=self.organization+ )++ response = self.client.post(+ f"/api/signup/{invite.id}/",+ {+ "first_name": "Alice",+ "password": VALID_TEST_PASSWORD,+ "role_at_organization": "Engineering",+ "next_url": "/oauth/authorize?client_id=test123",+ },+ )++ self.assertEqual(response.status_code, status.HTTP_201_CREATED)+ self.assertEqual(response.json()["redirect_url"], "/oauth/authorize?client_id=test123")+@patch("posthoganalytics.capture")def test_api_invite_sign_up(self, mock_capture):invite: OrganizationInvite = OrganizationInvite.objects.create(diff --git a/posthog/event_usage.py b/posthog/event_usage.pyindex 1cdf1555b47c..4eb0647db656 100644--- a/posthog/event_usage.py+++ b/posthog/event_usage.py@@ -15,6 +15,7 @@ from rest_framework.authentication import SessionAuthenticationfrom posthog.clickhouse.query_tagging import get_query_tag_valuefrom posthog.constants import POSTHOG_INTERNAL_EMAIL_SUFFIX+from posthog.helpers.oauth_pending_connection import PendingOAuthConnectionfrom posthog.models import Organization, Userfrom posthog.models.activity_logging.model_activity import is_impersonated_sessionfrom posthog.models.team import Team@@ -44,6 +45,7 @@ def report_user_signed_up(role_at_organization: str = "", # select input to ask what the user role is at the orgreferral_source: str = "", # free text input to ask users where did they hear about usreferral_source_ai_prompt: str = "", # prompt they used when discovering PostHog via AI+ oauth_connection: Optional[PendingOAuthConnection] = None, # the app whose OAuth request sent them to sign up) -> None:"""Reports that a new user has joined. Only triggered when a new user is actually created (i.e. when an existing user@@ -67,6 +69,9 @@ def report_user_signed_up("referral_source_ai_prompt": referral_source_ai_prompt,"is_email_verified": user.is_email_verified,}+ if oauth_connection is not None:+ props["signup_oauth_client_name"] = oauth_connection.client_name+ props["signup_oauth_client_id"] = oauth_connection.client_idif user_analytics_metadata is not None:props.update(user_analytics_metadata)diff --git a/posthog/helpers/oauth_pending_connection.py b/posthog/helpers/oauth_pending_connection.pynew file mode 100644index 000000000000..368fc211fd93--- /dev/null+++ b/posthog/helpers/oauth_pending_connection.py@@ -0,0 +1,123 @@+"""Cookie that carries a pending OAuth authorization through login and signup.++`/oauth/authorize` needs a session. A visitor without one is sent to `/login?next=...`,+and from there may go through signup and email verification before coming back. Only the+opaque `next` URL travels with them, so nothing on those screens can name the application+they are connecting.++This cookie makes that context readable on every `posthog.com` host, the website included,+which the app context cannot do because only the app's own documents receive it. The cookie+holds public application metadata only: the same name and logo the consent screen shows.+"""++import json+from urllib.parse import quote, unquote++from django.http import HttpRequest, HttpResponse++from posthog.dataclasses import frozen++PENDING_OAUTH_CONNECTION_COOKIE = "ph_pending_oauth_connection"++# Long enough to sign up and verify an email address, short enough that an abandoned+# connection does not keep branding the login page for days.+PENDING_OAUTH_CONNECTION_MAX_AGE_SECONDS = 60 * 60++# The cookie is shared with the website, so it is scoped to the registrable domain when+# the request host is under it. Any other host (localhost, a preview domain) gets a+# host-only cookie, because a browser drops a cookie whose Domain does not cover the host.+_SHARED_COOKIE_DOMAIN = "posthog.com"++# Column limits of the application row these values come from. Anything longer arrived+# from a forged cookie, and the reader treats it as absent.+_MAX_CLIENT_NAME_LENGTH = 255+_MAX_CLIENT_ID_LENGTH = 2048+# Browsers cap a whole cookie near 4 KB. A logo URI past this is left out rather than+# risk the browser rejecting the entire cookie.+_MAX_LOGO_URI_LENGTH = 1024+_MAX_HOST_LENGTH = 253+++def _optional_str(value: object, max_length: int) -> str | None:+ if not isinstance(value, str) or not value or len(value) > max_length:+ return None+ return value+++@frozen+class PendingOAuthConnection:+ """What the auth screens and the website may say about the application being connected."""++ client_name: str+ client_id: str+ logo_uri: str | None = None+ # Host of the registered redirect URI the visitor returns to, when it is a web URL.+ redirect_host: str | None = None++ def to_cookie_value(self) -> str:+ payload = {+ "client_name": self.client_name,+ "client_id": self.client_id,+ "logo_uri": _optional_str(self.logo_uri, _MAX_LOGO_URI_LENGTH),+ "redirect_host": self.redirect_host,+ }+ compact = {key: value for key, value in payload.items() if value is not None}+ # Percent-encoding keeps the value inside the cookie-safe alphabet, and it is what+ # `decodeURIComponent` on the reading side expects.+ return quote(json.dumps(compact, separators=(",", ":")), safe="")++ @classmethod+ def from_cookie_value(cls, raw: str | None) -> "PendingOAuthConnection | None":+ if not raw:+ return None+ try:+ payload = json.loads(unquote(raw))+ except (ValueError, TypeError):+ return None+ if not isinstance(payload, dict):+ return None+ client_name = _optional_str(payload.get("client_name"), _MAX_CLIENT_NAME_LENGTH)+ client_id = _optional_str(payload.get("client_id"), _MAX_CLIENT_ID_LENGTH)+ if client_name is None or client_id is None:+ return None+ return cls(+ client_name=client_name,+ client_id=client_id,+ logo_uri=_optional_str(payload.get("logo_uri"), _MAX_LOGO_URI_LENGTH),+ redirect_host=_optional_str(payload.get("redirect_host"), _MAX_HOST_LENGTH),+ )+++def _cookie_domain(request: HttpRequest) -> str | None:+ host = request.get_host().rsplit(":", 1)[0].lower()+ if host == _SHARED_COOKIE_DOMAIN or host.endswith("." + _SHARED_COOKIE_DOMAIN):+ return _SHARED_COOKIE_DOMAIN+ return None+++def set_pending_oauth_connection_cookie(+ request: HttpRequest, response: HttpResponse, connection: PendingOAuthConnection+) -> None:+ # nosemgrep: python.django.security.audit.secure-cookies.django-secure-set-cookie (httponly=False intentional, read by JS on the app and on the website)+ response.set_cookie(+ key=PENDING_OAUTH_CONNECTION_COOKIE,+ value=connection.to_cookie_value(),+ max_age=PENDING_OAUTH_CONNECTION_MAX_AGE_SECONDS,+ path="/",+ domain=_cookie_domain(request),+ secure=request.is_secure(),+ httponly=False,+ samesite="Lax",+ )+++def clear_pending_oauth_connection_cookie(request: HttpRequest, response: HttpResponse) -> None:+ """End the pending connection. A no-op without the cookie, so the deletion header is not+ attached to the many authorizations that started from an already signed-in session."""+ if PENDING_OAUTH_CONNECTION_COOKIE not in request.COOKIES:+ return+ response.delete_cookie(PENDING_OAUTH_CONNECTION_COOKIE, path="/", domain=_cookie_domain(request), samesite="Lax")+++def read_pending_oauth_connection(request: HttpRequest) -> PendingOAuthConnection | None:+ return PendingOAuthConnection.from_cookie_value(request.COOKIES.get(PENDING_OAUTH_CONNECTION_COOKIE))diff --git a/posthog/helpers/tests/test_oauth_pending_connection.py b/posthog/helpers/tests/test_oauth_pending_connection.pynew file mode 100644index 000000000000..a2c0ad55f02a--- /dev/null+++ b/posthog/helpers/tests/test_oauth_pending_connection.py@@ -0,0 +1,43 @@+import json+from urllib.parse import quote++from django.test import SimpleTestCase++from parameterized import parameterized++from posthog.helpers.oauth_pending_connection import PendingOAuthConnection+++class TestPendingOAuthConnectionCookieValue(SimpleTestCase):+ def test_round_trip_keeps_every_field(self):+ connection = PendingOAuthConnection(+ client_name="Claude & Co",+ client_id="https://claude.example.com/.well-known/oauth-client",+ logo_uri="https://claude.example.com/logo.png",+ redirect_host="claude.example.com",+ )++ self.assertEqual(PendingOAuthConnection.from_cookie_value(connection.to_cookie_value()), connection)++ def test_round_trip_drops_an_oversized_logo_but_keeps_the_rest(self):+ connection = PendingOAuthConnection(+ client_name="Cursor", client_id="cursor_client_id", logo_uri="https://example.com/" + "a" * 2000+ )++ restored = PendingOAuthConnection.from_cookie_value(connection.to_cookie_value())++ self.assertEqual(restored, PendingOAuthConnection(client_name="Cursor", client_id="cursor_client_id"))++ @parameterized.expand(+ [+ ("missing", None),+ ("empty", ""),+ ("not_json", "not%20json"),+ ("not_an_object", quote("[]")),+ ("missing_client_name", quote(json.dumps({"client_id": "x"}))),+ ("wrong_type", quote(json.dumps({"client_name": 5, "client_id": "x"}))),+ ("oversized_client_name", quote(json.dumps({"client_name": "a" * 256, "client_id": "x"}))),+ ]+ )+ def test_forged_or_malformed_values_read_as_absent(self, _name, raw):+ self.assertIsNone(PendingOAuthConnection.from_cookie_value(raw))