:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(oauth): ask users to keep or disconnect unverified partners on first login (#117756)
Matt Brooker75d6ea4c4c06
diff --git a/frontend/snapshots.yml b/frontend/snapshots.ymlindex af2854f4c52a..c3fd059e1858 100644--- a/frontend/snapshots.yml+++ b/frontend/snapshots.yml@@ -15347,13 +15347,13 @@ snapshots:scenes-other-billing-product--billing-product-without-addons--light:hash: v1.k794b7964.1fe58bea4905f6ae9b86f4a04cd31afe7696f9ad14dd09c8063cd8278866ee62.w_4wpfkxEMM9cvslGt2KP3O6hegMMlQZmnnN3eGDdnUscenes-other-credential-review--all-credential-types--dark:- hash: v1.k794b7964.734ead38dd025fbae5ab9b1ec621481f47803d6bac27e6c1921da06801971da7.i4a3jfG-6h4K8JwQc7PA1pT9CgfPqPxzOrGDqIS2JKA+ hash: v1.k794b7964.3c8a9e09b7a869d8223e10ee21cc51094d70f29dbd9187dfce8fff72588f59a8.efASQ5KXuzB_uaz9IObpuCiwN2TJnQUu_YMkeku5tU4scenes-other-credential-review--all-credential-types--light:- hash: v1.k794b7964.7b043550250312fc9811a52faf69314b321e8348f7904266a3f23b3629d32981.Tosd0NV6GhWdXrdkQ9yD8KH658L8Vpc68jyTsV4CvPE+ hash: v1.k794b7964.766a23a47420ba6a708f5084f995dd6ac25a828915284182eba4e88b796393f1.lo1HVZ3WIArWMjw3rTKtjuML0uaSnHGF9b_1hr3UKC0scenes-other-credential-review--only-a-connected-application--dark:- hash: v1.k794b7964.083ab1c7b52303db3543c12ccc1dee1bcd362b7a2b25d19f52634e25bc4fcfb2.SryekUv5NMLDw0c8j5Odv7nQPa-aqNycfHN-e6wtKm4+ hash: v1.k794b7964.3c8a9e09b7a869d8223e10ee21cc51094d70f29dbd9187dfce8fff72588f59a8.Lt0ziuFoVZUtXSlAbaynuoIS5zXugmTX-cVCR2YMr14scenes-other-credential-review--only-a-connected-application--light:- hash: v1.k794b7964.863a15297cedff0b0558c9a91e10190800012f40172a83d8ba0872cbcc8034de.CFQjit_QDWfWGwtrS4ORtDnk5SexHWF6h53-DLHNyGw+ hash: v1.k794b7964.766a23a47420ba6a708f5084f995dd6ac25a828915284182eba4e88b796393f1.tO-SEmx51HDseDPdpQoniCXLAzjt7QNeXqfUAAuXVroscenes-other-integration-landing-page--connect-rejected--dark:hash: v1.k794b7964.744ffc04fe74e99127eee73f8a1c395fe7c56d89447b71465a1797a1ef05b832.2I1sdaQ3oUvbNcUNwdAbHmTjccZ9vnAAUiV5loBZnEoscenes-other-integration-landing-page--connect-rejected--light:diff --git a/frontend/src/generated/core/api.schemas.ts b/frontend/src/generated/core/api.schemas.tsindex e261d1c70a75..26673b3ccdd2 100644--- a/frontend/src/generated/core/api.schemas.ts+++ b/frontend/src/generated/core/api.schemas.ts@@ -7,6 +7,28 @@* PostHog API - core* OpenAPI spec version: 1.0.0*/+export interface ConnectedAppApi {+ /** The OAuth application ID */+ id: string+ /** The application name */+ name: string+ /**+ * URL to the application's logo+ * @nullable+ */+ logo_uri: string | null+ /** Scopes granted to this application */+ scopes: string[]+ /** When the user first authorized this application */+ authorized_at: string+ /** Whether this application has been verified by PostHog */+ is_verified: boolean+ /** Whether this is a first-party PostHog application */+ is_first_party: boolean+ /** Whether the user must choose to keep or disconnect this application, because it set up one of the user's organizations and PostHog has not verified it */+ requires_access_confirmation: boolean+}+/*** * `engineering` - Engineering* * `data` - Datadiff --git a/frontend/src/generated/core/api.ts b/frontend/src/generated/core/api.tsindex ff4de495f8de..508e722923bf 100644--- a/frontend/src/generated/core/api.ts+++ b/frontend/src/generated/core/api.ts@@ -15,6 +15,7 @@ import type {CIMDVerificationTokenCreateApi,CIMDVerificationTokenWithValueApi,CimdVerificationTokensListParams,+ ConnectedAppApi,DataDeletionPreviewApi,DataDeletionRequestApi,DataDeletionRequestCreateApi,@@ -150,6 +151,36 @@ type NonReadonly<T> = [T] extends [UnionToIntersection<T>]}: DistributeReadOnlyOverUnions<T>+export const getOauthConnectedAppsListUrl = () => {+ return `/api/oauth/connected-apps/`+}++/**+ * Returns all OAuth applications that can currently act as the requesting user, whether they hold an unexpired access token or an unrevoked refresh token.+ * @summary List connected OAuth applications+ */+export const oauthConnectedAppsList = async (options?: RequestInit): Promise<ConnectedAppApi[]> => {+ return apiMutator<ConnectedAppApi[]>(getOauthConnectedAppsListUrl(), {+ ...options,+ method: 'GET',+ })+}++export const getOauthConnectedAppsRevokeCreateUrl = (id: string) => {+ return `/api/oauth/connected-apps/${id}/revoke/`+}++/**+ * Revokes all tokens and grants for the specified application for the current user.+ * @summary Revoke a connected OAuth application+ */+export const oauthConnectedAppsRevokeCreate = async (id: string, options?: RequestInit): Promise<void> => {+ return apiMutator<void>(getOauthConnectedAppsRevokeCreateUrl(id), {+ ...options,+ method: 'POST',+ })+}+export const getCimdVerificationTokensListUrl = (organizationId: string, params?: CimdVerificationTokensListParams) => {const normalizedParams = new URLSearchParams()diff --git a/frontend/src/scenes/authentication/account/credential-review/CredentialReview.stories.tsx b/frontend/src/scenes/authentication/account/credential-review/CredentialReview.stories.tsxindex 052cf5fe147d..066ae0bcd1a9 100644--- a/frontend/src/scenes/authentication/account/credential-review/CredentialReview.stories.tsx+++ b/frontend/src/scenes/authentication/account/credential-review/CredentialReview.stories.tsx@@ -2,6 +2,7 @@ import { Meta, StoryObj } from '@storybook/react'import { urls } from 'scenes/urls'+import type { ConnectedAppApi } from '~/generated/core/api.schemas'import { useStorybookMocks } from '~/mocks/browser'import preflightJson from '~/mocks/fixtures/_preflight.json'@@ -42,7 +43,7 @@ const partnerApiKey = {mask_value: 'phx_...abcd',}-const partnerApp = {+const unverifiedPartnerApp: ConnectedAppApi = {id: '0192f0e4-1f2a-7000-8000-000000000001',name: 'Acme Deploy',logo_uri: null,@@ -50,6 +51,18 @@ const partnerApp = {authorized_at: '2026-08-01T09:12:00Z',is_verified: false,is_first_party: false,+ requires_access_confirmation: true,+}++const verifiedPartnerApp: ConnectedAppApi = {+ id: '0192f0e4-1f2a-7000-8000-000000000002',+ name: 'Example Builder',+ logo_uri: null,+ scopes: ['project:read'],+ authorized_at: '2026-08-01T09:11:00Z',+ is_verified: true,+ is_first_party: false,+ requires_access_confirmation: false,}const passkey = {@@ -69,7 +82,7 @@ export const AllCredentialTypes: Story = {'/_preflight': cloudPreflight,'/api/personal_api_keys': [partnerApiKey],'/api/webauthn/credentials/': [passkey],- '/api/oauth/connected-apps/': [partnerApp],+ '/api/oauth/connected-apps/': [unverifiedPartnerApp, verifiedPartnerApp],},})return <CredentialReview />@@ -83,7 +96,7 @@ export const OnlyAConnectedApplication: Story = {'/_preflight': cloudPreflight,'/api/personal_api_keys': [],'/api/webauthn/credentials/': [],- '/api/oauth/connected-apps/': [partnerApp],+ '/api/oauth/connected-apps/': [unverifiedPartnerApp],},})return <CredentialReview />diff --git a/frontend/src/scenes/authentication/account/credential-review/CredentialReview.tsx b/frontend/src/scenes/authentication/account/credential-review/CredentialReview.tsxindex caf646cbcf33..f6c509a7d486 100644--- a/frontend/src/scenes/authentication/account/credential-review/CredentialReview.tsx+++ b/frontend/src/scenes/authentication/account/credential-review/CredentialReview.tsx@@ -6,9 +6,6 @@ import { LemonButton } from '@posthog/lemon-ui'import { pngHoggie } from 'lib/brand/hoggies'import { BridgePage } from 'lib/components/BridgePage/BridgePage'import { SceneExport } from 'scenes/sceneTypes'-import { connectedAppsLogic } from 'scenes/settings/user/connectedAppsLogic'-import { passkeySettingsLogic } from 'scenes/settings/user/passkeySettingsLogic'-import { personalAPIKeysLogic } from 'scenes/settings/user/personalAPIKeysLogic'import { credentialReviewLogic } from './credentialReviewLogic'import { CredentialsReviewList } from './CredentialsReviewList'@@ -22,11 +19,7 @@ const HedgehogHeart = pngHoggie(heartPng)export function CredentialReview(): JSX.Element {const { markComplete } = useActions(credentialReviewLogic)- const { keysLoading } = useValues(personalAPIKeysLogic)- const { passkeysLoading } = useValues(passkeySettingsLogic)- const { connectedAppsLoading } = useValues(connectedAppsLogic)-- const loading = keysLoading || passkeysLoading || connectedAppsLoading+ const { continueDisabledReason, isCompleting } = useValues(credentialReviewLogic)return (<BridgePage view="credential-review" fixedWidth={false}>@@ -47,7 +40,9 @@ export function CredentialReview(): JSX.Element {type="primary"size="large"onClick={() => markComplete()}- disabledReason={loading ? 'Loading your credentials…' : null}+ loading={isCompleting}+ disabledReason={continueDisabledReason}+ data-attr="credential-review-continue">Continue to PostHog</LemonButton>diff --git a/frontend/src/scenes/authentication/account/credential-review/CredentialsReviewList.tsx b/frontend/src/scenes/authentication/account/credential-review/CredentialsReviewList.tsxindex db0036f873a2..7cb1d86276a7 100644--- a/frontend/src/scenes/authentication/account/credential-review/CredentialsReviewList.tsx+++ b/frontend/src/scenes/authentication/account/credential-review/CredentialsReviewList.tsx@@ -10,6 +10,9 @@ import { personalAPIKeysLogic } from 'scenes/settings/user/personalAPIKeysLogic'import { PersonalAPIKeyType } from '~/types'+import { credentialReviewLogic } from './credentialReviewLogic'+import { PartnerAccessChoice } from './PartnerAccessChoice'+function scopeSummary(key: PersonalAPIKeyType): string {if (!key.scopes?.length) {return 'No access'@@ -57,14 +60,25 @@ export function CredentialsReviewList(): JSX.Element {const { deleteKey } = useActions(personalAPIKeysLogic)const { passkeys, passkeysLoading } = useValues(passkeySettingsLogic)const { deletePasskey } = useActions(passkeySettingsLogic)- const { connectedApps, connectedAppsLoading } = useValues(connectedAppsLogic)+ const { connectedAppsLoading } = useValues(connectedAppsLogic)+ const { partnersRequiringChoice, otherConnectedApps } = useValues(credentialReviewLogic)const showKeys = keysLoading || keys.length > 0const showPasskeys = passkeysLoading || passkeys.length > 0- const showConnectedApps = connectedAppsLoading || connectedApps.length > 0+ const showConnectedApps = connectedAppsLoading || otherConnectedApps.length > 0return (<div className="flex flex-col gap-6">+ {partnersRequiringChoice.length > 0 && (+ <section>+ <h3 className="text-base font-semibold mb-2">Confirm app access</h3>+ <div className="flex flex-col gap-2">+ {partnersRequiringChoice.map((app) => (+ <PartnerAccessChoice key={app.id} app={app} />+ ))}+ </div>+ </section>+ )}{showKeys && (<section><h3 className="text-base font-semibold mb-2">Personal API keys</h3>@@ -176,7 +190,7 @@ export function CredentialsReviewList(): JSX.Element {{showConnectedApps && (<section><h3 className="text-base font-semibold mb-2">Connected applications</h3>- <ConnectedApps />+ <ConnectedApps apps={otherConnectedApps} /></section>)}</div>diff --git a/frontend/src/scenes/authentication/account/credential-review/PartnerAccessChoice.tsx b/frontend/src/scenes/authentication/account/credential-review/PartnerAccessChoice.tsxnew file mode 100644index 000000000000..0e8ca95e858b--- /dev/null+++ b/frontend/src/scenes/authentication/account/credential-review/PartnerAccessChoice.tsx@@ -0,0 +1,60 @@+import { decode } from 'he'+import { useActions, useValues } from 'kea'++import { IconCheck } from '@posthog/icons'+import { LemonButton, LemonCard } from '@posthog/lemon-ui'++import type { ConnectedAppApi } from '~/generated/core/api.schemas'++import { credentialReviewLogic } from './credentialReviewLogic'++export function PartnerAccessChoice({ app }: { app: ConnectedAppApi }): JSX.Element {+ const { keptPartnerIds, revokingAppId, isCompleting } = useValues(credentialReviewLogic)+ const { keepPartnerConnected, disconnectPartner } = useActions(credentialReviewLogic)++ // Name is HTML-escaped at ingestion; decode for display (see posthog/api/oauth/client_name.py).+ const name = decode(app.name)+ const isKept = keptPartnerIds.includes(app.id)+ const isRevoking = revokingAppId === app.id++ return (+ <LemonCard hoverEffect={false} className="p-4 flex flex-wrap items-center justify-between gap-3">+ <div className="grow basis-60 min-w-0">+ <div className="font-semibold">{name}</div>+ <p className="text-secondary mb-0">+ {`${name} set up your PostHog organization and has access to your account. Keep it connected only if you asked ${name} to do this.`}+ </p>+ </div>+ <div className="flex flex-wrap gap-2">+ <LemonButton+ type="secondary"+ size="small"+ active={isKept}+ icon={isKept ? <IconCheck /> : undefined}+ onClick={() => keepPartnerConnected(app.id)}+ disabledReason={isRevoking ? `Disconnecting ${name}` : null}+ data-attr="credential-review-keep-partner"+ >+ Keep connected+ </LemonButton>+ <LemonButton+ type="secondary"+ status="danger"+ size="small"+ loading={isRevoking}+ onClick={() => disconnectPartner(app.id)}+ disabledReason={+ isCompleting+ ? 'Saving your review'+ : revokingAppId && !isRevoking+ ? 'Wait for the other app to disconnect'+ : null+ }+ data-attr="credential-review-disconnect-partner"+ >+ Disconnect+ </LemonButton>+ </div>+ </LemonCard>+ )+}diff --git a/frontend/src/scenes/authentication/account/credential-review/credentialReviewLogic.test.ts b/frontend/src/scenes/authentication/account/credential-review/credentialReviewLogic.test.tsindex 8b0574c05916..79bb046af83d 100644--- a/frontend/src/scenes/authentication/account/credential-review/credentialReviewLogic.test.ts+++ b/frontend/src/scenes/authentication/account/credential-review/credentialReviewLogic.test.ts@@ -8,18 +8,49 @@ import { removeProjectIdIfPresent } from 'lib/utils/kea-router'import { urls } from 'scenes/urls'import { userLogic } from 'scenes/userLogic'+import type { ConnectedAppApi } from '~/generated/core/api.schemas'import { useMocks } from '~/mocks/jest'import { initKeaTests } from '~/test/init'import { credentialReviewLogic } from './credentialReviewLogic'+const REVIEW_COMPLETE_URL = '/api/users/@me/credentials_review_complete/'++function connectedApp(id: string, flags: Partial<ConnectedAppApi>): ConnectedAppApi {+ return {+ id,+ name: id,+ logo_uri: null,+ scopes: ['project:read'],+ authorized_at: '2026-08-01T09:12:00Z',+ is_verified: false,+ is_first_party: false,+ requires_access_confirmation: false,+ ...flags,+ }+}++const UNVERIFIED_PARTNER_A = connectedApp('partner-a', { requires_access_confirmation: true })+const UNVERIFIED_PARTNER_B = connectedApp('partner-b', { requires_access_confirmation: true })+const ORDINARY_APP = connectedApp('ordinary-app', {})++function postedUrls(): string[] {+ return jest.mocked(api.create).mock.calls.map(([url]) => url)+}+describe('credentialReviewLogic', () => {+ let connectedApps: ConnectedAppApi[]+ let connectedAppsStatus: number+beforeEach(() => {+ connectedApps = []+ connectedAppsStatus = 200useMocks({get: {'/api/users/@me/': () => [200, MOCK_DEFAULT_USER],'/api/personal_api_keys/': () => [200, []],'/api/webauthn/credentials/': () => [200, []],+ '/api/oauth/connected-apps/': () => [connectedAppsStatus, connectedApps],},})initKeaTests()@@ -42,6 +73,7 @@ describe('credentialReviewLogic', () => {router.actions.push(urls.credentialReview(next))const logic = credentialReviewLogic()logic.mount()+ await expectLogic(logic).toFinishAllListeners()logic.actions.markComplete()await expectLogic(logic).toFinishAllListeners()@@ -49,4 +81,70 @@ describe('credentialReviewLogic', () => {const actualPath = router.values.location.pathname + router.values.location.search + router.values.location.hashexpect(removeProjectIdIfPresent(actualPath)).toEqual(removeProjectIdIfPresent(expectedPath))})++ test('Continue waits until every app that needs confirmation has a choice', async () => {+ connectedApps = [UNVERIFIED_PARTNER_A, UNVERIFIED_PARTNER_B, ORDINARY_APP]+ const logic = credentialReviewLogic()+ logic.mount()+ await expectLogic(logic).toFinishAllListeners()++ logic.actions.markComplete()+ await expectLogic(logic).toFinishAllListeners()+ expect(postedUrls()).toEqual([])++ logic.actions.keepPartnerConnected(UNVERIFIED_PARTNER_A.id)+ logic.actions.markComplete()+ await expectLogic(logic).toFinishAllListeners()+ expect(postedUrls()).toEqual([])++ logic.actions.keepPartnerConnected(UNVERIFIED_PARTNER_B.id)+ logic.actions.markComplete()+ logic.actions.markComplete()+ await expectLogic(logic).toFinishAllListeners()+ expect(postedUrls()).toEqual([REVIEW_COMPLETE_URL])+ })++ test('Continue stays disabled when the connected apps fail to load', async () => {+ connectedAppsStatus = 500+ const logic = credentialReviewLogic()+ logic.mount()+ await expectLogic(logic).toFinishAllListeners()++ logic.actions.markComplete()+ await expectLogic(logic).toFinishAllListeners()+ expect(postedUrls()).toEqual([])+ })++ test('Disconnect revokes the partner once and unblocks Continue', async () => {+ connectedApps = [UNVERIFIED_PARTNER_A]+ const logic = credentialReviewLogic()+ logic.mount()+ await expectLogic(logic).toFinishAllListeners()++ logic.actions.disconnectPartner(UNVERIFIED_PARTNER_A.id)+ logic.actions.disconnectPartner(UNVERIFIED_PARTNER_A.id)+ await expectLogic(logic).toFinishAllListeners()+ expect(postedUrls()).toEqual([`/api/oauth/connected-apps/${UNVERIFIED_PARTNER_A.id}/revoke/`])++ logic.actions.markComplete()+ await expectLogic(logic).toFinishAllListeners()+ expect(postedUrls()).toEqual([+ `/api/oauth/connected-apps/${UNVERIFIED_PARTNER_A.id}/revoke/`,+ REVIEW_COMPLETE_URL,+ ])+ })++ test('Disconnect is ignored while the review is being saved', async () => {+ connectedApps = [UNVERIFIED_PARTNER_A]+ const logic = credentialReviewLogic()+ logic.mount()+ await expectLogic(logic).toFinishAllListeners()++ logic.actions.keepPartnerConnected(UNVERIFIED_PARTNER_A.id)+ logic.actions.markComplete()+ logic.actions.disconnectPartner(UNVERIFIED_PARTNER_A.id)+ await expectLogic(logic).toFinishAllListeners()++ expect(postedUrls()).toEqual([REVIEW_COMPLETE_URL])+ })})diff --git a/frontend/src/scenes/authentication/account/credential-review/credentialReviewLogic.ts b/frontend/src/scenes/authentication/account/credential-review/credentialReviewLogic.tsindex 2d39d8571d1b..23964c55fc5a 100644--- a/frontend/src/scenes/authentication/account/credential-review/credentialReviewLogic.ts+++ b/frontend/src/scenes/authentication/account/credential-review/credentialReviewLogic.ts@@ -1,46 +1,256 @@-import { MakeLogicType, actions, afterMount, connect, kea, listeners, path } from 'kea'+import { MakeLogicType, actions, afterMount, connect, kea, listeners, path, reducers, selectors } from 'kea'import { router } from 'kea-router'+import posthog from 'posthog-js'-import api from 'lib/api'import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'import { getRelativeNextPath } from 'lib/utils/url'+import { connectedAppsLogic } from 'scenes/settings/user/connectedAppsLogic'import { passkeySettingsLogic } from 'scenes/settings/user/passkeySettingsLogic'import { personalAPIKeysLogic } from 'scenes/settings/user/personalAPIKeysLogic'import { urls } from 'scenes/urls'import { userLogic } from 'scenes/userLogic'+import { usersCredentialsReviewCompleteCreate } from '~/generated/core/api'+import type { ConnectedAppApi } from '~/generated/core/api.schemas'++// pinned: analytics event name and properties, renaming breaks dashboards+const PARTNER_ACCESS_CHOSEN_EVENT = 'credential review partner access chosen'++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface credentialReviewLogicValues {+ connectedApps: ConnectedAppApi[] // connectedAppsLogic+ connectedAppsLoading: boolean // connectedAppsLogic+ passkeysLoading: boolean // passkeySettingsLogic+ keysLoading: boolean // personalAPIKeysLogic+ connectedAppsLoadFailed: boolean+ continueDisabledReason: string | null+ isCompleting: boolean+ keptPartnerIds: string[]+ otherConnectedApps: ConnectedAppApi[]+ partnersAwaitingChoice: ConnectedAppApi[]+ partnersRequiringChoice: ConnectedAppApi[]+ revokingAppId: string | null+}+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.export interface credentialReviewLogicActions {+ loadConnectedAppsFailure: (+ error: string,+ errorObject?: any+ ) => {+ error: string+ errorObject?: any+ } // connectedAppsLogic+ loadConnectedAppsSuccess: (+ connectedApps: ConnectedAppApi[],+ payload?: any+ ) => {+ connectedApps: ConnectedAppApi[]+ payload?: any+ } // connectedAppsLogic+ revokeApp: (id: string) => {+ id: string+ } // connectedAppsLogic+ revokeAppFailure: (+ error: string,+ errorObject?: any+ ) => {+ error: string+ errorObject?: any+ } // connectedAppsLogic+ revokeAppSuccess: (+ connectedApps: ConnectedAppApi[],+ payload?:+ | {+ id: string+ }+ | undefined+ ) => {+ connectedApps: ConnectedAppApi[]+ payload?: {+ id: string+ }+ } // connectedAppsLogicloadPasskeys: () => any // passkeySettingsLogicloadKeys: () => {value: true} // personalAPIKeysLogic+ disconnectPartner: (appId: string) => {+ appId: string+ }+ keepPartnerConnected: (appId: string) => {+ appId: string+ }markComplete: () => {value: true}+ setCompleting: (completing: boolean) => {+ completing: boolean+ }+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface credentialReviewLogicMeta {+ __keaTypeGenInternalSelectorTypes: {+ partnersRequiringChoice: (connectedApps: ConnectedAppApi[]) => ConnectedAppApi[]+ otherConnectedApps: (connectedApps: ConnectedAppApi[]) => ConnectedAppApi[]+ partnersAwaitingChoice: (+ partnersRequiringChoice: ConnectedAppApi[],+ keptPartnerIds: string[]+ ) => ConnectedAppApi[]+ continueDisabledReason: (+ revokingAppId: string | null,+ keysLoading: boolean,+ passkeysLoading: boolean,+ connectedAppsLoading: boolean,+ connectedAppsLoadFailed: boolean,+ partnersAwaitingChoice: ConnectedAppApi[]+ ) => string | null+ }}-export type credentialReviewLogicType = MakeLogicType<{}, credentialReviewLogicActions>+export type credentialReviewLogicType = MakeLogicType<+ credentialReviewLogicValues,+ credentialReviewLogicActions,+ Record<string, any>,+ credentialReviewLogicMeta+>export const credentialReviewLogic = kea<credentialReviewLogicType>([path(['scenes', 'authentication', 'account', 'credential-review', 'credentialReviewLogic']),- // connect (not bare import calls) so both list logics are mounted as dependencies+ // connect (not bare import calls) so the list logics are mounted as dependencies// of this scene logic. afterMount runs before the review component renders, so without// this the load calls below hit an unmounted logic and throw, which sceneLogic// catches and turns into a 404 for the whole credential review screen.connect(() => ({- actions: [personalAPIKeysLogic, ['loadKeys'], passkeySettingsLogic, ['loadPasskeys']],+ values: [+ connectedAppsLogic,+ ['connectedApps', 'connectedAppsLoading'],+ passkeySettingsLogic,+ ['passkeysLoading'],+ personalAPIKeysLogic,+ ['keysLoading'],+ ],+ actions: [+ connectedAppsLogic,+ [+ 'loadConnectedAppsFailure',+ 'loadConnectedAppsSuccess',+ 'revokeApp',+ 'revokeAppFailure',+ 'revokeAppSuccess',+ ],+ passkeySettingsLogic,+ ['loadPasskeys'],+ personalAPIKeysLogic,+ ['loadKeys'],+ ],})),actions({+ keepPartnerConnected: (appId: string) => ({ appId }),+ disconnectPartner: (appId: string) => ({ appId }),markComplete: true,+ setCompleting: (completing: boolean) => ({ completing }),+ }),+ reducers({+ keptPartnerIds: [+ [] as string[],+ {+ keepPartnerConnected: (state, { appId }) => (state.includes(appId) ? state : [...state, appId]),+ },+ ],+ revokingAppId: [+ null as string | null,+ {+ revokeApp: (_, { id }) => id,+ revokeAppSuccess: () => null,+ revokeAppFailure: () => null,+ },+ ],+ isCompleting: [+ false,+ {+ setCompleting: (_, { completing }) => completing,+ },+ ],+ connectedAppsLoadFailed: [+ false,+ {+ loadConnectedAppsFailure: () => true,+ loadConnectedAppsSuccess: () => false,+ },+ ],+ }),+ selectors({+ partnersRequiringChoice: [+ (s) => [s.connectedApps],+ (connectedApps: ConnectedAppApi[]): ConnectedAppApi[] =>+ connectedApps.filter((app) => app.requires_access_confirmation),+ ],+ otherConnectedApps: [+ (s) => [s.connectedApps],+ (connectedApps: ConnectedAppApi[]): ConnectedAppApi[] =>+ connectedApps.filter((app) => !app.requires_access_confirmation),+ ],+ partnersAwaitingChoice: [+ (s) => [s.partnersRequiringChoice, s.keptPartnerIds],+ (partnersRequiringChoice: ConnectedAppApi[], keptPartnerIds: string[]): ConnectedAppApi[] =>+ partnersRequiringChoice.filter((app) => !keptPartnerIds.includes(app.id)),+ ],+ continueDisabledReason: [+ (s) => [+ s.revokingAppId,+ s.keysLoading,+ s.passkeysLoading,+ s.connectedAppsLoading,+ s.connectedAppsLoadFailed,+ s.partnersAwaitingChoice,+ ],+ (+ revokingAppId: string | null,+ keysLoading: boolean,+ passkeysLoading: boolean,+ connectedAppsLoading: boolean,+ connectedAppsLoadFailed: boolean,+ partnersAwaitingChoice: ConnectedAppApi[]+ ): string | null => {+ if (revokingAppId) {+ return 'Disconnecting app…'+ }+ if (keysLoading || passkeysLoading || connectedAppsLoading) {+ return 'Loading your credentials…'+ }+ if (connectedAppsLoadFailed) {+ return 'Could not load your connected apps. Reload the page to try again.'+ }+ if (partnersAwaitingChoice.length > 0) {+ return 'Choose to keep or disconnect each app above'+ }+ return null+ },+ ],}),- listeners({+ listeners(({ actions, values }) => ({+ keepPartnerConnected: ({ appId }) => {+ posthog.capture(PARTNER_ACCESS_CHOSEN_EVENT, { choice: 'keep', application_id: appId })+ },+ disconnectPartner: ({ appId }) => {+ if (values.revokingAppId || values.isCompleting) {+ return+ }+ posthog.capture(PARTNER_ACCESS_CHOSEN_EVENT, { choice: 'disconnect', application_id: appId })+ actions.revokeApp(appId)+ },markComplete: async () => {+ if (values.isCompleting || values.continueDisabledReason) {+ return+ }+ actions.setCompleting(true)try {- // nosemgrep: prefer-codegen-api -- Legacy raw API call with a hand-written URL and an unchecked response type. usersCredentialsReviewCompleteCreate() from '~/generated/core/api' serves this route, but its generated types do not describe this call yet, so fix the endpoint's OpenAPI schema first.- await api.create('api/users/@me/credentials_review_complete/')+ await usersCredentialsReviewCompleteCreate('@me')} catch {lemonToast.error('Could not save your review. Try again.')+ actions.setCompleting(false)return}// Flip the local user state's requires_credential_review via reducer before@@ -51,7 +261,7 @@ export const credentialReviewLogic = kea<credentialReviewLogicType>([const nextPath = getRelativeNextPath(router.values.searchParams['next'], location)router.actions.push(nextPath ?? urls.projectHomepage())},- }),+ })),afterMount(({ actions }) => {// Neither logic auto-loads its list on mount, so trigger both here. Otherwise// the review screen would render empty until the user hit the settings page.diff --git a/frontend/src/scenes/settings/user/ConnectedApps.tsx b/frontend/src/scenes/settings/user/ConnectedApps.tsxindex 21c82d1162d8..97abda06fbb2 100644--- a/frontend/src/scenes/settings/user/ConnectedApps.tsx+++ b/frontend/src/scenes/settings/user/ConnectedApps.tsx@@ -9,7 +9,9 @@ import { pngHoggie } from 'lib/brand/hoggies'import { IconKey } from 'lib/lemon-ui/icons'import { humanFriendlyDetailedTime } from 'lib/utils/datetime'-import { connectedAppsLogic, ConnectedApp } from './connectedAppsLogic'+import type { ConnectedAppApi } from '~/generated/core/api.schemas'++import { connectedAppsLogic } from './connectedAppsLogic'const HedgehogMagnifyingGlass = pngHoggie(magnifyingGlassPng)@@ -50,11 +52,11 @@ function ScopesAccordion({ scopes }: { scopes: string[] }): JSX.Element {)}-export function ConnectedApps(): JSX.Element {+export function ConnectedApps({ apps }: { apps?: ConnectedAppApi[] }): JSX.Element {const { connectedApps, connectedAppsLoading } = useValues(connectedAppsLogic)const { revokeApp } = useActions(connectedAppsLogic)- const handleRevoke = (app: ConnectedApp): void => {+ const handleRevoke = (app: ConnectedAppApi): void => {// Name is HTML-escaped at ingestion; decode for display (see posthog/api/oauth/client_name.py).const name = decode(app.name)@@ -74,7 +76,7 @@ export function ConnectedApps(): JSX.Element {return (<LemonTable- dataSource={connectedApps}+ dataSource={apps ?? connectedApps}loading={connectedAppsLoading}columns={[{diff --git a/frontend/src/scenes/settings/user/connectedAppsLogic.test.ts b/frontend/src/scenes/settings/user/connectedAppsLogic.test.tsindex 2e732ad5e197..1143fc979e53 100644--- a/frontend/src/scenes/settings/user/connectedAppsLogic.test.ts+++ b/frontend/src/scenes/settings/user/connectedAppsLogic.test.ts@@ -2,12 +2,13 @@ import { expectLogic } from 'kea-test-utils'import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'+import type { ConnectedAppApi } from '~/generated/core/api.schemas'import { useMocks } from '~/mocks/jest'import { initKeaTests } from '~/test/init'-import { ConnectedApp, connectedAppsLogic } from './connectedAppsLogic'+import { connectedAppsLogic } from './connectedAppsLogic'-const APP_A: ConnectedApp = {+const APP_A: ConnectedAppApi = {id: 'app-a',name: 'App A',logo_uri: null,@@ -15,9 +16,10 @@ const APP_A: ConnectedApp = {authorized_at: '2026-06-18T00:00:00Z',is_verified: true,is_first_party: false,+ requires_access_confirmation: false,}-const APP_B: ConnectedApp = {+const APP_B: ConnectedAppApi = {id: 'app-b',name: 'App B',logo_uri: null,@@ -25,6 +27,7 @@ const APP_B: ConnectedApp = {authorized_at: '2026-06-10T00:00:00Z',is_verified: false,is_first_party: false,+ requires_access_confirmation: false,}async function waitForInFlightRevoke(getResolve: () => (() => void) | undefined): Promise<() => void> {@@ -77,6 +80,23 @@ describe('connectedAppsLogic', () => {expect(lemonToast.success).toHaveBeenCalled()})+ it('reloads the list when the app had already lost access', async () => {+ await expectLogic(logic).toFinishAllListeners()+ useMocks({+ get: {+ '/api/oauth/connected-apps/': () => [200, [APP_B]],+ },+ post: {+ '/api/oauth/connected-apps/:id/revoke/': () => [404, { detail: 'No active connection found.' }],+ },+ })++ logic.actions.revokeApp(APP_A.id)+ await expectLogic(logic).toFinishAllListeners()++ expect(logic.values.connectedApps).toEqual([APP_B])+ })+it('does not toast when the logic unmounts mid-revoke', async () => {jest.spyOn(lemonToast, 'success')await expectLogic(logic).toFinishAllListeners()diff --git a/frontend/src/scenes/settings/user/connectedAppsLogic.ts b/frontend/src/scenes/settings/user/connectedAppsLogic.tsindex 7a51fa0cdbfc..76048c24e170 100644--- a/frontend/src/scenes/settings/user/connectedAppsLogic.ts+++ b/frontend/src/scenes/settings/user/connectedAppsLogic.ts@@ -1,22 +1,14 @@-import { MakeLogicType, actions, events, kea, path } from 'kea'+import { MakeLogicType, actions, events, kea, listeners, path } from 'kea'import { loaders } from 'kea-loaders'-import api from 'lib/api'import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'-export interface ConnectedApp {- id: string- name: string- logo_uri: string | null- scopes: string[]- authorized_at: string- is_verified: boolean- is_first_party: boolean-}+import { oauthConnectedAppsList, oauthConnectedAppsRevokeCreate } from '~/generated/core/api'+import type { ConnectedAppApi } from '~/generated/core/api.schemas'// Generated by kea-typegen. Update if you're an agent, ignore if you're human.export interface connectedAppsLogicValues {- connectedApps: ConnectedApp[]+ connectedApps: ConnectedAppApi[]connectedAppsLoading: boolean}@@ -31,10 +23,10 @@ export interface connectedAppsLogicActions {errorObject?: any}loadConnectedAppsSuccess: (- connectedApps: ConnectedApp[],+ connectedApps: ConnectedAppApi[],payload?: any) => {- connectedApps: ConnectedApp[]+ connectedApps: ConnectedAppApi[]payload?: any}revokeApp: (id: string) => {@@ -48,12 +40,12 @@ export interface connectedAppsLogicActions {errorObject?: any}revokeAppSuccess: (- connectedApps: ConnectedApp[],+ connectedApps: ConnectedAppApi[],payload?: {id: string}) => {- connectedApps: ConnectedApp[]+ connectedApps: ConnectedAppApi[]payload?: {id: string}@@ -71,16 +63,14 @@ export const connectedAppsLogic = kea<connectedAppsLogicType>([loaders(({ values }) => ({connectedApps: [- [] as ConnectedApp[],+ [] as ConnectedAppApi[],{loadConnectedApps: async () => {- // 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.- return await api.get('api/oauth/connected-apps/')+ return await oauthConnectedAppsList()},revokeApp: async ({ id }, breakpoint) => {const remainingApps = values.connectedApps.filter((app) => app.id !== id)- // 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.- await api.create(`api/oauth/connected-apps/${id}/revoke/`)+ await oauthConnectedAppsRevokeCreate(id)breakpoint()lemonToast.success('App access revoked')return remainingApps@@ -89,6 +79,15 @@ export const connectedAppsLogic = kea<connectedAppsLogicType>([],})),+ listeners(({ actions }) => ({+ revokeAppFailure: ({ errorObject }) => {+ // A 404 means the access already lapsed, so the listed row is stale.+ if (errorObject?.status === 404) {+ actions.loadConnectedApps()+ }+ },+ })),+events(({ actions }) => ({afterMount: () => actions.loadConnectedApps(),})),diff --git a/posthog/api/oauth/connected_apps.py b/posthog/api/oauth/connected_apps.pyindex 3d5db9587d05..271c73b9aad5 100644--- a/posthog/api/oauth/connected_apps.py+++ b/posthog/api/oauth/connected_apps.py@@ -15,6 +15,7 @@ from posthog.models.oauth import (live_oauth_refresh_tokens,revoke_oauth_session,)+from posthog.models.organization_provisioning import OrganizationProvisioningfrom posthog.models.user import Userfrom posthog.permissions import TimeSensitiveActionPermission@@ -27,14 +28,21 @@ class ConnectedAppSerializer(serializers.Serializer):authorized_at = serializers.DateTimeField(help_text="When the user first authorized this application")is_verified = serializers.BooleanField(help_text="Whether this application has been verified by PostHog")is_first_party = serializers.BooleanField(help_text="Whether this is a first-party PostHog application")+ requires_access_confirmation = serializers.BooleanField(+ help_text=(+ "Whether the user must choose to keep or disconnect this application, because it set up one of "+ "the user's organizations and PostHog has not verified it"+ )+ )-@extend_schema(tags=["oauth"])+@extend_schema(tags=["oauth"], extensions={"x-product": "core"})class ConnectedAppsViewSet(viewsets.ViewSet):"""ViewSet for listing and revoking OAuth applications connected to the current user."""+ scope_object = "INTERNAL"authentication_classes = [SessionAuthentication]permission_classes = [IsAuthenticated, TimeSensitiveActionPermission]http_method_names = ["get", "post"]@@ -70,6 +78,11 @@ class ConnectedAppsViewSet(viewsets.ViewSet):record(refresh_token["application_id"], refresh_token["created"], refresh_token["access_token__scope"])applications = OAuthApplication.objects.filter(id__in=app_map.keys())+ provisioner_ids = set(+ OrganizationProvisioning.objects.filter(+ application_id__in=app_map.keys(), organization__membership__user=user+ ).values_list("application_id", flat=True)+ )results = []for app in applications:@@ -83,6 +96,9 @@ class ConnectedAppsViewSet(viewsets.ViewSet):"authorized_at": app_data["authorized_at"],"is_verified": app.is_verified,"is_first_party": app.is_first_party,+ "requires_access_confirmation": (+ app.id in provisioner_ids and not app.is_verified and not app.is_first_party+ ),})@@ -91,6 +107,7 @@ class ConnectedAppsViewSet(viewsets.ViewSet):return Response(serializer.data)@extend_schema(+ request=None,responses={204: None},summary="Revoke a connected OAuth application",description="Revokes all tokens and grants for the specified application for the current user.",diff --git a/posthog/api/oauth/test_connected_apps.py b/posthog/api/oauth/test_connected_apps.pyindex ce7a2320e1c0..013efcd27134 100644--- a/posthog/api/oauth/test_connected_apps.py+++ b/posthog/api/oauth/test_connected_apps.py@@ -1,5 +1,6 @@import uuidfrom datetime import timedelta+from typing import Literalimport time_machinefrom posthog.test.base import APIBaseTest@@ -11,6 +12,8 @@ from rest_framework import statusfrom rest_framework.test import APIClientfrom posthog.models.oauth import OAuthAccessToken, OAuthApplication, OAuthGrant, OAuthRefreshToken+from posthog.models.organization import Organization+from posthog.models.organization_provisioning import OrganizationProvisioningfrom posthog.models.user import User@@ -136,15 +139,68 @@ class TestConnectedAppsViewSet(APIBaseTest):assert response.status_code == status.HTTP_200_OKassert len(response.json()) == 2- def test_list_shows_verified_and_first_party_flags(self):- app = self._create_app(is_verified=True, is_first_party=True)+ @parameterized.expand(+ [+ (+ "unverified_partner_that_set_up_the_users_org",+ {"is_provisioning_partner": True},+ "own",+ {"is_verified": False, "is_first_party": False, "requires_access_confirmation": True},+ ),+ (+ "verified_partner",+ {"is_provisioning_partner": True, "is_verified": True},+ "own",+ {"is_verified": True, "is_first_party": False, "requires_access_confirmation": False},+ ),+ (+ "first_party_partner",+ {"is_provisioning_partner": True, "is_first_party": True},+ "own",+ {"is_verified": False, "is_first_party": True, "requires_access_confirmation": False},+ ),+ (+ "partner_switched_off_after_setting_up_the_users_org",+ {"is_provisioning_partner": False},+ "own",+ {"requires_access_confirmation": True},+ ),+ (+ "partner_the_user_authorized_directly",+ {"is_provisioning_partner": True, "provisioning": {"can_create_accounts": True}},+ None,+ {"requires_access_confirmation": False},+ ),+ (+ "partner_that_set_up_another_org",+ {"is_provisioning_partner": True},+ "other",+ {"requires_access_confirmation": False},+ ),+ ]+ )+ def test_list_shows_trust_flags(+ self,+ _name: str,+ app_kwargs: dict,+ provisioned_org: Literal["own", "other"] | None,+ expected_flags: dict[str, bool],+ ):+ app = self._create_app(**app_kwargs)self._create_token(app)+ if provisioned_org is not None:+ OrganizationProvisioning.objects.create(+ organization=self.organization+ if provisioned_org == "own"+ else Organization.objects.create(name="Someone else's org"),+ partner=OrganizationProvisioning.Partner.PROVISIONING_API,+ application=app,+ )response = self.client.get("/api/oauth/connected-apps/")data = response.json()[0]- assert data["is_verified"] is True- assert data["is_first_party"] is True+ assert {flag: data[flag] for flag in expected_flags} == expected_flagsdef test_revoke_deletes_all_tokens_for_app(self):app = self._create_app()diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex c7a35fe912fb..80b3dbb4c33f 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -24650,6 +24650,28 @@ export namespace Schemas {PosthogCode: 'posthog_code',} as const;+ export interface ConnectedApp {+ /** The OAuth application ID */+ id: string;+ /** The application name */+ name: string;+ /**+ * URL to the application's logo+ * @nullable+ */+ logo_uri: string | null;+ /** Scopes granted to this application */+ scopes: string[];+ /** When the user first authorized this application */+ authorized_at: string;+ /** Whether this application has been verified by PostHog */+ is_verified: boolean;+ /** Whether this is a first-party PostHog application */+ is_first_party: boolean;+ /** Whether the user must choose to keep or disconnect this application, because it set up one of the user's organizations and PostHog has not verified it */+ requires_access_confirmation: boolean;+ }+/*** * `ready` - ready* * `pending_oauth` - pending_oauth