: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(auth): open the password field inside the email card (#125933)
Rafael Audibertf8e303216b03
diff --git a/docs/published/handbook/engineering/oauth-development-guide.md b/docs/published/handbook/engineering/oauth-development-guide.mdindex 1bdeb5dd45f4..fb62647757a6 100644--- a/docs/published/handbook/engineering/oauth-development-guide.md+++ b/docs/published/handbook/engineering/oauth-development-guide.md@@ -332,10 +332,10 @@ To add one, create a JSON file there with `client_id` set to its own URL. The CI## Self-registered client logos-Both self-registration paths accept a `logo_uri`, and PostHog shows it on the consent screen and on the login, signup, and email verification screens. A client that sends none gets the first letter of its name instead.+Both self-registration paths accept a `logo_uri`, and PostHog shows it on the consent screen and on the login, signup, and email verification screens. A client without a logo gets the first letter of its name instead.- Dynamic client registration (`POST /oauth/register/`, RFC 7591): send `logo_uri` alongside `redirect_uris`. The response echoes it back.-- Client ID metadata documents: put `logo_uri` in the document.+- Client ID metadata documents: put `logo_uri` in the document. A document without one gets `https://<client_id host>/apple-touch-icon.png`, the touch icon of the host that serves the document. It never comes from `client_uri`, which the document asserts about itself, so a client cannot borrow another site's icon. Where the host has no such icon, the screens fall back to the first letter. A refresh keeps a stored logo when the document still has none.The URI must be `https` and must pass `is_url_allowed`, the same SSRF guard the rest of the codebase uses. That rejects a loopback, private, metadata or internal-domain host, and it resolves the name, so a public hostname pointing at a private address is rejected too. A URI that fails either check is dropped and left out of the registration response. It never fails the registration, since a client can complete every OAuth flow without a logo.@@ -356,7 +356,9 @@ An account created while the cookie is present skips in-app onboarding. Signup sWhile the cookie is present, the auth page 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: `/login` and `/signup` render the same page, which asks for the email first and then shows the login or the signup steps. The frontend captures `auth step viewed` for every step, with `step` (`email`, `login`, `login_code`, `signup_credentials`, `signup_profile`, `signup_pending_invite`, or `verify_email`), `entry` (`login` or `signup`), and `oauth_client_name` and `oauth_client_id` while the cookie is present. `auth email submitted` records the routing decision with `routed_to` and `account_exists`. `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. When the signup creates a new organization, the project group also gets `created_via_oauth_client` and `created_via_oauth_client_id`.+To try these screens locally, run `generate_demo_data`. It registers the Claude and ChatGPT connectors from their public client ID metadata documents, the same way production registers them. Then open **Login tools** on `/login` and pick a connector under **Start an OAuth connection**. That sets the cookie and a `next` link to the consent screen, as the redirect above does. **Clear** deletes the cookie again.++Analytics: `/login` and `/signup` render the same page, which asks for the email first and then opens the login or the signup password under it. The frontend captures `auth step viewed` for every step, with `step` (`email`, `login`, `login_code`, `signup_credentials`, `signup_profile`, `signup_pending_invite`, or `verify_email`), `entry` (`login` or `signup`), and `oauth_client_name` and `oauth_client_id` while the cookie is present. `auth email submitted` records the routing decision with `routed_to` and `account_exists`. `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. When the signup creates a new organization, the project group also gets `created_via_oauth_client` and `created_via_oauth_client_id`.## Endpointsdiff --git a/frontend/snapshots.yml b/frontend/snapshots.ymlindex 83ae245b62e4..f321b5260d93 100644--- a/frontend/snapshots.yml+++ b/frontend/snapshots.yml@@ -2013,17 +2013,17 @@ snapshots:components-not-found--not-found--light:hash: v1.k794b7964.ef3247e1f5c8360e264349da02724c306672e837b42f16ad74a8fad9d1219d02.A0XX2XEOCK7YQYtIRtCKo0SB4kHqS_vBHaH141IrbEEcomponents-oauth-connection-logos--broken-logo--dark:- hash: v1.k794b7964.9e8e6d61c4484e125eede42304b6f38a2ecc96ef84818d2e9e07eb02607accbf.J1zRnFl4_rbeScN1BSh09dqW8mhinsbZxdE9PEWzqNw+ hash: v1.k794b7964.a6caaf7dfabf6aca8af46748185f45994b60c0d1e6cae2301e7808a0779ee2c0.IHPxw0K7GIcHedJO8HabsPFM3gqEBkixVgWXYnPosmQcomponents-oauth-connection-logos--broken-logo--light:- hash: v1.k794b7964.76669465d3b4dddf9fd33d45bb09f1db0e05f78aeb14e8c64940db1a81d9aab0.N9Td2xmjU22juReZFAmBFCvJ7RWnKgQkxHMYFrFa698+ hash: v1.k794b7964.8d26f2f0e43e242978bc6eed82d97bbb5e462936ed39b6307dd7f808744a8dd9.i2Bbd984H0CSmUtIfQTlHfYhqprj-AaqEGHR7554wF8components-oauth-connection-logos--with-logo--dark:- hash: v1.k794b7964.c6713b67e0825fcbaddf9a5161ac218cc10b7b37e0b76989546af3ccc9e2170f.BgdGrVUOhTti04YuJiDOFf64LC0C6bIjmmcmTcFyK78+ hash: v1.k794b7964.c42697fa400505cc9e161f46c0777e3f4ebd41da4040020c162167eecf8bf7be.xwTyREga_cIqBftFhwXSj5ur0o_W9ZiIus1o6yO4gP8components-oauth-connection-logos--with-logo--light:- hash: v1.k794b7964.ada4261a542447f12d0f896d64fa07c776083499e8d50fe264eb5529b6aa92c5.vS-uZ_4tH1vaKaV-9BIrq2MBpzFVmrzlrZTqkLh_uBQ+ hash: v1.k794b7964.813621f9ecbc4322028782ad595cce0f4a2122de1c32ba77ce852e90d870cb48.mLkH_gNyYtAdCx-UC5FmxuC1i-BhXP1fz6flg1-6g3Acomponents-oauth-connection-logos--without-logo--dark:- hash: v1.k794b7964.9e8e6d61c4484e125eede42304b6f38a2ecc96ef84818d2e9e07eb02607accbf.UHsxNwfUnwWBY7bE6K812O-LImDiM_tdY2moYXIQCT4+ hash: v1.k794b7964.a6caaf7dfabf6aca8af46748185f45994b60c0d1e6cae2301e7808a0779ee2c0.9271nBdYGNaPCHz-bqbPn-geTRzhM3PWsdw-oJh9XEwcomponents-oauth-connection-logos--without-logo--light:- hash: v1.k794b7964.76669465d3b4dddf9fd33d45bb09f1db0e05f78aeb14e8c64940db1a81d9aab0.kkQspWJQLQTm73qg8wVkXhF8XnAdVcSzRnneE1ZywlU+ hash: v1.k794b7964.8d26f2f0e43e242978bc6eed82d97bbb5e462936ed39b6307dd7f808744a8dd9.ErF1tre7CqFIFz7785s5lH-gw2jmVfiyI1RMJUxxW60components-pay-gate-mini--pay-gate-mini--dark:hash: v1.k794b7964.42a516cf3e11bb319673f4b0fd69efd4150fca0477d502749a36ba338da33e05.tM1QnvnZagRnjAU2zw0xRjujJMSapGoK_xbKBITppmQcomponents-pay-gate-mini--pay-gate-mini--light:diff --git a/frontend/src/lib/brand/index.tsx b/frontend/src/lib/brand/index.tsxindex 5aad2d6fd346..518bfa6cdd39 100644--- a/frontend/src/lib/brand/index.tsx+++ b/frontend/src/lib/brand/index.tsx@@ -4,7 +4,7 @@// choke point that adapts it to dark mode and to the holiday season, so those behaviors can't// drift per-consumer.import { Logo as BrandLogo } from '@posthog/brand/logo'-import type { LogoProps, LogomarkProps } from '@posthog/brand/logo'+import type { LogoHoliday, LogoProps, LogomarkProps } from '@posthog/brand/logo'import { currentHoliday } from 'lib/holidays'import { cn } from 'lib/utils/css-classes'@@ -29,7 +29,10 @@ const LOGO_SIZE_HEIGHTS: Record<LogoSize, number> = {// instead, so one token scales any layout consistently — hide the raw dimension props from callers.type WithLogoSize<P> = Omit<P, 'size' | 'width' | 'height'> & { size?: LogoSize }export type AppLogoProps = WithLogoSize<LogoProps>-export type AppLogomarkProps = WithLogoSize<LogomarkProps>+export type AppLogomarkProps = Omit<WithLogoSize<LogomarkProps>, 'holiday'> & {+ /** A holiday to dress up for. Omit it to follow the calendar, or pass `null` for no accessory. */+ holiday?: LogoHoliday | null+}/*** The PostHog logo, adapted to the app's theme. With no explicit `variant` it renders the@@ -61,7 +64,7 @@ export function Logo({ variant, className, size, ...props }: AppLogoProps): JSX.* `size` sets the height (see {@link LogoSize}); `jumpOnClick` and other package props pass through.*/export function Logomark({ variant, className, holiday, size, ...props }: AppLogomarkProps): JSX.Element {- const resolvedHoliday = holiday ?? currentHoliday()+ const resolvedHoliday = holiday === null ? undefined : (holiday ?? currentHoliday())const height = size ? LOGO_SIZE_HEIGHTS[size] : undefinedif (variant) {return (diff --git a/frontend/src/lib/components/OAuthConnectionLogos/OAuthConnectionLogos.tsx b/frontend/src/lib/components/OAuthConnectionLogos/OAuthConnectionLogos.tsxindex e182edab6e30..ff3cf2f78ed1 100644--- a/frontend/src/lib/components/OAuthConnectionLogos/OAuthConnectionLogos.tsx+++ b/frontend/src/lib/components/OAuthConnectionLogos/OAuthConnectionLogos.tsx@@ -12,8 +12,9 @@ export function OAuthConnectionLogos({ appName, logoUri }: { appName: string; lo// pinned: `data-attr` value read by autocapture dashboards, so it keeps the name it was// first shipped under on the login page.<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 size="sm" />+ <span className="flex items-center justify-center w-12 h-12 p-1.5 rounded-full border border-border bg-bg-light">+ {/* No `size`, so the mark fills the padded circle. A holiday accessory would stick out of it. */}+ <Logomark holiday={null} /></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">diff --git a/frontend/src/lib/components/SignupReferralSource.tsx b/frontend/src/lib/components/SignupReferralSource.tsxindex de355d8a5372..0f24299f64db 100644--- a/frontend/src/lib/components/SignupReferralSource.tsx+++ b/frontend/src/lib/components/SignupReferralSource.tsx@@ -144,7 +144,9 @@ export function getReferralFollowUp(referralSource: string): 'ai' | 'influencer'export default function SignupReferralSource({ disabled }: { disabled: boolean }): JSX.Element {return (- <>+ // A collapsed follow-up placed directly in the form would still take a form gap, so the+ // follow-ups share this column and carry their own top padding instead+ <div className="flex flex-col"><LemonField name="referral_source" label="Where did you hear about us?" showOptional>{({ value, onChange }) => (<LemonInput@@ -166,6 +168,7 @@ export default function SignupReferralSource({ disabled }: { disabled: boolean }<><AnimatedCollapsible collapsed={followUp !== 'ai'}><LemonField+ className="pt-4"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"@@ -182,6 +185,7 @@ export default function SignupReferralSource({ disabled }: { disabled: boolean }</AnimatedCollapsible><AnimatedCollapsible collapsed={followUp !== 'influencer'}><LemonField+ className="pt-4"name="referral_source_influencer"label="Which account or person led you to PostHog?"help="Name the account, channel, or person if you remember"@@ -200,6 +204,6 @@ export default function SignupReferralSource({ disabled }: { disabled: boolean })}}</KeaField>- </>+ </div>)}diff --git a/frontend/src/scenes/authentication/auth/Auth.test.tsx b/frontend/src/scenes/authentication/auth/Auth.test.tsxindex f2590f74f9dd..1966dbcff0f5 100644--- a/frontend/src/scenes/authentication/auth/Auth.test.tsx+++ b/frontend/src/scenes/authentication/auth/Auth.test.tsx@@ -111,6 +111,10 @@ describe('Auth', () => {// guards that wiring. The payload shaping itself is covered in signupLogic.test.ts.it('walks a new email through every signup step and posts what was typed into them', async () => {await submitEmail('[email protected]')++ await screen.findByTestId('signup-auth-continue')+ expect(screen.queryByText('Please enter your password to continue')).not.toBeInTheDocument()+await submitPassword('Str0ng-Test-Pass!')await fillOnboardingAndSubmit({ name: 'Alice Bob', organizationName: 'Hogflix SpinOff' })diff --git a/frontend/src/scenes/authentication/auth/Auth.tsx b/frontend/src/scenes/authentication/auth/Auth.tsxindex a19d1cdb5268..c0cfe9ab8b92 100644--- a/frontend/src/scenes/authentication/auth/Auth.tsx+++ b/frontend/src/scenes/authentication/auth/Auth.tsx@@ -17,9 +17,7 @@ import { AuthPageStep, authLogic } from './authLogic'import { authTelemetryLogic } from './authTelemetryLogic'import { EmailStep } from './steps/EmailStep'import { LoginCodeStep } from './steps/LoginCodeStep'-import { LoginStep } from './steps/LoginStep'import { PendingInviteStep } from './steps/PendingInviteStep'-import { SignupCredentialsStep } from './steps/SignupCredentialsStep'import { SignupProfileStep } from './steps/SignupProfileStep'export const scene: SceneExport = {@@ -46,10 +44,11 @@ function authNotes(step: AuthPageStep, entry: AuthEntry, isReturning: boolean):}const STEP_COMPONENTS: Record<AuthPageStep, () => JSX.Element> = {+ // These three share one component, so React keeps the card and opens the password field inside itemail: EmailStep,- login: LoginStep,+ login: EmailStep,login_code: LoginCodeStep,- signup_credentials: SignupCredentialsStep,+ signup_credentials: EmailStep,signup_profile: SignupProfileStep,signup_pending_invite: PendingInviteStep,}diff --git a/frontend/src/scenes/authentication/auth/authLogic.test.ts b/frontend/src/scenes/authentication/auth/authLogic.test.tsindex 6698269b46fa..d4f7f80d6c84 100644--- a/frontend/src/scenes/authentication/auth/authLogic.test.ts+++ b/frontend/src/scenes/authentication/auth/authLogic.test.ts@@ -161,6 +161,16 @@ describe('authLogic', () => {authLogic.actions.backToEmail()await expectLogic(signupLogic).toMatchValues({ passkeyRegistered: false })})++ it('opens the next password field without the error a failed login submit left behind', async () => {+ loginLogic.actions.submitLogin()+ await expectLogic(loginLogic).toDispatchActions(['submitLoginFailure'])++ expect(loginLogic.values.loginErrors.password).toBeTruthy()++ authLogic.actions.backToEmail()+ await expectLogic(loginLogic).toMatchValues({ loginErrors: {} })+ })})describe('funnel events', () => {diff --git a/frontend/src/scenes/authentication/auth/authLogic.ts b/frontend/src/scenes/authentication/auth/authLogic.tsindex 59d4c762671a..a19c1157205b 100644--- a/frontend/src/scenes/authentication/auth/authLogic.ts+++ b/frontend/src/scenes/authentication/auth/authLogic.ts@@ -25,6 +25,10 @@ export function canSignUpWithEmail(precheck: PrecheckResponseType, preflight: Prreturn !!preflight?.can_create_org && !precheck.sso_enforcement}+export function hasSingleSignOn(precheck: PrecheckResponseType): boolean {+ return !!precheck.sso_enforcement || precheck.saml_available || !!precheck.oidc_available+}+export function accountPathFor(precheck: PrecheckResponseType, preflight: PreflightStatus | null): AuthAccountPath {// Demo signup logs an existing demo user straight in, and demo users have no password to type.if (preflight?.demo) {@@ -44,6 +48,7 @@ export function accountPathFor(precheck: PrecheckResponseType, preflight: Prefliexport interface authLogicValues {featureFlags: FeatureFlagsSet // featureFlagLogiccodeVerificationRequired: boolean // loginLogic+ isPasswordLoginUnavailable: boolean // loginLogiclogin: LoginForm // loginLogicprecheckResponse: PrecheckResponseType // loginLogicpreflight: PreflightStatus | null // preflightLogic@@ -59,6 +64,7 @@ export interface authLogicValues {emailValidationError: string | nullentry: AuthEntryisEmailSubmitting: boolean+ isLoginPasswordHidden: booleanstep: AuthPageStep}@@ -89,6 +95,9 @@ export interface authLogicActions {}precheckResponse: PrecheckResponseType} // loginLogic+ resetLogin: (values?: LoginForm | undefined) => {+ values?: LoginForm+ } // loginLogicsetLoginValue: (key: import('node_modules/kea-forms/lib').FieldName,value: any@@ -96,6 +105,9 @@ export interface authLogicActions {name: import('node_modules/kea-forms/lib').FieldNamevalue: any} // loginLogic+ submitLogin: () => {+ value: boolean+ } // loginLogicprecheckSignupEmail: (email: string) => {email: string} // signupLogic@@ -115,6 +127,9 @@ export interface authLogicActions {error: string | nullisTaken: boolean} // signupLogic+ submitSignupPanelAuth: () => {+ value: boolean+ } // signupLogicbackToEmail: () => {value: true}@@ -134,6 +149,9 @@ export interface authLogicActions {setEmailValidationError: (error: string | null) => {error: string | null}+ submitEmailStep: () => {+ value: true+ }}// Generated by kea-typegen. Update if you're an agent, ignore if you're human.@@ -149,6 +167,11 @@ export interface authLogicMeta {canSignUpWithEmail: (precheckResponse: PrecheckResponseType, preflight: PreflightStatus | null) => booleanisEmailSubmitting: (awaitingPrecheckFor: string | null, isSignupEmailChecking: boolean) => booleanemailError: (emailValidationError: string | null, signupEmailError: string | null) => string | null+ isLoginPasswordHidden: (+ precheckResponse: PrecheckResponseType,+ isPasswordLoginUnavailable: boolean,+ accountExists: boolean | null+ ) => boolean}}@@ -168,19 +191,35 @@ export const authLogic = kea<authLogicType>([featureFlagLogic,['featureFlags'],loginLogic,- ['login', 'codeVerificationRequired', 'precheckResponse'],+ ['login', 'codeVerificationRequired', 'precheckResponse', 'isPasswordLoginUnavailable'],signupLogic,['panel', 'pendingInvite', 'isSignupEmailChecking', 'signupEmailError'],],actions: [loginLogic,- ['precheck', 'precheckSuccess', 'setLoginValue', 'clearGeneralError', 'exitCodeVerification'],+ [+ 'precheck',+ 'precheckSuccess',+ 'setLoginValue',+ 'resetLogin',+ 'submitLogin',+ 'clearGeneralError',+ 'exitCodeVerification',+ ],signupLogic,- ['precheckSignupEmail', 'setSignupEmailError', 'setPendingInvite', 'setPanel', 'resetSignupCredentials'],+ [+ 'precheckSignupEmail',+ 'setSignupEmailError',+ 'setPendingInvite',+ 'setPanel',+ 'resetSignupCredentials',+ 'submitSignupPanelAuth',+ ],],})),actions({continueWithEmail: true,+ submitEmailStep: true,setEmailValidationError: (error: string | null) => ({ error }),setAwaitingPrecheckFor: (email: string | null) => ({ email }),chooseAccountPath: (accountPath: AuthAccountPath, accountExists: boolean | null) => ({@@ -269,8 +308,28 @@ export const authLogic = kea<authLogicType>([(emailValidationError: string | null, signupEmailError: string | null): string | null =>emailValidationError ?? signupEmailError,],+ // A new person reaches the login step on a SAML or OIDC domain, where the IdP creates the account,+ // or where nobody may sign up with email, such as a self-hosted instance with signups off+ isLoginPasswordHidden: [+ (s) => [s.precheckResponse, s.isPasswordLoginUnavailable, s.accountExists],+ (+ precheckResponse: PrecheckResponseType,+ isPasswordLoginUnavailable: boolean,+ accountExists: boolean | null+ ): boolean => !!precheckResponse.sso_enforcement || isPasswordLoginUnavailable || accountExists === false,+ ],}),listeners(({ actions, values }) => ({+ // The email card is one form, and its submit button finishes whichever path the email took+ submitEmailStep: () => {+ if (values.step === 'login') {+ actions.submitLogin()+ } else if (values.step === 'signup_credentials') {+ actions.submitSignupPanelAuth()+ } else {+ actions.continueWithEmail()+ }+ },continueWithEmail: () => {const email = values.login.email.trim()if (!email) {@@ -321,7 +380,9 @@ export const authLogic = kea<authLogicType>([},backToEmail: () => {actions.exitCodeVerification()- actions.setLoginValue('password', '')+ // A reset also clears the "show errors" state that a rejected password left behind, so the+ // next password field does not open with a red error+ actions.resetLogin({ email: values.login.email, password: '' })actions.clearGeneralError()actions.setPendingInvite(null)actions.setPanel(0)@@ -336,7 +397,8 @@ export const authLogic = kea<authLogicType>([if (values.awaitingPrecheckFor !== null && values.awaitingPrecheckFor !== values.login.email) {actions.setAwaitingPrecheckFor(null)}- if (values.accountPath !== null && values.step === 'email') {+ // The password field opens under the email field, so editing the email closes it+ if (values.accountPath !== null && ['email', 'login', 'signup_credentials'].includes(values.step)) {actions.backToEmail()}if (values.emailError) {diff --git a/frontend/src/scenes/authentication/auth/components/AuthEmailField.tsx b/frontend/src/scenes/authentication/auth/components/AuthEmailField.tsxnew file mode 100644index 000000000000..bb94832202a2--- /dev/null+++ b/frontend/src/scenes/authentication/auth/components/AuthEmailField.tsx@@ -0,0 +1,49 @@+import { useActions, useValues } from 'kea'+import { useEffect } from 'react'++import { usePrevious } from 'lib/hooks/usePrevious'+import { LemonField } from 'lib/lemon-ui/LemonField'+import { LemonInput } from 'lib/lemon-ui/LemonInput/LemonInput'+import { isWebKitBrowser } from 'lib/utils/dom'+import { isEmail } from 'lib/utils/url'++import { authLogic } from '../authLogic'+import { loginLogic } from '../loginLogic'++export function AuthEmailField(): JSX.Element {+ const { login, precheckResponse } = useValues(loginLogic)+ const { setLoginValue, precheck } = useActions(loginLogic)+ const { entry, emailError } = useValues(authLogic)+ const prevEmail = usePrevious(login.email)++ // An autofilled address is prechecked at once, so a passkey prompt can open before Continue+ useEffect(() => {+ const charDelta = login.email.length - (prevEmail?.length ?? 0)+ const isAutofill = charDelta > 1++ if (isAutofill && isEmail(login.email, { requireTLD: true }) && precheckResponse.status === 'pending') {+ precheck({ email: login.email })+ }+ }, [login.email, prevEmail, precheckResponse.status, precheck])++ return (+ <LemonField.Pure label="Email" htmlFor="auth-email" error={emailError}>+ <LemonInput+ id="auth-email"+ className="ph-ignore-input"+ // pinned: Playwright and autocapture select these per entry URL+ data-attr={entry === 'signup' ? 'signup-email' : 'login-email'}+ type="email"+ autoFocus+ placeholder="[email protected]"+ // The `webauthn` token enables passkey autofill (conditional UI),+ // which we only offer on WebKit; elsewhere the auto-modal handles passkeys.+ autoComplete={isWebKitBrowser() ? 'username webauthn' : 'username'}+ value={login.email}+ onChange={(value) => setLoginValue('email', value)}+ status={emailError ? 'danger' : 'default'}+ fullWidth+ />+ </LemonField.Pure>+ )+}diff --git a/frontend/src/scenes/authentication/auth/components/CreateAccountTerms.tsx b/frontend/src/scenes/authentication/auth/components/CreateAccountTerms.tsxnew file mode 100644index 000000000000..fc4d8857809e--- /dev/null+++ b/frontend/src/scenes/authentication/auth/components/CreateAccountTerms.tsx@@ -0,0 +1,17 @@+import { Link } from 'lib/lemon-ui/Link'++export function CreateAccountTerms(): JSX.Element {+ return (+ <p className="AuthScene__terms mt-5 mb-0 text-xs leading-relaxed text-tertiary text-center">+ <span>By creating an account, you agree to our</span>{' '}+ <Link to="https://posthog.com/terms" target="_blank">+ Terms of Service ↗+ </Link>{' '}+ <span>and</span>{' '}+ <Link to="https://posthog.com/privacy" target="_blank">+ Privacy Policy ↗+ </Link>+ <span>.</span>+ </p>+ )+}diff --git a/frontend/src/scenes/authentication/auth/components/EmailStepSocialButtons.tsx b/frontend/src/scenes/authentication/auth/components/EmailStepSocialButtons.tsxnew file mode 100644index 000000000000..a46104272b58--- /dev/null+++ b/frontend/src/scenes/authentication/auth/components/EmailStepSocialButtons.tsx@@ -0,0 +1,64 @@+import { useValues } from 'kea'++import { SocialLoginButtons } from 'lib/components/SocialLoginButton/SocialLoginButton'+import { useLastLoginMethod } from 'scenes/authentication/shared/lastLoginMethod'+import { preflightLogic } from 'scenes/PreflightCheck/preflightLogic'++import { authLogic } from '../authLogic'+import { PrecheckResponseType, loginLogic } from '../loginLogic'++// A new person here signs in through the IdP. SAML normally replaces this row, but an account+// without a password still needs to see whatever methods it does have.+function hidesLoginRow(+ precheck: PrecheckResponseType,+ accountExists: boolean | null,+ isPasswordLoginUnavailable: boolean+): boolean {+ return (+ accountExists === false ||+ !!precheck.sso_enforcement ||+ (precheck.saml_available && !isPasswordLoginUnavailable)+ )+}++export function EmailStepSocialButtons(): JSX.Element | null {+ const { entry, step, accountExists } = useValues(authLogic)+ const { precheckResponse, isPasswordLoginUnavailable, restrictToProviders } = useValues(loginLogic)+ const { preflight } = useValues(preflightLogic)+ const lastLoginMethod = useLastLoginMethod()++ if (step === 'signup_credentials') {+ return preflight?.demo ? null : (+ <SocialLoginButtons topDivider caption="or sign up with" captionLocation="top" />+ )+ }+ if (step === 'login') {+ if (hidesLoginRow(precheckResponse, accountExists, isPasswordLoginUnavailable)) {+ return null+ }+ return (+ <SocialLoginButtons+ topDivider+ caption={isPasswordLoginUnavailable ? 'Log in with' : 'or log in with'}+ captionLocation="top"+ lastUsedProvider={lastLoginMethod}+ restrictToProviders={restrictToProviders}+ // Once we know the account's methods, only offer a passkey if it actually has+ // one — otherwise this is the same dead button we're removing.+ showPasskey={!isPasswordLoginUnavailable || !!precheckResponse.webauthn_credentials?.length}+ />+ )+ }+ if (preflight?.demo) {+ return null+ }+ return (+ <SocialLoginButtons+ topDivider+ caption="or continue with"+ captionLocation="top"+ lastUsedProvider={lastLoginMethod}+ showPasskey={entry === 'login'}+ />+ )+}diff --git a/frontend/src/scenes/authentication/auth/components/EmailStepSubmitButton.tsx b/frontend/src/scenes/authentication/auth/components/EmailStepSubmitButton.tsxnew file mode 100644index 000000000000..48a3bde43a7c--- /dev/null+++ b/frontend/src/scenes/authentication/auth/components/EmailStepSubmitButton.tsx@@ -0,0 +1,62 @@+import { useValues } from 'kea'++import { LemonButton } from 'lib/lemon-ui/LemonButton'++import { authLogic } from '../authLogic'+import { loginLogic } from '../loginLogic'+import { signupLogic } from '../signupLogic'++export function EmailStepSubmitButton(): JSX.Element | null {+ const { entry, step, isEmailSubmitting, isLoginPasswordHidden } = useValues(authLogic)+ const { isLoginSubmitting } = useValues(loginLogic)+ const { validatedPassword, passkeyRegistered, isSignupPanelAuthSubmitting } = useValues(signupLogic)++ if (step === 'login') {+ return isLoginPasswordHidden ? null : (+ <LemonButton+ type="primary"+ size="large"+ center+ fullWidth+ htmlType="submit"+ data-attr="password-login"+ loading={isLoginSubmitting}+ >+ Log in+ </LemonButton>+ )+ }+ if (step === 'signup_credentials') {+ return (+ <LemonButton+ type="primary"+ size="large"+ center+ fullWidth+ htmlType="submit"+ // pinned: Playwright and the signup funnel select the account creation submit by this+ data-attr="signup-auth-continue"+ loading={isSignupPanelAuthSubmitting}+ disabledReason={+ !passkeyRegistered && validatedPassword.feedback ? validatedPassword.feedback : undefined+ }+ >+ Create account+ </LemonButton>+ )+ }+ return (+ <LemonButton+ type="primary"+ size="large"+ center+ fullWidth+ htmlType="submit"+ // pinned: `signup-start` is the signup funnel's existing first-step attribute+ data-attr={entry === 'signup' ? 'signup-start' : 'login-email-continue'}+ loading={isEmailSubmitting}+ >+ Continue+ </LemonButton>+ )+}diff --git a/frontend/src/scenes/authentication/auth/components/EmailStepTitle.tsx b/frontend/src/scenes/authentication/auth/components/EmailStepTitle.tsxnew file mode 100644index 000000000000..8772b41047d5--- /dev/null+++ b/frontend/src/scenes/authentication/auth/components/EmailStepTitle.tsx@@ -0,0 +1,95 @@+import { useValues } from 'kea'++import { AuthCardTitle } from 'scenes/authentication/shared/authScene/AuthCardTitle'+import { useLastLoginMethod } from 'scenes/authentication/shared/lastLoginMethod'+import { pendingOAuthConnectionLogic } from 'scenes/authentication/shared/pendingOAuthConnectionLogic'++import { authLogic, hasSingleSignOn } from '../authLogic'+import { loginLogic } from '../loginLogic'+import { ConnectTitle } from './ConnectTitle'+import { HighlightedName } from './HighlightedName'++function LoginTitle(): JSX.Element {+ const { precheckResponse } = useValues(loginLogic)+ const { entry, accountExists } = useValues(authLogic)+ const { pendingConnection } = useValues(pendingOAuthConnectionLogic)++ const greeting =+ accountExists === false+ ? 'Nice to meet you.'+ : accountExists === null+ ? 'Hi there.'+ : entry === 'signup'+ ? 'Plot twist: this email already has an account.'+ : 'Good to see you.'++ if (pendingConnection) {+ return (+ <AuthCardTitle+ title={<ConnectTitle lead="Log in to connect" clientName={pendingConnection.clientName} />}+ sub={greeting}+ />+ )+ }+ if (accountExists === false) {+ return (+ <AuthCardTitle+ title={hasSingleSignOn(precheckResponse) ? 'Your team uses single sign-on' : 'No account here yet'}+ sub={greeting}+ />+ )+ }+ return <AuthCardTitle title={accountExists === null ? 'Log in' : 'Welcome back'} sub={greeting} />+}++function SignupTitle(): JSX.Element {+ const { pendingConnection } = useValues(pendingOAuthConnectionLogic)++ return (+ <AuthCardTitle+ title={+ pendingConnection ? (+ <ConnectTitle lead="Create your account to connect" clientName={pendingConnection.clientName} />+ ) : (+ 'Create your account'+ )+ }+ sub="There's no account for this email yet. Choose a password to create one."+ />+ )+}++export function EmailStepTitle(): JSX.Element {+ const { entry, step } = useValues(authLogic)+ const { pendingConnection } = useValues(pendingOAuthConnectionLogic)+ const isReturning = useLastLoginMethod() !== null++ if (step === 'login') {+ return <LoginTitle />+ }+ if (step === 'signup_credentials') {+ return <SignupTitle />+ }+ if (pendingConnection) {+ return (+ <AuthCardTitle+ title={<ConnectTitle lead="Log in or sign up to connect" clientName={pendingConnection.clientName} />}+ sub={`${pendingConnection.clientName} saved you a seat.`}+ />+ )+ }+ if (entry === 'signup') {+ return <AuthCardTitle title="Get started" sub="Make your product self-driving." />+ }+ return (+ <AuthCardTitle+ title={+ <>+ <span>{isReturning ? 'Log in to ' : 'Log in or sign up to '}</span>+ <HighlightedName>@PostHog</HighlightedName>+ </>+ }+ sub={isReturning ? "Welcome back. Let's go ship something." : 'Hedgehogs of all kinds welcome.'}+ />+ )+}diff --git a/frontend/src/scenes/authentication/auth/components/EmailTakenNotice.tsx b/frontend/src/scenes/authentication/auth/components/EmailTakenNotice.tsxnew file mode 100644index 000000000000..e0a8cb954fa4--- /dev/null+++ b/frontend/src/scenes/authentication/auth/components/EmailTakenNotice.tsx@@ -0,0 +1,27 @@+import { useActions, useValues } from 'kea'++import { Link } from 'lib/lemon-ui/Link'++import { authLogic } from '../authLogic'+import { signupLogic } from '../signupLogic'++export function EmailTakenNotice(): JSX.Element | null {+ const { signupEmailTaken } = useValues(signupLogic)+ const { chooseAccountPath } = useActions(authLogic)++ if (!signupEmailTaken) {+ return null+ }+ return (+ <p className="-mt-2 mb-0 text-sm text-secondary">+ <Link+ onClick={() => chooseAccountPath('login', true)}+ data-attr="auth-email-taken-login"+ className="font-semibold no-underline cursor-pointer hover:underline hover:underline-offset-2 text-warning"+ >+ Log in instead+ </Link>+ <span>. Signed up with a version of this address with dots or a +tag? Log in with that one.</span>+ </p>+ )+}diff --git a/frontend/src/scenes/authentication/auth/components/JoinOrganizationHint.tsx b/frontend/src/scenes/authentication/auth/components/JoinOrganizationHint.tsxnew file mode 100644index 000000000000..f210fda850af--- /dev/null+++ b/frontend/src/scenes/authentication/auth/components/JoinOrganizationHint.tsx@@ -0,0 +1,35 @@+import { useValues } from 'kea'+import { useState } from 'react'++import { AuthBanner } from 'scenes/authentication/shared/authScene/AuthBanner'+import { preflightLogic } from 'scenes/PreflightCheck/preflightLogic'++import { authLogic } from '../authLogic'++export function JoinOrganizationHint(): JSX.Element | null {+ const { entry, step } = useValues(authLogic)+ const { preflight } = useValues(preflightLogic)+ const [showJoinOrg, setShowJoinOrg] = useState(false)++ if (step !== 'email' || entry !== 'signup' || preflight?.demo) {+ return null+ }+ return (+ <div className="mt-4 text-center">+ <button+ type="button"+ data-attr="signup-join-existing-org"+ className="font-semibold no-underline cursor-pointer hover:underline hover:underline-offset-2 text-secondary text-xs"+ onClick={() => setShowJoinOrg((v) => !v)}+ >+ Trying to join an existing organization?+ </button>+ {showJoinOrg && (+ <AuthBanner variant="note" className="mt-3">+ You'll need your invite link. When a teammate invites you, we email you a personal link. Didn't get+ one? Check spam, or ask them to resend it from their members settings.+ </AuthBanner>+ )}+ </div>+ )+}diff --git a/frontend/src/scenes/authentication/auth/components/LoginPasswordField.tsx b/frontend/src/scenes/authentication/auth/components/LoginPasswordField.tsxnew file mode 100644index 000000000000..a3af99871f37--- /dev/null+++ b/frontend/src/scenes/authentication/auth/components/LoginPasswordField.tsx@@ -0,0 +1,81 @@+import { useActions, useValues } from 'kea'++import { SSO_PROVIDER_NAMES } from 'lib/constants'+import { LemonField } from 'lib/lemon-ui/LemonField'+import { LemonInput } from 'lib/lemon-ui/LemonInput/LemonInput'+import { Link } from 'lib/lemon-ui/Link'+import { AuthBanner } from 'scenes/authentication/shared/authScene/AuthBanner'+import { urls } from 'scenes/urls'++import { authLogic, hasSingleSignOn } from '../authLogic'+import { loginLogic } from '../loginLogic'++export function LoginPasswordField(): JSX.Element {+ const { accountExists, isLoginPasswordHidden } = useValues(authLogic)+ const { login, loginErrors, precheckResponse, hasNoConfiguredLoginMethod, autoRedirectingToProvider } =+ useValues(loginLogic)+ const { setLoginValue } = useActions(loginLogic)++ return (+ // `empty:hidden` drops the top padding for an SSO-only account, which has nothing to show here+ <div className="flex flex-col gap-4 pt-4 empty:hidden">+ {!isLoginPasswordHidden && (+ <LemonField.Pure+ htmlFor="auth-login-password"+ label={+ <div className="flex items-baseline justify-between w-full">+ <span>Password</span>+ <Link+ to={[urls.passwordReset(), { email: login.email }]}+ data-attr="forgot-password"+ className="text-xs font-semibold text-warning"+ tabIndex={-1}+ >+ Forgot password?+ </Link>+ </div>+ }+ error={loginErrors.password}+ >+ <LemonInput+ id="auth-login-password"+ className="ph-ignore-input"+ data-attr="password"+ type="password"+ autoFocus+ autoComplete="current-password"+ value={login.password}+ onChange={(value) => setLoginValue('password', value)}+ status={loginErrors.password ? 'danger' : 'default'}+ fullWidth+ />+ </LemonField.Pure>+ )}+ {accountExists === false && !hasSingleSignOn(precheckResponse) && (+ <AuthBanner variant="note">+ There's no account for this email. Ask your PostHog admin for an invite.+ </AuthBanner>+ )}+ {hasNoConfiguredLoginMethod && (+ <AuthBanner variant="warning">+ <span>No sign-in method is set up for this account. Use</span>{' '}+ <Link+ to={[urls.passwordReset(), { email: login.email }]}+ // Autocapture reports the click. Each reset entry point has its+ // own `data-attr`, so one funnel can tell them apart.+ data-attr="login-no-method-reset-password"+ className="font-semibold no-underline cursor-pointer hover:underline hover:underline-offset-2 text-warning"+ >+ Forgot password?+ </Link>{' '}+ <span>to set a password by email.</span>+ </AuthBanner>+ )}+ {autoRedirectingToProvider && (+ <p className="text-sm text-secondary text-center mb-0">+ Redirecting to {SSO_PROVIDER_NAMES[autoRedirectingToProvider]}…+ </p>+ )}+ </div>+ )+}diff --git a/frontend/src/scenes/authentication/auth/components/LoginSignupLink.tsx b/frontend/src/scenes/authentication/auth/components/LoginSignupLink.tsxnew file mode 100644index 000000000000..c9c12770dfb1--- /dev/null+++ b/frontend/src/scenes/authentication/auth/components/LoginSignupLink.tsx@@ -0,0 +1,46 @@+import { useActions, useValues } from 'kea'++import { Link } from 'lib/lemon-ui/Link'++import { authLogic } from '../authLogic'++const LINK_CLASS_NAME =+ 'font-semibold no-underline cursor-pointer hover:underline hover:underline-offset-2 text-warning'++export function LoginSignupLink(): JSX.Element | null {+ const { canSignUpWithEmail, accountExists } = useValues(authLogic)+ const { chooseAccountPath } = useActions(authLogic)++ if (!canSignUpWithEmail) {+ return null+ }+ // The precheck failed, so this may be a new person. Signup still refuses an email that has an account.+ if (accountExists === null) {+ return (+ <p className="mt-4 mb-0 text-sm text-secondary text-center">+ <span>New to PostHog?</span>{' '}+ <Link+ onClick={() => chooseAccountPath('signup', null)}+ data-attr="auth-unknown-account-signup"+ className={LINK_CLASS_NAME}+ >+ Create an account+ </Link>+ </p>+ )+ }+ if (accountExists === false) {+ return (+ <p className="mt-4 mb-0 text-sm text-secondary text-center">+ <Link+ onClick={() => chooseAccountPath('signup', false)}+ data-attr="auth-sso-domain-signup-with-email"+ className={LINK_CLASS_NAME}+ >+ Sign up with email instead+ </Link>+ </p>+ )+ }+ return null+}diff --git a/frontend/src/scenes/authentication/auth/components/LoginSingleSignOnButtons.tsx b/frontend/src/scenes/authentication/auth/components/LoginSingleSignOnButtons.tsxnew file mode 100644index 000000000000..6d708d1b7981--- /dev/null+++ b/frontend/src/scenes/authentication/auth/components/LoginSingleSignOnButtons.tsx@@ -0,0 +1,29 @@+import { useValues } from 'kea'++import { SSOEnforcedLoginButton } from 'lib/components/SocialLoginButton/SocialLoginButton'+import { useLastLoginMethod } from 'scenes/authentication/shared/lastLoginMethod'++import { loginLogic } from '../loginLogic'++export function LoginSingleSignOnButtons(): JSX.Element {+ const { precheckResponse, login } = useValues(loginLogic)+ const lastLoginMethod = useLastLoginMethod()++ return (+ <>+ {precheckResponse.sso_enforcement && (+ <SSOEnforcedLoginButton+ provider={precheckResponse.sso_enforcement}+ email={login.email}+ isLastUsed={lastLoginMethod === precheckResponse.sso_enforcement}+ />+ )}+ {precheckResponse.saml_available && !precheckResponse.sso_enforcement && (+ <SSOEnforcedLoginButton provider="saml" email={login.email} isLastUsed={lastLoginMethod === 'saml'} />+ )}+ {precheckResponse.oidc_available && !precheckResponse.sso_enforcement && (+ <SSOEnforcedLoginButton provider="oidc" email={login.email} isLastUsed={lastLoginMethod === 'oidc'} />+ )}+ </>+ )+}diff --git a/frontend/src/scenes/authentication/auth/components/SignupPasswordField.tsx b/frontend/src/scenes/authentication/auth/components/SignupPasswordField.tsxnew file mode 100644index 000000000000..78826ea35d55--- /dev/null+++ b/frontend/src/scenes/authentication/auth/components/SignupPasswordField.tsx@@ -0,0 +1,68 @@+import { useActions, useValues } from 'kea'++import PasswordStrength from 'lib/components/PasswordStrength'+import passkeyLogo from 'lib/components/SocialLoginButton/passkey.svg'+import { LemonButton } from 'lib/lemon-ui/LemonButton'+import { LemonField } from 'lib/lemon-ui/LemonField'+import { LemonInput } from 'lib/lemon-ui/LemonInput/LemonInput'+import { AuthBanner } from 'scenes/authentication/shared/authScene/AuthBanner'++import { signupLogic } from '../signupLogic'++export function SignupPasswordField(): JSX.Element {+ const {+ signupPanelAuth,+ signupPanelAuthErrors,+ validatedPassword,+ passkeyRegistered,+ isPasskeyRegistering,+ passkeyError,+ } = useValues(signupLogic)+ const { setSignupPanelAuthValue, registerPasskey } = useActions(signupLogic)++ return (+ <div className="flex flex-col gap-2 pt-4">+ {passkeyError && <AuthBanner variant="danger">{passkeyError}</AuthBanner>}+ {passkeyRegistered ? (+ <AuthBanner variant="success">Passkey registered. Continue below.</AuthBanner>+ ) : (+ <>+ <LemonField.Pure+ htmlFor="auth-signup-password"+ label={+ <div className="flex items-baseline justify-between w-full">+ <span>Choose a password</span>+ <PasswordStrength validatedPassword={validatedPassword} />+ </div>+ }+ error={signupPanelAuthErrors.password}+ >+ <LemonInput+ id="auth-signup-password"+ className="ph-ignore-input"+ data-attr="password"+ type="password"+ autoFocus+ autoComplete="new-password"+ value={signupPanelAuth.password}+ onChange={(value) => setSignupPanelAuthValue('password', value)}+ status={signupPanelAuthErrors.password ? 'danger' : 'default'}+ fullWidth+ />+ </LemonField.Pure>+ <LemonButton+ type="tertiary"+ size="small"+ icon={<img src={passkeyLogo} alt="" className="object-contain w-5 h-5" />}+ onClick={registerPasskey}+ loading={isPasskeyRegistering}+ data-attr="signup-passkey"+ className="self-start"+ >+ Use a passkey instead+ </LemonButton>+ </>+ )}+ </div>+ )+}diff --git a/frontend/src/scenes/authentication/auth/loginLogic.ts b/frontend/src/scenes/authentication/auth/loginLogic.tsindex 4716445bfe5b..ec8edf14c396 100644--- a/frontend/src/scenes/authentication/auth/loginLogic.ts+++ b/frontend/src/scenes/authentication/auth/loginLogic.ts@@ -217,7 +217,6 @@ export interface CodeVerificationForm {export interface loginLogicValues {devLoginTimeSavedLabel: string | null // devLoginLogicdevUsers: DevUser[] // devLoginLogic- devUsersLoading: boolean // devLoginLogicfeatureFlags: FeatureFlagsSet // featureFlagLogicpreflight: PreflightStatus | null // preflightLogicautoRedirectAttemptedForEmail: string | null@@ -272,7 +271,6 @@ export interface loginLogicActions {devLogin: (email: string) => {email: string} // devLoginLogic- loadDevUsers: (_: any) => any // devLoginLogicclearGeneralError: () => {value: true}@@ -447,9 +445,9 @@ export const loginLogic = kea<loginLogicType>([featureFlagLogic,['featureFlags'],devLoginLogic,- ['devUsers', 'devUsersLoading', 'devLoginTimeSavedLabel'],+ ['devUsers', 'devLoginTimeSavedLabel'],],- actions: [devLoginLogic, ['devLogin', 'loadDevUsers']],+ actions: [devLoginLogic, ['devLogin']],})),actions({setGeneralError: (code: string, detail: string) => ({ code, detail }),diff --git a/frontend/src/scenes/authentication/auth/signupLogic.ts b/frontend/src/scenes/authentication/auth/signupLogic.tsindex c7922fec54a5..642ae169fee1 100644--- a/frontend/src/scenes/authentication/auth/signupLogic.ts+++ b/frontend/src/scenes/authentication/auth/signupLogic.ts@@ -610,7 +610,9 @@ export const signupLogic = kea<signupLogicType>([listeners(({ actions, values }) => ({precheckSignupEmail: async ({ email }, breakpoint) => {actions.setPasskeyError(null)- actions.setSignupPanelAuthManualErrors({})+ // Reset rather than `setSignupPanelAuthManualErrors({})`: kea-forms turns error display on with+ // any manual errors call, so the empty password field would open with a red error+ actions.resetSignupPanelAuth()let precheckResponse: SignupEmailPrecheckResponsetry {// nosemgrep: prefer-codegen-api -- Legacy raw API call with a hand-written URL and an unchecked response type. No generated function covers this endpoint yet. Find out why the generated client skips it (no schema, no product tag, or excluded from the spec) and fix that first.diff --git a/frontend/src/scenes/authentication/auth/steps/EmailStep.tsx b/frontend/src/scenes/authentication/auth/steps/EmailStep.tsxindex 368dc321b29b..819bce574659 100644--- a/frontend/src/scenes/authentication/auth/steps/EmailStep.tsx+++ b/frontend/src/scenes/authentication/auth/steps/EmailStep.tsx@@ -1,166 +1,77 @@import { useActions, useValues } from 'kea'-import { useEffect, useState } from 'react'-import { SocialLoginButtons } from 'lib/components/SocialLoginButton/SocialLoginButton'-import { usePrevious } from 'lib/hooks/usePrevious'-import { LemonButton } from 'lib/lemon-ui/LemonButton'-import { LemonField } from 'lib/lemon-ui/LemonField'-import { LemonInput } from 'lib/lemon-ui/LemonInput/LemonInput'-import { Link } from 'lib/lemon-ui/Link'-import { isWebKitBrowser } from 'lib/utils/dom'-import { isEmail } from 'lib/utils/url'-import { AuthBanner } from 'scenes/authentication/shared/authScene/AuthBanner'-import { AuthCardTitle } from 'scenes/authentication/shared/authScene/AuthCardTitle'+import { AnimatedCollapsible } from 'lib/components/AnimatedCollapsible'import { AuthSceneCard } from 'scenes/authentication/shared/authScene/AuthScene'import { RegionField } from 'scenes/authentication/shared/authScene/RegionField'-import { useLastLoginMethod } from 'scenes/authentication/shared/lastLoginMethod'-import { pendingOAuthConnectionLogic } from 'scenes/authentication/shared/pendingOAuthConnectionLogic'-import { preflightLogic } from 'scenes/PreflightCheck/preflightLogic'import { authLogic } from '../authLogic'-import { ConnectTitle } from '../components/ConnectTitle'-import { HighlightedName } from '../components/HighlightedName'+import { AuthEmailField } from '../components/AuthEmailField'+import { CreateAccountTerms } from '../components/CreateAccountTerms'+import { EmailStepSocialButtons } from '../components/EmailStepSocialButtons'+import { EmailStepSubmitButton } from '../components/EmailStepSubmitButton'+import { EmailStepTitle } from '../components/EmailStepTitle'+import { EmailTakenNotice } from '../components/EmailTakenNotice'+import { JoinOrganizationHint } from '../components/JoinOrganizationHint'import { LoginErrorBanner } from '../components/LoginErrorBanner'+import { LoginPasswordField } from '../components/LoginPasswordField'+import { LoginSignupLink } from '../components/LoginSignupLink'+import { LoginSingleSignOnButtons } from '../components/LoginSingleSignOnButtons'+import { OtherRegionNotice } from '../components/OtherRegionNotice'import { SessionRiskBanner } from '../components/SessionRiskBanner'+import { SignupPasswordField } from '../components/SignupPasswordField'import { loginLogic } from '../loginLogic'import { signupLogic } from '../signupLogic'-function EmailStepTitle(): JSX.Element {- const { entry } = useValues(authLogic)- const { pendingConnection } = useValues(pendingOAuthConnectionLogic)- const isReturning = useLastLoginMethod() !== null-- if (pendingConnection) {- return (- <AuthCardTitle- title={<ConnectTitle lead="Log in or sign up to connect" clientName={pendingConnection.clientName} />}- sub={`${pendingConnection.clientName} saved you a seat.`}- />- )- }- if (entry === 'signup') {- return <AuthCardTitle title="Get started" sub="Make your product self-driving." />- }- return (- <AuthCardTitle- title={- <>- <span>{isReturning ? 'Log in to ' : 'Log in or sign up to '}</span>- <HighlightedName>@PostHog</HighlightedName>- </>- }- sub={isReturning ? "Welcome back. Let's go ship something." : 'Hedgehogs of all kinds welcome.'}- />- )-}-+/**+ * The email card. It also renders the `login` and `signup_credentials` steps, so once the precheck+ * answers, the password for that path opens under the email field instead of on a new screen.+ */export function EmailStep(): JSX.Element {- const { login, precheckResponse } = useValues(loginLogic)- const { setLoginValue, precheck } = useActions(loginLogic)- const { entry, emailError, isEmailSubmitting } = useValues(authLogic)- const { continueWithEmail, chooseAccountPath } = useActions(authLogic)- const { signupEmailTaken } = useValues(signupLogic)- const { preflight } = useValues(preflightLogic)- const lastLoginMethod = useLastLoginMethod()- const prevEmail = usePrevious(login.email)- const [showJoinOrg, setShowJoinOrg] = useState(false)-- // An autofilled address is prechecked at once, so a passkey prompt can open before Continue- useEffect(() => {- const charDelta = login.email.length - (prevEmail?.length ?? 0)- const isAutofill = charDelta > 1-- if (isAutofill && isEmail(login.email, { requireTLD: true }) && precheckResponse.status === 'pending') {- precheck({ email: login.email })- }- }, [login.email, prevEmail, precheckResponse.status, precheck])+ const { login, generalError } = useValues(loginLogic)+ const { step } = useValues(authLogic)+ const { submitEmailStep } = useActions(authLogic)+ const { signupEmail } = useValues(signupLogic)return (- <AuthSceneCard showPendingConnection>+ <AuthSceneCard+ footer={step === 'signup_credentials' ? <CreateAccountTerms /> : undefined}+ showPendingConnection+ ><EmailStepTitle /><SessionRiskBanner className="mb-4" /><LoginErrorBanner />+ {step === 'login' && generalError?.code === 'invalid_credentials' && (+ <OtherRegionNotice email={login.email} reason="login_failed" />+ )}<formclassName="flex flex-col gap-4"noValidateonSubmit={(e) => {e.preventDefault()- continueWithEmail()+ submitEmailStep()}}><RegionField />- <LemonField.Pure label="Email" htmlFor="auth-email" error={emailError}>- <LemonInput- id="auth-email"- className="ph-ignore-input"- // pinned: Playwright and autocapture select these per entry URL- data-attr={entry === 'signup' ? 'signup-email' : 'login-email'}- type="email"- autoFocus- placeholder="[email protected]"- // The `webauthn` token enables passkey autofill (conditional UI),- // which we only offer on WebKit; elsewhere the auto-modal handles passkeys.- autoComplete={isWebKitBrowser() ? 'username webauthn' : 'username'}- value={login.email}- onChange={(value) => setLoginValue('email', value)}- status={emailError ? 'danger' : 'default'}- fullWidth- />- </LemonField.Pure>- {signupEmailTaken && (- <p className="-mt-2 mb-0 text-sm text-secondary">- <Link- onClick={() => chooseAccountPath('login', true)}- data-attr="auth-email-taken-login"- className="font-semibold no-underline cursor-pointer hover:underline hover:underline-offset-2 text-warning"- >- Log in instead- </Link>- <span>- . Signed up with a version of this address with dots or a +tag? Log in with that one.- </span>- </p>- )}- <LemonButton- type="primary"- size="large"- center- fullWidth- htmlType="submit"- // pinned: `signup-start` is the signup funnel's existing first-step attribute- data-attr={entry === 'signup' ? 'signup-start' : 'login-email-continue'}- loading={isEmailSubmitting}- >- Continue- </LemonButton>- </form>- {!preflight?.demo && (- <SocialLoginButtons- topDivider- caption="or continue with"- captionLocation="top"- lastUsedProvider={lastLoginMethod}- showPasskey={entry === 'login'}- />- )}- {entry === 'signup' && !preflight?.demo && (- <div className="mt-4 text-center">- <button- type="button"- data-attr="signup-join-existing-org"- className="font-semibold no-underline cursor-pointer hover:underline hover:underline-offset-2 text-secondary text-xs"- onClick={() => setShowJoinOrg((v) => !v)}- >- Trying to join an existing organization?- </button>- {showJoinOrg && (- <AuthBanner variant="note" className="mt-3">- You'll need your invite link. When a teammate invites you, we email you a personal link.- Didn't get one? Check spam, or ask them to resend it from their members settings.- </AuthBanner>- )}+ <div className="flex flex-col">+ <AuthEmailField />+ <AnimatedCollapsible collapsed={step === 'email'} autoHeight>+ {step === 'login' ? (+ <LoginPasswordField />+ ) : step === 'signup_credentials' ? (+ <SignupPasswordField />+ ) : (+ <></>+ )}+ </AnimatedCollapsible></div>- )}+ <EmailTakenNotice />+ <EmailStepSubmitButton />+ {step === 'login' && <LoginSingleSignOnButtons />}+ {step === 'signup_credentials' && <OtherRegionNotice email={signupEmail} reason="no_account" />}+ </form>+ {step === 'login' && <LoginSignupLink />}+ <EmailStepSocialButtons />+ <JoinOrganizationHint /></AuthSceneCard>)}diff --git a/frontend/src/scenes/authentication/auth/steps/LoginStep.tsx b/frontend/src/scenes/authentication/auth/steps/LoginStep.tsxdeleted file mode 100644index 0653bfd281c2..000000000000--- a/frontend/src/scenes/authentication/auth/steps/LoginStep.tsx+++ /dev/null@@ -1,242 +0,0 @@-import { useActions, useValues } from 'kea'-import { Form } from 'kea-forms'--import { SocialLoginButtons, SSOEnforcedLoginButton } from 'lib/components/SocialLoginButton/SocialLoginButton'-import { SSO_PROVIDER_NAMES } from 'lib/constants'-import { LemonButton } from 'lib/lemon-ui/LemonButton'-import { LemonField } from 'lib/lemon-ui/LemonField'-import { LemonInput } from 'lib/lemon-ui/LemonInput/LemonInput'-import { Link } from 'lib/lemon-ui/Link'-import { AuthBanner } from 'scenes/authentication/shared/authScene/AuthBanner'-import { AuthCardTitle } from 'scenes/authentication/shared/authScene/AuthCardTitle'-import { AuthSceneCard } from 'scenes/authentication/shared/authScene/AuthScene'-import { useLastLoginMethod } from 'scenes/authentication/shared/lastLoginMethod'-import { pendingOAuthConnectionLogic } from 'scenes/authentication/shared/pendingOAuthConnectionLogic'-import { urls } from 'scenes/urls'--import { authLogic } from '../authLogic'-import { ConnectTitle } from '../components/ConnectTitle'-import { LoginErrorBanner } from '../components/LoginErrorBanner'-import { OtherRegionNotice } from '../components/OtherRegionNotice'-import { UseDifferentEmailLink } from '../components/UseDifferentEmailLink'-import { PrecheckResponseType, loginLogic } from '../loginLogic'--function hasSingleSignOn(precheck: PrecheckResponseType): boolean {- return !!precheck.sso_enforcement || precheck.saml_available || !!precheck.oidc_available-}--function LoginStepTitle(): JSX.Element {- const { login, precheckResponse } = useValues(loginLogic)- const { entry, accountExists } = useValues(authLogic)- const { pendingConnection } = useValues(pendingOAuthConnectionLogic)- const email = <span className="AuthScene__mono">{login.email}</span>-- const greeting =- accountExists === false ? (- <>- <span>Nice to meet you,</span> {email}- <span>.</span>- </>- ) : accountExists === null ? (- <>- <span>Hi,</span> {email}- <span>.</span>- </>- ) : entry === 'signup' ? (- <>- <span>Plot twist:</span> {email} <span>already has an account.</span>- </>- ) : (- <>- <span>Good to see you,</span> {email}- <span>.</span>- </>- )- if (pendingConnection) {- return (- <AuthCardTitle- title={<ConnectTitle lead="Log in to connect" clientName={pendingConnection.clientName} />}- sub={greeting}- />- )- }- if (accountExists === false) {- return (- <AuthCardTitle- title={hasSingleSignOn(precheckResponse) ? 'Your team uses single sign-on' : 'No account here yet'}- sub={greeting}- />- )- }- return <AuthCardTitle title={accountExists === null ? 'Log in' : 'Welcome back'} sub={greeting} />-}--export function LoginStep(): JSX.Element {- const { chooseAccountPath } = useActions(authLogic)- const { canSignUpWithEmail, accountExists } = useValues(authLogic)- const {- precheckResponse,- login,- isLoginSubmitting,- generalError,- isPasswordLoginUnavailable,- hasNoConfiguredLoginMethod,- restrictToProviders,- autoRedirectingToProvider,- } = useValues(loginLogic)- const lastLoginMethod = useLastLoginMethod()-- // A new person reaches this step on a SAML or OIDC domain, where the IdP creates the account, or- // where nobody may sign up with email, such as a self-hosted instance with signups off- const isNewAccount = accountExists === false- // The precheck failed, so this may be a new person. Signup still refuses an email that has an account.- const isAccountUnknown = accountExists === null- const isPasswordHidden = !!precheckResponse.sso_enforcement || isPasswordLoginUnavailable || isNewAccount-- return (- <AuthSceneCard footer={<UseDifferentEmailLink />} showPendingConnection>- <LoginStepTitle />- <LoginErrorBanner />- {generalError?.code === 'invalid_credentials' && (- <OtherRegionNotice email={login.email} reason="login_failed" />- )}- <Form logic={loginLogic} formKey="login" enableFormOnSubmit className="flex flex-col gap-4">- {/* Password managers pair the saved password with this username */}- <input type="email" name="email" autoComplete="username" value={login.email} readOnly hidden />- {!isPasswordHidden && (- <LemonField- name="password"- label={- <div className="flex items-baseline justify-between w-full">- <span>Password</span>- <Link- to={[urls.passwordReset(), { email: login.email }]}- data-attr="forgot-password"- className="text-xs font-semibold text-warning"- tabIndex={-1}- >- Forgot password?- </Link>- </div>- }- >- {({ value, onChange, error, id }) => (- <LemonInput- id={id}- className="ph-ignore-input"- data-attr="password"- type="password"- autoFocus- placeholder="••••••••••"- autoComplete="current-password"- value={value ?? ''}- onChange={onChange}- status={error ? 'danger' : 'default'}- fullWidth- />- )}- </LemonField>- )}- {isNewAccount && !hasSingleSignOn(precheckResponse) && (- <AuthBanner variant="note">- There's no account for this email. Ask your PostHog admin for an invite.- </AuthBanner>- )}- {hasNoConfiguredLoginMethod && (- <AuthBanner variant="warning">- <span>No sign-in method is set up for this account. Use</span>{' '}- <Link- to={[urls.passwordReset(), { email: login.email }]}- // Autocapture reports the click. Each reset entry point has its- // own `data-attr`, so one funnel can tell them apart.- data-attr="login-no-method-reset-password"- className="font-semibold no-underline cursor-pointer hover:underline hover:underline-offset-2 text-warning"- >- Forgot password?- </Link>{' '}- <span>to set a password by email.</span>- </AuthBanner>- )}- {autoRedirectingToProvider && (- <p className="text-sm text-secondary text-center mb-0">- Redirecting to {SSO_PROVIDER_NAMES[autoRedirectingToProvider]}…- </p>- )}- {/* No password to submit means this button would do nothing */}- {!isPasswordHidden && (- <LemonButton- type="primary"- size="large"- center- fullWidth- htmlType="submit"- data-attr="password-login"- loading={isLoginSubmitting}- >- Log in- </LemonButton>- )}- {precheckResponse.sso_enforcement && (- <SSOEnforcedLoginButton- provider={precheckResponse.sso_enforcement}- email={login.email}- isLastUsed={lastLoginMethod === precheckResponse.sso_enforcement}- />- )}- {precheckResponse.saml_available && !precheckResponse.sso_enforcement && (- <SSOEnforcedLoginButton- provider="saml"- email={login.email}- isLastUsed={lastLoginMethod === 'saml'}- />- )}- {precheckResponse.oidc_available && !precheckResponse.sso_enforcement && (- <SSOEnforcedLoginButton- provider="oidc"- email={login.email}- isLastUsed={lastLoginMethod === 'oidc'}- />- )}- </Form>- {isAccountUnknown && canSignUpWithEmail && (- <p className="mt-4 mb-0 text-sm text-secondary text-center">- <span>New to PostHog?</span>{' '}- <Link- onClick={() => chooseAccountPath('signup', null)}- data-attr="auth-unknown-account-signup"- className="font-semibold no-underline cursor-pointer hover:underline hover:underline-offset-2 text-warning"- >- Create an account- </Link>- </p>- )}- {isNewAccount && canSignUpWithEmail && (- <p className="mt-4 mb-0 text-sm text-secondary text-center">- <Link- onClick={() => chooseAccountPath('signup', false)}- data-attr="auth-sso-domain-signup-with-email"- className="font-semibold no-underline cursor-pointer hover:underline hover:underline-offset-2 text-warning"- >- Sign up with email instead- </Link>- </p>- )}- {/* Normally SAML replaces this row, but when the account has no password we need to- show whatever it does have. */}- {!isNewAccount &&- !precheckResponse.sso_enforcement &&- (!precheckResponse.saml_available || isPasswordLoginUnavailable) && (- <SocialLoginButtons- topDivider- caption={isPasswordLoginUnavailable ? 'Log in with' : 'Or log in with'}- captionLocation="top"- lastUsedProvider={lastLoginMethod}- restrictToProviders={restrictToProviders}- // Once we know the account's methods, only offer a passkey if it actually has- // one — otherwise this is the same dead button we're removing.- showPasskey={!isPasswordLoginUnavailable || !!precheckResponse.webauthn_credentials?.length}- />- )}- </AuthSceneCard>- )-}diff --git a/frontend/src/scenes/authentication/auth/steps/SignupCredentialsStep.tsx b/frontend/src/scenes/authentication/auth/steps/SignupCredentialsStep.tsxdeleted file mode 100644index f7810143c547..000000000000--- a/frontend/src/scenes/authentication/auth/steps/SignupCredentialsStep.tsx+++ /dev/null@@ -1,149 +0,0 @@-import { useActions, useValues } from 'kea'-import { Form } from 'kea-forms'--import PasswordStrength from 'lib/components/PasswordStrength'-import passkeyLogo from 'lib/components/SocialLoginButton/passkey.svg'-import { SocialLoginButtons } from 'lib/components/SocialLoginButton/SocialLoginButton'-import { LemonButton } from 'lib/lemon-ui/LemonButton'-import { LemonField } from 'lib/lemon-ui/LemonField'-import { LemonInput } from 'lib/lemon-ui/LemonInput/LemonInput'-import { Link } from 'lib/lemon-ui/Link'-import { AuthBanner } from 'scenes/authentication/shared/authScene/AuthBanner'-import { AuthCardTitle } from 'scenes/authentication/shared/authScene/AuthCardTitle'-import { AuthSceneCard } from 'scenes/authentication/shared/authScene/AuthScene'-import { pendingOAuthConnectionLogic } from 'scenes/authentication/shared/pendingOAuthConnectionLogic'--import { ConnectTitle } from '../components/ConnectTitle'-import { OtherRegionNotice } from '../components/OtherRegionNotice'-import { UseDifferentEmailLink } from '../components/UseDifferentEmailLink'-import { signupLogic } from '../signupLogic'--export function SignupCredentialsStep(): JSX.Element {- const {- signupEmail,- isSignupPanelAuthSubmitting,- validatedPassword,- passkeyRegistered,- isPasskeyRegistering,- passkeyError,- } = useValues(signupLogic)- const { registerPasskey } = useActions(signupLogic)- const { pendingConnection } = useValues(pendingOAuthConnectionLogic)-- const footer = (- <>- <p className="AuthScene__terms mt-5 mb-0 text-xs leading-relaxed text-tertiary text-center">- <span>By creating an account, you agree to our</span>{' '}- <Link to="https://posthog.com/terms" target="_blank">- Terms of Service ↗- </Link>{' '}- <span>and</span>{' '}- <Link to="https://posthog.com/privacy" target="_blank">- Privacy Policy ↗- </Link>- <span>.</span>- </p>- <UseDifferentEmailLink />- </>- )-- const greeting = (- <>- <span>Nice to meet you,</span> <span className="AuthScene__mono">{signupEmail}</span>- <span>.</span>- </>- )-- return (- <AuthSceneCard footer={footer} showPendingConnection>- <AuthCardTitle- title={- pendingConnection ? (- <ConnectTitle lead="Create your account to connect" clientName={pendingConnection.clientName} />- ) : (- 'Create your account'- )- }- sub={greeting}- />- {passkeyError && (- <AuthBanner variant="danger" className="mb-4">- {passkeyError}- </AuthBanner>- )}- {passkeyRegistered ? (- <AuthBanner variant="success">Passkey registered. Continue below.</AuthBanner>- ) : (- <LemonButton- type="secondary"- size="large"- fullWidth- icon={<img src={passkeyLogo} alt="Passkey" className="object-contain w-7 h-7" />}- onClick={registerPasskey}- loading={isPasskeyRegistering}- disabled={isPasskeyRegistering}- data-attr="signup-passkey"- center- >- Sign up with a passkey- </LemonButton>- )}- {!passkeyRegistered && (- <div className="my-4 flex gap-3 items-center">- <span className="flex-1 h-px bg-[#e0e1d9]" />- <span className="text-xs text-secondary whitespace-nowrap">or use a password</span>- <span className="flex-1 h-px bg-[#e0e1d9]" />- </div>- )}- <Form logic={signupLogic} formKey="signupPanelAuth" enableFormOnSubmit className="flex flex-col gap-4">- {/* Password managers save the new password under this username */}- <input type="email" name="email" autoComplete="username" value={signupEmail} readOnly hidden />- {!passkeyRegistered && (- <LemonField- name="password"- label={- <div className="flex items-baseline justify-between w-full">- <span>Password</span>- <PasswordStrength validatedPassword={validatedPassword} />- </div>- }- >- {({ value, onChange, error, id }) => (- <LemonInput- id={id}- className="ph-ignore-input"- data-attr="password"- type="password"- autoFocus- autoComplete="new-password"- placeholder="••••••••••"- value={value ?? ''}- onChange={onChange}- status={error ? 'danger' : 'default'}- fullWidth- />- )}- </LemonField>- )}- <LemonButton- type="primary"- size="large"- center- fullWidth- htmlType="submit"- data-attr="signup-auth-continue"- loading={isSignupPanelAuthSubmitting}- disabledReason={- !passkeyRegistered && validatedPassword.feedback ? validatedPassword.feedback : undefined- }- >- Create account- </LemonButton>- <OtherRegionNotice email={signupEmail} reason="no_account" />- </Form>- {/* A verified company domain with auto-join adds people who sign in with Google, GitHub or- GitLab to their team's organization. An email signup creates a new organization instead. */}- <SocialLoginButtons topDivider caption="or sign up with" captionLocation="top" />- </AuthSceneCard>- )-}diff --git a/frontend/src/scenes/authentication/shared/authScene/DevLoginPanel.stories.tsx b/frontend/src/scenes/authentication/shared/authScene/DevLoginPanel.stories.tsxindex 44f6fcf552e5..eac8f98ebadf 100644--- a/frontend/src/scenes/authentication/shared/authScene/DevLoginPanel.stories.tsx+++ b/frontend/src/scenes/authentication/shared/authScene/DevLoginPanel.stories.tsx@@ -3,7 +3,7 @@ import type { Meta, StoryFn } from '@storybook/react'import { useStorybookMocks } from '~/mocks/browser'import preflightJson from '~/mocks/fixtures/_preflight.json'-import type { DevUser } from '../devLoginLogic'+import type { DevOAuthConnector, DevUser } from '../devLoginLogic'import { DevLoginPanel } from './DevLoginPanel'type StoryArgs = {@@ -11,6 +11,24 @@ type StoryArgs = {devUsers: 'none' | 'default' | 'many'}+const DEV_OAUTH_CONNECTORS: DevOAuthConnector[] = [+ {+ client_id: 'https://chatgpt.com/oauth/client.json',+ client_name: 'ChatGPT',+ // No external logo, so the story renders the same picture offline+ logo_uri: null,+ redirect_host: 'chatgpt.com',+ authorize_path: '/oauth/authorize/?client_id=https%3A%2F%2Fchatgpt.com%2Foauth%2Fclient.json',+ },+ {+ client_id: 'https://claude.ai/oauth/mcp-oauth-client-metadata',+ client_name: 'Claude',+ logo_uri: null,+ redirect_host: 'claude.ai',+ authorize_path: '/oauth/authorize/?client_id=https%3A%2F%2Fclaude.ai%2Foauth%2Fmcp-oauth-client-metadata',+ },+]+const DEV_USERS_MOCKS: Record<StoryArgs['devUsers'], DevUser[]> = {none: [],default: [@@ -82,7 +100,10 @@ const Template: StoryFn<StoryArgs> = ({ allowDevLogin, devUsers }) => {is_debug: true,allow_dev_login: allowDevLogin,},- '/api/login/dev': { users: DEV_USERS_MOCKS[devUsers] },+ '/api/login/dev': {+ users: DEV_USERS_MOCKS[devUsers],+ oauth_connectors: devUsers === 'none' ? [] : DEV_OAUTH_CONNECTORS,+ },},})diff --git a/frontend/src/scenes/authentication/shared/authScene/DevLoginPanel.tsx b/frontend/src/scenes/authentication/shared/authScene/DevLoginPanel.tsxindex 8c95389282d3..dceaffc6765f 100644--- a/frontend/src/scenes/authentication/shared/authScene/DevLoginPanel.tsx+++ b/frontend/src/scenes/authentication/shared/authScene/DevLoginPanel.tsx@@ -15,12 +15,13 @@ import { preflightLogic } from 'scenes/PreflightCheck/preflightLogic'import { Region } from '~/types'import { DevUser, devLoginLogic } from '../devLoginLogic'+import { DevOAuthConnectionSection } from './DevOAuthConnectionSection'/** Floating dev-only panel (top-right) combining dev-login shortcuts and OAuth prod-data login. */export function DevLoginPanel(): JSX.Element | null {const { preflight } = useValues(preflightLogic)- const { devUsers, devUsersLoading, devLoginPanelOpen, createFreshAccountLoading } = useValues(devLoginLogic)- const { devLogin, loadDevUsers, createFreshAccount, setDevLoginPanelOpen } = useActions(devLoginLogic)+ const { devUsers, devLoginOptionsLoading, devLoginPanelOpen, createFreshAccountLoading } = useValues(devLoginLogic)+ const { devLogin, loadDevLoginOptions, createFreshAccount, setDevLoginPanelOpen } = useActions(devLoginLogic)const { loginInProgress } = useValues(oauthLogic)const { beginLogin } = useActions(oauthLogic)@@ -29,9 +30,9 @@ export function DevLoginPanel(): JSX.Element | null {useEffect(() => {if (allowDevLogin && devLoginPanelOpen) {- loadDevUsers(null)+ loadDevLoginOptions(null)}- }, [allowDevLogin, devLoginPanelOpen, loadDevUsers])+ }, [allowDevLogin, devLoginPanelOpen, loadDevLoginOptions])if (!isDebug) {return null@@ -64,12 +65,12 @@ export function DevLoginPanel(): JSX.Element | null {{devUsers.map((user) => (<DevUserButton key={user.email} user={user} onClick={devLogin} />))}- {devUsersLoading && (+ {devLoginOptionsLoading && (<div className="flex justify-center py-4"><Spinner /></div>)}- {!devUsersLoading && devUsers.length === 0 && (+ {!devLoginOptionsLoading && devUsers.length === 0 && (<p className="text-xs text-muted text-center px-2 py-4 m-0">No accounts yet. Create a fresh demo account below.</p>@@ -93,6 +94,7 @@ export function DevLoginPanel(): JSX.Element | null {Create fresh demo account</LemonButton>)}+ {allowDevLogin && <DevOAuthConnectionSection />}<div><p className="text-xs font-medium text-muted mb-1">Log in via OAuth</p><div className="grid grid-cols-2 gap-1">diff --git a/frontend/src/scenes/authentication/shared/authScene/DevOAuthConnectionSection.tsx b/frontend/src/scenes/authentication/shared/authScene/DevOAuthConnectionSection.tsxnew file mode 100644index 000000000000..7848b1e56b65--- /dev/null+++ b/frontend/src/scenes/authentication/shared/authScene/DevOAuthConnectionSection.tsx@@ -0,0 +1,66 @@+import { useActions, useValues } from 'kea'++import { IconX } from '@posthog/icons'++import { LemonButton } from 'lib/lemon-ui/LemonButton'+import { pendingOAuthConnectionLogic } from 'scenes/authentication/shared/pendingOAuthConnectionLogic'++import { devLoginLogic } from '../devLoginLogic'++export function DevOAuthConnectionSection(): JSX.Element {+ const { devOAuthConnectors, devLoginOptionsLoading } = useValues(devLoginLogic)+ const { clearPendingOAuthConnection, startPendingOAuthConnection } = useActions(devLoginLogic)+ const { pendingConnection } = useValues(pendingOAuthConnectionLogic)++ if (pendingConnection) {+ return (+ <div>+ <p className="text-xs font-medium text-muted mb-1">Pending OAuth connection</p>+ <LemonButton+ type="secondary"+ size="small"+ fullWidth+ center+ icon={<IconX />}+ onClick={clearPendingOAuthConnection}+ data-attr="dev-clear-pending-oauth-connection"+ tooltip="Deletes the ph_pending_oauth_connection cookie, so these screens stop showing the app. The next= link in the URL still goes to the consent page after login."+ >+ Clear {pendingConnection.clientName}+ </LemonButton>+ </div>+ )+ }+ return (+ <div>+ <p className="text-xs font-medium text-muted mb-1">Start an OAuth connection</p>+ {devOAuthConnectors.length > 0 ? (+ <div className="grid grid-cols-2 gap-1">+ {devOAuthConnectors.map((connector) => (+ <LemonButton+ key={connector.client_id}+ type="secondary"+ size="small"+ fullWidth+ center+ icon={+ connector.logo_uri ? (+ <img src={connector.logo_uri} alt="" className="w-4 h-4 object-contain" />+ ) : undefined+ }+ onClick={() => startPendingOAuthConnection(connector)}+ data-attr={`dev-start-oauth-connection-${connector.client_id}`}+ tooltip="Sets the ph_pending_oauth_connection cookie and a next= link to the consent page, as a connector would."+ >+ <span className="truncate">{connector.client_name}</span>+ </LemonButton>+ ))}+ </div>+ ) : (+ !devLoginOptionsLoading && (+ <p className="text-xs text-muted m-0">Run generate_demo_data to add connector apps.</p>+ )+ )}+ </div>+ )+}diff --git a/frontend/src/scenes/authentication/shared/devLoginLogic.ts b/frontend/src/scenes/authentication/shared/devLoginLogic.tsindex 93186eb1b3a6..7f5f5f20b750 100644--- a/frontend/src/scenes/authentication/shared/devLoginLogic.ts+++ b/frontend/src/scenes/authentication/shared/devLoginLogic.ts@@ -1,8 +1,10 @@import { MakeLogicType, actions, kea, listeners, path, reducers, selectors } from 'kea'import { loaders } from 'kea-loaders'+import { router } from 'kea-router'import api from 'lib/api'import { lemonToast } from 'lib/lemon-ui/LemonToast'+import { urls } from 'scenes/urls'export interface DevUser {email: string@@ -12,20 +14,38 @@ export interface DevUser {last_login: string | null}+export interface DevOAuthConnector {+ client_id: string+ client_name: string+ logo_uri: string | null+ redirect_host: string | null+ authorize_path: string+}++export interface DevLoginOptions {+ users: DevUser[]+ oauth_connectors?: DevOAuthConnector[]+}+export const DEV_LOGIN_SECONDS_SAVED_PER_CLICK = 5// Generated by kea-typegen. Update if you're an agent, ignore if you're human.export interface devLoginLogicValues {createFreshAccountLoading: booleandevLoginCount: number+ devLoginOptions: DevLoginOptions+ devLoginOptionsLoading: booleandevLoginPanelOpen: booleandevLoginTimeSavedLabel: string | null+ devOAuthConnectors: DevOAuthConnector[]devUsers: DevUser[]- devUsersLoading: boolean}// Generated by kea-typegen. Update if you're an agent, ignore if you're human.export interface devLoginLogicActions {+ clearPendingOAuthConnection: () => {+ value: true+ }createFreshAccount: () => {value: true}@@ -38,29 +58,34 @@ export interface devLoginLogicActions {devLogin: (email: string) => {email: string}- loadDevUsers: (_: any) => any- loadDevUsersFailure: (+ loadDevLoginOptions: (_: any) => any+ loadDevLoginOptionsFailure: (error: string,errorObject?: any) => {error: stringerrorObject?: any}- loadDevUsersSuccess: (- devUsers: DevUser[],+ loadDevLoginOptionsSuccess: (+ devLoginOptions: DevLoginOptions,payload?: any) => {- devUsers: DevUser[]+ devLoginOptions: DevLoginOptionspayload?: any}setDevLoginPanelOpen: (open: boolean) => {open: boolean}+ startPendingOAuthConnection: (connector: DevOAuthConnector) => {+ connector: DevOAuthConnector+ }}// Generated by kea-typegen. Update if you're an agent, ignore if you're human.export interface devLoginLogicMeta {__keaTypeGenInternalSelectorTypes: {+ devUsers: (devLoginOptions: DevLoginOptions) => DevUser[]+ devOAuthConnectors: (devLoginOptions: DevLoginOptions) => DevOAuthConnector[]devLoginTimeSavedLabel: (devLoginCount: number) => string | null}}@@ -80,6 +105,8 @@ export const devLoginLogic = kea<devLoginLogicType>([createFreshAccountSuccess: true,createFreshAccountFailure: (error: string) => ({ error }),setDevLoginPanelOpen: (open: boolean) => ({ open }),+ clearPendingOAuthConnection: true,+ startPendingOAuthConnection: (connector: DevOAuthConnector) => ({ connector }),}),reducers({devLoginCount: [@@ -108,27 +135,32 @@ export const devLoginLogic = kea<devLoginLogicType>([],}),loaders(() => ({- devUsers: [- [] as DevUser[],+ devLoginOptions: [+ { users: [] } as DevLoginOptions,{// Not fired on an `onMount` because we don't always need it. The whole list comes// down in one go — this only ever runs against a local instance.- loadDevUsers: async (_, breakpoint) => {+ loadDevLoginOptions: async (_, breakpoint) => {breakpoint()try {// nosemgrep: prefer-codegen-api -- Legacy raw API call with a hand-written URL and an unchecked response type. No generated function covers this endpoint yet. Find out why the generated client skips it (no schema, no product tag, or excluded from the spec) and fix that first.- const response = await api.get<{ users: DevUser[] }>('api/login/dev')+ const response = await api.get<DevLoginOptions>('api/login/dev')breakpoint()- return response.users+ return response} catch {// Endpoint is unavailable unless allow_dev_login is set in preflight.- return []+ return { users: [] }}},},],})),selectors(() => ({+ devUsers: [(s) => [s.devLoginOptions], (devLoginOptions: DevLoginOptions): DevUser[] => devLoginOptions.users],+ devOAuthConnectors: [+ (s) => [s.devLoginOptions],+ (devLoginOptions: DevLoginOptions): DevOAuthConnector[] => devLoginOptions.oauth_connectors ?? [],+ ],devLoginTimeSavedLabel: [(s) => [s.devLoginCount],(devLoginCount: number): string | null => {@@ -149,6 +181,37 @@ export const devLoginLogic = kea<devLoginLogicType>([],})),listeners(({ actions }) => ({+ clearPendingOAuthConnection: async () => {+ // Dynamic import: loginLogic, which the boot path loads, imports this logic, and the+ // pending connection logic pulls in an HTML entity decoder that /login does not need+ const { PENDING_OAUTH_CONNECTION_COOKIE, pendingOAuthConnectionLogic } =+ await import('./pendingOAuthConnectionLogic')+ // Locally the backend sets the cookie on the request host with no `Domain`, so a+ // host-only deletion on `/` matches it+ document.cookie = `${PENDING_OAUTH_CONNECTION_COOKIE}=; Max-Age=0; path=/`+ pendingOAuthConnectionLogic.findMounted()?.actions.clearPendingConnection()+ },+ startPendingOAuthConnection: async ({ connector }) => {+ const { PENDING_OAUTH_CONNECTION_COOKIE, pendingOAuthConnectionLogic } =+ await import('./pendingOAuthConnectionLogic')+ const payload = {+ client_name: connector.client_name,+ client_id: connector.client_id,+ logo_uri: connector.logo_uri ?? undefined,+ redirect_host: connector.redirect_host ?? undefined,+ }+ // Matches the backend's encoding and one-hour lifetime (posthog/helpers/oauth_pending_connection.py)+ document.cookie = `${PENDING_OAUTH_CONNECTION_COOKIE}=${encodeURIComponent(JSON.stringify(payload))}; Max-Age=3600; path=/; SameSite=Lax`+ pendingOAuthConnectionLogic.findMounted()?.actions.setPendingConnection({+ clientName: connector.client_name,+ clientId: connector.client_id,+ logoUri: connector.logo_uri,+ redirectHost: connector.redirect_host,+ })+ const { pathname } = router.values.location+ const authPath = pathname === urls.signup() ? urls.signup() : urls.login()+ router.actions.push(authPath, { next: connector.authorize_path })+ },devLogin: async ({ email }) => {// Dynamic import to avoid a circular dependency: loginLogic statically imports this logic.const { loginLogic, redirectAfterLogin } = await import('scenes/authentication/auth/loginLogic')diff --git a/frontend/src/scenes/authentication/shared/pendingOAuthConnectionLogic.ts b/frontend/src/scenes/authentication/shared/pendingOAuthConnectionLogic.tsindex c87406ee4e66..ca5a833191e3 100644--- a/frontend/src/scenes/authentication/shared/pendingOAuthConnectionLogic.ts+++ b/frontend/src/scenes/authentication/shared/pendingOAuthConnectionLogic.ts@@ -54,6 +54,9 @@ export interface pendingOAuthConnectionLogicValues {// Generated by kea-typegen. Update if you're an agent, ignore if you're human.export interface pendingOAuthConnectionLogicActions {+ clearPendingConnection: () => {+ value: true+ }setPendingConnection: (pendingConnection: PendingOAuthConnection) => {pendingConnection: PendingOAuthConnection}@@ -70,12 +73,14 @@ export const pendingOAuthConnectionLogic: LogicWrapper<pendingOAuthConnectionLogpath(['scenes', 'authentication', 'shared', 'pendingOAuthConnectionLogic']),actions({setPendingConnection: (pendingConnection: PendingOAuthConnection) => ({ pendingConnection }),+ clearPendingConnection: true,}),reducers({pendingConnection: [null as PendingOAuthConnection | null,{setPendingConnection: (_, { pendingConnection }) => pendingConnection,+ clearPendingConnection: () => null,},],}),diff --git a/frontend/src/scenes/settings/user/ConnectedAppLogo.tsx b/frontend/src/scenes/settings/user/ConnectedAppLogo.tsxnew file mode 100644index 000000000000..f4ca48b2a1f9--- /dev/null+++ b/frontend/src/scenes/settings/user/ConnectedAppLogo.tsx@@ -0,0 +1,24 @@+import { useState } from 'react'++export function ConnectedAppLogo({ name, logoUri }: { name: string; logoUri: string | null }): JSX.Element {+ // A CIMD app without a logo of its own gets its host's touch icon, which may not exist+ const [logoFailed, setLogoFailed] = useState(false)++ if (logoUri && !logoFailed) {+ return (+ <div className="w-8 h-8 shrink-0 rounded bg-bg-light border flex items-center justify-center p-1">+ <img+ src={logoUri}+ alt={`${name} logo`}+ className="w-full h-full object-contain"+ onError={() => setLogoFailed(true)}+ />+ </div>+ )+ }+ return (+ <div className="w-8 h-8 shrink-0 rounded bg-border flex items-center justify-center text-sm font-bold text-muted">+ {name.charAt(0).toUpperCase()}+ </div>+ )+}diff --git a/frontend/src/scenes/settings/user/ConnectedApps.tsx b/frontend/src/scenes/settings/user/ConnectedApps.tsxindex 97abda06fbb2..d227ee4e8d71 100644--- a/frontend/src/scenes/settings/user/ConnectedApps.tsx+++ b/frontend/src/scenes/settings/user/ConnectedApps.tsx@@ -11,6 +11,7 @@ import { humanFriendlyDetailedTime } from 'lib/utils/datetime'import type { ConnectedAppApi } from '~/generated/core/api.schemas'+import { ConnectedAppLogo } from './ConnectedAppLogo'import { connectedAppsLogic } from './connectedAppsLogic'const HedgehogMagnifyingGlass = pngHoggie(magnifyingGlassPng)@@ -84,19 +85,7 @@ export function ConnectedApps({ apps }: { apps?: ConnectedAppApi[] }): JSX.ElemedataIndex: 'name',render: (_, app) => (<div className="flex items-center gap-2">- {app.logo_uri ? (- <div className="w-8 h-8 shrink-0 rounded bg-bg-light border flex items-center justify-center p-1">- <img- src={app.logo_uri}- alt={`${decode(app.name)} logo`}- className="w-full h-full object-contain"- />- </div>- ) : (- <div className="w-8 h-8 shrink-0 rounded bg-border flex items-center justify-center text-sm font-bold text-muted">- {decode(app.name).charAt(0).toUpperCase()}- </div>- )}+ <ConnectedAppLogo name={decode(app.name)} logoUri={app.logo_uri ?? null} /><span className="font-medium">{decode(app.name)}</span>{app.is_first_party ? (<LemonTag type="highlight" size="small">diff --git a/playwright/e2e/signup.spec.ts b/playwright/e2e/signup.spec.tsindex 37bf42ce67ff..d36ea47a7cbb 100644--- a/playwright/e2e/signup.spec.ts+++ b/playwright/e2e/signup.spec.ts@@ -121,9 +121,8 @@ test.describe('Signup', () => {// The same email now has an account, so it goes to the login step instead of signupawait submitEmailAndExpectLoginStep(page, email)- await page.locator('[data-attr=auth-use-different-email]').click()- // Update email to generic email and retry+ // Typing a new email closes the login step's password field and retries the signupconst newEmail = `${randomString('new_user')}@posthog.com`await startSignupFlow(page, newEmail, VALID_PASSWORD)await page.locator('[data-attr=signup-name]').fill('Alice Bob')diff --git a/posthog/api/authentication.py b/posthog/api/authentication.pyindex d1d51158e426..8d8d9654ed60 100644--- a/posthog/api/authentication.py+++ b/posthog/api/authentication.py@@ -62,6 +62,7 @@ from posthog.event_usage import report_user_logged_in, report_user_password_resefrom posthog.exceptions_capture import capture_exceptionfrom posthog.geoip import get_geoip_propertiesfrom posthog.helpers.dev_login import is_dev_login_allowed+from posthog.helpers.dev_oauth_connectors import seeded_dev_oauth_connector_linksfrom posthog.helpers.email_utils import EmailLookupHandlerfrom posthog.helpers.sso import (GITHUB_EMAIL_LOOKUP_ERROR,@@ -729,10 +730,32 @@ class DevLoginUserSerializer(serializers.Serializer):)+class DevOAuthConnectorSerializer(serializers.Serializer):+ client_id = serializers.CharField(+ read_only=True, help_text="Client ID of the connector application, which is its CIMD document URL."+ )+ client_name = serializers.CharField(read_only=True, help_text="Application name, shown on the auth screens.")+ logo_uri = serializers.CharField(+ read_only=True, allow_null=True, help_text="HTTPS logo from the connector's CIMD document, or null."+ )+ redirect_host = serializers.CharField(+ read_only=True, allow_null=True, help_text="Host of the application's redirect URI."+ )+ authorize_path = serializers.CharField(+ read_only=True,+ help_text="The /oauth/authorize path the connector sends people to, for the login page's next parameter.",+ )++class DevLoginUserListSerializer(serializers.Serializer):users = DevLoginUserSerializer(many=True, read_only=True, help_text="Every active user, seeded accounts first, then most recently used.")+ oauth_connectors = DevOAuthConnectorSerializer(+ many=True,+ read_only=True,+ help_text="Connector applications registered by generate_demo_data, to start a pending OAuth connection.",+ )class DevLoginViewSet(NonCreatingViewSetMixin, viewsets.GenericViewSet):@@ -763,7 +786,9 @@ class DevLoginViewSet(NonCreatingViewSetMixin, viewsets.GenericViewSet):for entry in users:entry["label"] = DEV_LOGIN_KNOWN_EMAIL_LABELS.get(entry["email"])- return Response({"users": users})+ return Response(+ DevLoginUserListSerializer({"users": users, "oauth_connectors": seeded_dev_oauth_connector_links()}).data+ )class TwoFactorSerializer(serializers.Serializer):diff --git a/posthog/api/oauth/cimd.py b/posthog/api/oauth/cimd.pyindex 26957775bcc4..32b61c151419 100644--- a/posthog/api/oauth/cimd.py+++ b/posthog/api/oauth/cimd.py@@ -601,6 +601,18 @@ def _resolve_client_authentication(return AbstractApplication.CLIENT_PUBLIC, metadata.get("jwks_uri")+def _logo_uri_for(metadata: CIMDMetadataDocument, url: str) -> str | None:+ """The document's logo, or else the touch icon at the root of the host that serves the document.++ Many clients publish no `logo_uri`. The fallback comes from the client_id host, which the+ document was fetched from, and not from the self-asserted `client_uri`, so a client cannot+ borrow another site's icon. Where the host has no icon, the screens show the client's initial.+ """+ if logo_uri := metadata.get("logo_uri"):+ return logo_uri+ return usable_logo_uri(f"https://{urlparse(url).netloc}/apple-touch-icon.png")++def _create_cimd_application(url: str,metadata: CIMDMetadataDocument,@@ -623,7 +635,7 @@ def _create_cimd_application(client_name = sanitize_client_name(client_name)redirect_uris = " ".join(metadata.get("redirect_uris", []))- logo_uri = metadata.get("logo_uri") or None+ logo_uri = _logo_uri_for(metadata, url)verification = _resolve_verification_token(metadata, url, capture_ph_event=capture_ph_event)resolved_scopes = _resolve_scopes(metadata)resolved_optional_scopes = _resolve_optional_scopes(metadata)@@ -713,7 +725,9 @@ def _update_cimd_application(pass # Keep existing name if new one is invalidapp.redirect_uris = " ".join(metadata.get("redirect_uris", []))- app.logo_uri = new_uri if (new_uri := metadata.get("logo_uri")) is not None else app.logo_uri+ # A document without a logo keeps the stored one, and only an app with none gets the host icon+ if metadata.get("logo_uri") is not None or not app.logo_uri:+ app.logo_uri = _logo_uri_for(metadata, app.client_id)app.cimd_metadata_last_fetched = timezone.now()# Re-derived on every refresh, in both directions: a registered partner that startsdiff --git a/posthog/api/oauth/test_cimd.py b/posthog/api/oauth/test_cimd.pyindex b8cd16e0aa4e..0eeac38256d3 100644--- a/posthog/api/oauth/test_cimd.py+++ b/posthog/api/oauth/test_cimd.py@@ -395,6 +395,25 @@ class TestFetchAndUpsertCimdApplication(APIBaseTest):else:self.assertEqual(refreshed.client_type, OAuthApplication.CLIENT_PUBLIC)+ @parameterized.expand(+ [+ ("document_logo", {"logo_uri": "https://cdn.example.com/logo.png"}, "https://cdn.example.com/logo.png"),+ (+ "host_icon_without_logo",+ {"client_uri": "https://someone-else.example.org"},+ "https://app.example.com/apple-touch-icon.png",+ ),+ ]+ )+ @patch("posthog.api.oauth.cimd.requests.Session.get")+ def test_stores_logo_or_document_host_icon(self, _name, overrides, expected_logo_uri, mock_get, _url_mock):+ mock_get.return_value = _mock_response(_make_metadata(**overrides), headers={})++ app = fetch_and_upsert_cimd_application(VALID_CIMD_URL)++ assert app is not None+ self.assertEqual(app.logo_uri, expected_logo_uri)+@patch("posthog.api.oauth.cimd.requests.Session.get")def test_updates_existing_application(self, mock_get, _url_mock):metadata1 = _make_metadata(client_name="Original Name")diff --git a/posthog/api/test/test_authentication.py b/posthog/api/test/test_authentication.pyindex 68c0ac4ebc62..3a248bd26b8f 100644--- a/posthog/api/test/test_authentication.py+++ b/posthog/api/test/test_authentication.py@@ -22,6 +22,7 @@ from django.test.utils import CaptureQueriesContextfrom django.utils import timezonefrom django.utils.module_loading import import_string+import requestsfrom asgiref.sync import sync_to_asyncfrom django_otp.oath import totpfrom django_otp.plugins.otp_static.models import StaticDevice@@ -38,6 +39,7 @@ from two_factor.utils import totp_digitsfrom posthog.api.authentication import password_reset_token_generator, social_login_notificationfrom posthog.api.email_verification import is_email_verification_disabled+from posthog.api.oauth.cimd import CIMDFetchErrorfrom posthog.auth import (ExportRendererAuthentication,InternalAPIUser,@@ -54,6 +56,7 @@ from posthog.auth import (mint_export_renderer_token,)from posthog.clickhouse.query_tagging import AccessMethod, get_query_tags, tags_context+from posthog.helpers.dev_oauth_connectors import DEV_OAUTH_CONNECTOR_CIMD_URLS, seed_dev_oauth_connectorsfrom posthog.helpers.user_devices import (KNOWN_DEVICE_COOKIE,build_known_device_cookie_value,@@ -782,11 +785,32 @@ class TestDevLoginAPI(APIBaseTest):@override_settings(DEBUG=True, ALLOW_DEV_LOGIN=True)def test_dev_login_list_and_create_when_allowed(self):+ for url in DEV_OAUTH_CONNECTOR_CIMD_URLS:+ OAuthApplication.objects.create(+ name=f"Connector {url}",+ client_id=url,+ client_type="public",+ authorization_grant_type="authorization-code",+ redirect_uris="https://connector.example.com/callback",+ algorithm="RS256",+ is_cimd_client=True,+ )+response = self.client.get("/api/login/dev")self.assertEqual(response.status_code, status.HTTP_200_OK)+emails = {user["email"] for user in response.json()["users"]}self.assertIn(self.user.email, emails)+ authorize_paths = {+ connector["client_id"]: connector["authorize_path"] for connector in response.json()["oauth_connectors"]+ }+ self.assertEqual(set(authorize_paths), set(DEV_OAUTH_CONNECTOR_CIMD_URLS))+ self.assertIn(+ "redirect_uri=https%3A%2F%2Fconnector.example.com%2Fcallback",+ authorize_paths[DEV_OAUTH_CONNECTOR_CIMD_URLS[0]],+ )+self.client.logout()response = self.client.post("/api/login/dev", {"email": self.user.email})self.assertEqual(response.status_code, status.HTTP_200_OK)@@ -806,6 +830,19 @@ class TestDevLoginAPI(APIBaseTest):emails = [user["email"] for user in response.json()["users"]]self.assertEqual(emails[:2], ["[email protected]", "[email protected]"])+ @parameterized.expand(+ [+ ("rejected_document", CIMDFetchError("Metadata document endpoint returned HTTP 503")),+ ("dropped_connection", requests.exceptions.ChunkedEncodingError("Connection broken")),+ ]+ )+ def test_dev_connector_seed_records_unreachable_documents(self, _name, error):+ with patch("posthog.helpers.dev_oauth_connectors.get_or_create_cimd_application", side_effect=error):+ result = seed_dev_oauth_connectors()++ self.assertEqual(result.created, [])+ self.assertEqual(result.failed, list(DEV_OAUTH_CONNECTOR_CIMD_URLS))+@override_settings(DEBUG=True, ALLOW_DEV_LOGIN=False)def test_dev_login_hidden_when_allow_dev_login_disabled(self):response = self.client.get("/api/login/dev")diff --git a/posthog/helpers/dev_oauth_connectors.py b/posthog/helpers/dev_oauth_connectors.pynew file mode 100644index 000000000000..bdb49fedffa5--- /dev/null+++ b/posthog/helpers/dev_oauth_connectors.py@@ -0,0 +1,100 @@+"""The AI connectors that send people through `/oauth/authorize`, registered on a local instance.++`generate_demo_data` registers them from their public Client ID Metadata Documents (CIMD), the+same way production registers them on their first authorization, so their name and logo match+what people see in production. The dev login tools then start a pending connection with one, so+the connector version of the login and signup screens can be tried locally.+"""++import base64+import hashlib+from urllib.parse import urlencode, urlparse++import requests+from oauth2_provider.settings import oauth2_settings++from posthog.api.oauth.cimd import CIMDFetchError, CIMDValidationError, get_or_create_cimd_application+from posthog.api.oauth.logo_uri import usable_logo_uri+from posthog.dataclasses import frozen+from posthog.models.oauth import OAuthApplication++# The documents these connectors publish (claude.com/docs/connectors/building/authentication and+# developers.openai.com/apps-sdk/build/auth). Each one is the connector's client_id.+DEV_OAUTH_CONNECTOR_CIMD_URLS: tuple[str, ...] = (+ "https://claude.ai/oauth/mcp-oauth-client-metadata",+ "https://chatgpt.com/oauth/client.json",+)++# The dev tools stop at the consent screen and never exchange the code, so one fixed verifier is enough+_DEV_CODE_VERIFIER = "posthog-local-dev-connector-code-verifier"+++def _code_challenge(verifier: str) -> str:+ digest = hashlib.sha256(verifier.encode()).digest()+ return base64.urlsafe_b64encode(digest).rstrip(b"=").decode()+++@frozen+class DevOAuthConnectorSeedResult:+ created: list[str]+ failed: list[str]+++def seed_dev_oauth_connectors() -> DevOAuthConnectorSeedResult:+ # OAuthApplication.clean() rejects RS256 where no OIDC RSA private key is configured+ if not oauth2_settings.OIDC_RSA_PRIVATE_KEY:+ return DevOAuthConnectorSeedResult(created=[], failed=list(DEV_OAUTH_CONNECTOR_CIMD_URLS))+ existing = set(+ OAuthApplication.objects.filter(client_id__in=DEV_OAUTH_CONNECTOR_CIMD_URLS).values_list("client_id", flat=True)+ )+ created: list[str] = []+ failed: list[str] = []+ for url in DEV_OAUTH_CONNECTOR_CIMD_URLS:+ if url in existing:+ continue+ try:+ application = get_or_create_cimd_application(url)+ # The fetcher wraps connection errors, but one raised while it streams the body comes through as is+ except (CIMDFetchError, CIMDValidationError, requests.RequestException):+ failed.append(url)+ continue+ created.append(application.name)+ return DevOAuthConnectorSeedResult(created=created, failed=failed)+++@frozen+class DevOAuthConnectorLink:+ client_id: str+ client_name: str+ logo_uri: str | None+ redirect_host: str | None+ authorize_path: str+++def seeded_dev_oauth_connector_links() -> list[DevOAuthConnectorLink]:+ applications = OAuthApplication.objects.filter(client_id__in=DEV_OAUTH_CONNECTOR_CIMD_URLS).order_by("name")+ links: list[DevOAuthConnectorLink] = []+ for application in applications:+ redirect_uris = application.redirect_uris.split()+ if not redirect_uris:+ continue+ query = urlencode(+ {+ "client_id": application.client_id,+ "redirect_uri": redirect_uris[0],+ "response_type": "code",+ "scope": "openid",+ "code_challenge": _code_challenge(_DEV_CODE_VERIFIER),+ "code_challenge_method": "S256",+ }+ )+ links.append(+ DevOAuthConnectorLink(+ client_id=application.client_id,+ client_name=application.name,+ logo_uri=usable_logo_uri(application.logo_uri),+ redirect_host=urlparse(redirect_uris[0]).hostname,+ authorize_path=f"/oauth/authorize/?{query}",+ )+ )+ return linksdiff --git a/posthog/management/commands/generate_demo_data.py b/posthog/management/commands/generate_demo_data.pyindex 8e4863bdb1f4..a7d735655ac0 100644--- a/posthog/management/commands/generate_demo_data.py+++ b/posthog/management/commands/generate_demo_data.py@@ -15,6 +15,7 @@ from django.db.utils import OperationalErrorfrom posthog.api.person import PERSON_DEFAULT_DISPLAY_NAME_PROPERTIESfrom posthog.health import get_pending_postgres_migrations+from posthog.helpers.dev_oauth_connectors import seed_dev_oauth_connectorsfrom posthog.management.commands.sync_feature_flags_from_api import sync_feature_flags_from_apifrom posthog.models.team.setup_tasks import SetupTaskIdfrom posthog.models.team.team import Team@@ -238,6 +239,17 @@ class Command(BaseCommand):else:print("Dashboard template seeds already present.")+ # Same local-only scope as the demo project token, because the dev login tools are what uses them+ if settings.DEBUG and not settings.TEST:+ print("Registering OAuth connector apps from their CIMD documents (dev)...")+ connector_seed = seed_dev_oauth_connectors()+ if connector_seed.created:+ print(f"Registered OAuth connector apps: {', '.join(connector_seed.created)}")+ if connector_seed.failed:+ print(f"Could not register (network or OIDC key missing): {', '.join(connector_seed.failed)}")+ if not connector_seed.created and not connector_seed.failed:+ print("OAuth connector apps already present.")+print("\nMaster project reset!\n"if existing_team_id == 0