Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(oauth): device grant for CIMD clients, with its approval page (#127811)

Rafael Audibertd32b65d47631
diff --git a/bin/ensure-local-setup b/bin/ensure-local-setup
index 22ecfe3d8a73..8df2d08ab476 100755
--- a/bin/ensure-local-setup
+++ b/bin/ensure-local-setup
@@ -96,6 +96,7 @@ STEPS = [
("wizard cloud-run OAuth app", ensure_wizard_oauth_app),
# Local migrate runs use --scope=postgres, which skips bin/migrate's tasks-oauth scope, so seed the sandbox agent OAuth apps here.
("task sandbox OAuth apps", lambda: call_command("setup_tasks_oauth")),
+ ("PostHog CIMD apps", lambda: call_command("setup_posthog_cimd_apps")),
]
diff --git a/frontend/bin/build-app-url-manifest.mjs b/frontend/bin/build-app-url-manifest.mjs
index a535c7b4d702..31cb00e54338 100644
--- a/frontend/bin/build-app-url-manifest.mjs
+++ b/frontend/bin/build-app-url-manifest.mjs
@@ -45,6 +45,7 @@ const PATHS_WITHOUT_PROJECT_ID = new Set([
'embedded',
'interview',
'cli',
+ 'device',
'render_query',
])
// Instance-level pages living under a product's own prefix, so a first-segment check misses them.
diff --git a/frontend/src/generated/core/api.schemas.ts b/frontend/src/generated/core/api.schemas.ts
index 999fcd898e5e..88eae823a3ef 100644
--- a/frontend/src/generated/core/api.schemas.ts
+++ b/frontend/src/generated/core/api.schemas.ts
@@ -68,6 +68,21 @@ export interface DeviceUserCodeApi {
user_code: string
}
+export interface GrantedScopesApi {
+ /**
+ * The project these scopes work in. Null when the connection is not limited to projects.
+ * @nullable
+ */
+ project_id: number | null
+ /**
+ * The organization these scopes work in, for a connection limited to organizations. Null when the connection is not limited to organizations.
+ * @nullable
+ */
+ organization_id: string | null
+ /** The scopes granted in the project. */
+ scopes: string[]
+}
+
export interface DeviceGrantDetailsApi {
/** The code, in the form the device shows it. */
user_code: string
@@ -84,6 +99,8 @@ export interface DeviceGrantDetailsApi {
is_verified: boolean
/** The scopes the token will carry if the person approves. */
scopes: string[]
+ /** The scopes the person already gave this client, per project. A step-up in a project asks for these plus new ones, and the page lists only the new ones. */
+ granted_scopes: GrantedScopesApi[]
/** When the code expires. */
expires_at: string
}
diff --git a/frontend/src/lib/utils/kea-router.ts b/frontend/src/lib/utils/kea-router.ts
index 901a76e1db52..3aaa574ae2e1 100644
--- a/frontend/src/lib/utils/kea-router.ts
+++ b/frontend/src/lib/utils/kea-router.ts
@@ -18,6 +18,7 @@ const pathsWithoutProjectId = [
'embedded',
'interview',
'cli',
+ 'device',
'render_query',
]
diff --git a/frontend/src/scenes/appScenes.ts b/frontend/src/scenes/appScenes.ts
index f95d4d21442f..fa8f59ceb9ad 100644
--- a/frontend/src/scenes/appScenes.ts
+++ b/frontend/src/scenes/appScenes.ts
@@ -18,6 +18,7 @@ export const appScenes: Record<Scene | string, () => any> = {
[Scene.Billing]: () => import('./billing/Billing'),
[Scene.Canvas]: () => import('./notebooks/NotebookCanvasScene'),
[Scene.CLIAuthorize]: () => import('./authentication/cli/CLIAuthorize'),
+ [Scene.OAuthDeviceAuthorize]: () => import('./authentication/device/OAuthDeviceAuthorize'),
[Scene.CLILive]: () => import('./authentication/cli/CLILive'),
[Scene.Cohort]: () => import('./cohorts/Cohort'),
[Scene.CohortCalculationHistory]: () => import('./cohorts/CohortCalculationHistory'),
diff --git a/frontend/src/scenes/authentication/device/OAuthDeviceAuthorize.tsx b/frontend/src/scenes/authentication/device/OAuthDeviceAuthorize.tsx
new file mode 100644
index 000000000000..37edbf99a491
--- /dev/null
+++ b/frontend/src/scenes/authentication/device/OAuthDeviceAuthorize.tsx
@@ -0,0 +1,208 @@
+import { useActions, useValues } from 'kea'
+
+import { IconCheck } from '@posthog/icons'
+import { LemonButton, LemonInput, LemonSelect, LemonTag } from '@posthog/lemon-ui'
+
+import { LemonField } from 'lib/lemon-ui/LemonField'
+import { AuthBanner } from 'scenes/authentication/shared/authScene/AuthBanner'
+import { AuthCardTitle } from 'scenes/authentication/shared/authScene/AuthCardTitle'
+import { AUTH_NOTES } from 'scenes/authentication/shared/authScene/authNotes'
+import { AuthScene, AuthSceneCard } from 'scenes/authentication/shared/authScene/AuthScene'
+import { SceneExport } from 'scenes/sceneTypes'
+
+import { oauthDeviceAuthorizeLogic } from './oauthDeviceAuthorizeLogic'
+
+export const scene: SceneExport = {
+ component: OAuthDeviceAuthorize,
+ logic: oauthDeviceAuthorizeLogic,
+}
+
+export function OAuthDeviceAuthorize(): JSX.Element {
+ const {
+ userCode,
+ deviceGrant,
+ deviceGrantLoading,
+ organizationId,
+ organizations,
+ projectId,
+ projects,
+ projectsLoading,
+ projectsError,
+ decision,
+ decisionLoading,
+ error,
+ isStepUp,
+ scopeDescriptions,
+ } = useValues(oauthDeviceAuthorizeLogic)
+ const { setUserCode, lookUpCode, setOrganizationId, setProjectId, loadProjects, approve, deny } =
+ useActions(oauthDeviceAuthorizeLogic)
+
+ if (decision) {
+ const approved = decision === 'authorized'
+ return (
+ <AuthScene notes={approved ? AUTH_NOTES.oauthDevice.approved : AUTH_NOTES.oauthDevice.denied}>
+ <AuthSceneCard>
+ <AuthCardTitle
+ title={approved ? 'Login approved' : 'Login denied'}
+ sub="You can close this window and go back to where you started the login."
+ />
+ </AuthSceneCard>
+ </AuthScene>
+ )
+ }
+
+ if (!deviceGrant) {
+ return (
+ <AuthScene notes={AUTH_NOTES.oauthDevice.enterCode}>
+ <AuthSceneCard>
+ <AuthCardTitle title="Approve a login" sub="Type the code your terminal shows, like BCDF-GHJK." />
+ <form
+ className="flex flex-col gap-4"
+ onSubmit={(event) => {
+ event.preventDefault()
+ lookUpCode()
+ }}
+ >
+ <LemonField.Pure label="Code" error={error}>
+ <LemonInput
+ className="ph-ignore-input font-mono text-lg tracking-wider"
+ autoFocus
+ data-attr="oauth-device-code"
+ placeholder="BCDF-GHJK"
+ maxLength={20}
+ value={userCode}
+ onChange={setUserCode}
+ autoComplete="off"
+ autoCorrect="off"
+ autoCapitalize="characters"
+ spellCheck={false}
+ />
+ </LemonField.Pure>
+ <LemonButton
+ type="primary"
+ htmlType="submit"
+ data-attr="oauth-device-continue"
+ fullWidth
+ center
+ size="large"
+ loading={deviceGrantLoading}
+ disabledReason={userCode.trim() ? undefined : 'Type the code first'}
+ >
+ Continue
+ </LemonButton>
+ </form>
+ </AuthSceneCard>
+ </AuthScene>
+ )
+ }
+
+ return (
+ <AuthScene notes={AUTH_NOTES.oauthDevice.review}>
+ <AuthSceneCard>
+ <AuthCardTitle
+ title={
+ isStepUp
+ ? `${deviceGrant.client_name} wants more access`
+ : `${deviceGrant.client_name} wants to access your PostHog account`
+ }
+ sub="Check that this code matches the one your terminal shows."
+ />
+ <div className="flex flex-col gap-4">
+ <div className="flex items-center justify-center gap-2">
+ <span
+ className="ph-no-capture font-mono text-2xl font-semibold tracking-wider"
+ data-attr="oauth-device-user-code"
+ >
+ {deviceGrant.user_code}
+ </span>
+ {deviceGrant.is_verified && <LemonTag type="success">Verified app</LemonTag>}
+ </div>
+ <AuthBanner variant="warning">
+ Only approve a login you started yourself. If someone sent you this code, deny it: approving
+ gives them access to your account.
+ </AuthBanner>
+ <LemonField.Pure label="Organization">
+ <LemonSelect
+ data-attr="oauth-device-organization"
+ placeholder="Select an organization"
+ value={organizationId}
+ onChange={setOrganizationId}
+ options={organizations.map((organization) => ({
+ label: organization.name,
+ value: organization.id,
+ }))}
+ />
+ </LemonField.Pure>
+ <LemonField.Pure label="Project" help="The login only works in this project.">
+ <LemonSelect
+ data-attr="oauth-device-project"
+ placeholder="Select a project"
+ value={projectId}
+ onChange={setProjectId}
+ disabledReason={organizationId ? undefined : 'Select an organization first'}
+ loading={projectsLoading}
+ options={projects.map((project) => ({ label: project.name, value: project.id }))}
+ />
+ </LemonField.Pure>
+ {projectsError && organizationId && (
+ <AuthBanner variant="danger">
+ <div className="flex flex-wrap items-center justify-between gap-2">
+ <span>Couldn't load the projects. {projectsError}</span>
+ <LemonButton
+ type="secondary"
+ size="small"
+ onClick={() => loadProjects(organizationId)}
+ loading={projectsLoading}
+ data-attr="oauth-device-retry-projects"
+ >
+ Try again
+ </LemonButton>
+ </div>
+ </AuthBanner>
+ )}
+ <div>
+ <p className="mb-2 font-semibold">
+ {isStepUp
+ ? `${deviceGrant.client_name} keeps the access you gave it, and will also be able to:`
+ : `${deviceGrant.client_name} will be able to:`}
+ </p>
+ <ul className="max-h-64 overflow-y-auto space-y-1 pr-1">
+ {scopeDescriptions.map((description) => (
+ <li key={description} className="flex items-center gap-2">
+ <IconCheck color="var(--success)" className="shrink-0" />
+ <span>{description}</span>
+ </li>
+ ))}
+ </ul>
+ </div>
+ {error && <AuthBanner variant="danger">{error}</AuthBanner>}
+ <div className="grid grid-cols-2 gap-2">
+ <LemonButton
+ type="secondary"
+ data-attr="oauth-device-deny"
+ fullWidth
+ center
+ size="large"
+ onClick={deny}
+ disabledReason={decisionLoading ? 'Sending your answer' : undefined}
+ >
+ Deny
+ </LemonButton>
+ <LemonButton
+ type="primary"
+ data-attr="oauth-device-approve"
+ fullWidth
+ center
+ size="large"
+ onClick={approve}
+ loading={decisionLoading}
+ disabledReason={projectId === null ? 'Select a project first' : undefined}
+ >
+ Approve
+ </LemonButton>
+ </div>
+ </div>
+ </AuthSceneCard>
+ </AuthScene>
+ )
+}
diff --git a/frontend/src/scenes/authentication/device/oauthDeviceAuthorizeLogic.test.ts b/frontend/src/scenes/authentication/device/oauthDeviceAuthorizeLogic.test.ts
new file mode 100644
index 000000000000..3f8363e5ab92
--- /dev/null
+++ b/frontend/src/scenes/authentication/device/oauthDeviceAuthorizeLogic.test.ts
@@ -0,0 +1,154 @@
+import { router } from 'kea-router'
+import { expectLogic } from 'kea-test-utils'
+
+import { urls } from 'scenes/urls'
+
+import type { DeviceGrantDetailsApi } from '~/generated/core/api.schemas'
+import { useMocks } from '~/mocks/jest'
+import { initKeaTests } from '~/test/init'
+
+import { oauthDeviceAuthorizeLogic } from './oauthDeviceAuthorizeLogic'
+
+const GRANT: DeviceGrantDetailsApi = {
+ user_code: 'BCDF-GHJK',
+ client_id: 'https://posthog.com/.well-known/oauth/hog/client-metadata.json',
+ client_name: 'hog',
+ logo_uri: null,
+ is_verified: false,
+ scopes: ['openid', 'insight:read', 'insight:write', 'dashboard:write'],
+ granted_scopes: [],
+ expires_at: '2026-03-02T10:30:00Z',
+}
+
+describe('oauthDeviceAuthorizeLogic', () => {
+ let lookups: string[]
+ let approvals: unknown[]
+
+ function useGrantMocks(grant: DeviceGrantDetailsApi): void {
+ useMocks({
+ post: {
+ '/api/oauth_device/lookup/': async ({ request }) => {
+ lookups.push(((await request.json()) as { user_code: string }).user_code)
+ return [200, grant]
+ },
+ '/api/oauth_device/approve/': async ({ request }) => {
+ approvals.push(await request.json())
+ return [200, { status: 'authorized' }]
+ },
+ },
+ })
+ }
+
+ beforeEach(() => {
+ lookups = []
+ approvals = []
+ initKeaTests()
+ })
+
+ const ALL = ['View your User ID', 'Write access to insights', 'Write access to dashboards']
+
+ it.each([
+ ['a first login lists every requested scope', [], ALL, false],
+ [
+ 'a login that adds nothing in the project lists every scope',
+ [
+ {
+ project_id: 42,
+ organization_id: null,
+ scopes: ['openid', 'insight:read', 'insight:write', 'dashboard:write'],
+ },
+ ],
+ ALL,
+ false,
+ ],
+ [
+ 'a step-up lists only the scopes it adds in the project',
+ [{ project_id: 42, organization_id: null, scopes: ['openid', 'insight:read'] }],
+ ['Write access to insights', 'Write access to dashboards'],
+ true,
+ ],
+ [
+ 'scopes granted in another organization count for nothing here',
+ [{ project_id: null, organization_id: 'another-org', scopes: ['openid', 'insight:read'] }],
+ ALL,
+ false,
+ ],
+ [
+ 'scopes granted in another project count for nothing here',
+ [{ project_id: 7, organization_id: null, scopes: ['openid', 'insight:read'] }],
+ ALL,
+ false,
+ ],
+ ])('%s', async (_name, grantedScopes, expectedDescriptions, isStepUp) => {
+ useGrantMocks({ ...GRANT, granted_scopes: grantedScopes })
+ const logic = oauthDeviceAuthorizeLogic()
+ logic.mount()
+
+ router.actions.push(urls.oauthDeviceAuthorize(), { code: 'bcdf-ghjk' })
+ await expectLogic(logic).toFinishAllListeners()
+ logic.actions.setProjectId(42)
+
+ expect(lookups).toEqual(['BCDF-GHJK'])
+ await expectLogic(logic).toMatchValues({ isStepUp, scopeDescriptions: expectedDescriptions })
+ })
+
+ it("drops the previous organization's projects when the next ones fail to load", async () => {
+ useMocks({
+ get: {
+ '/api/organizations/:organizationId/projects/': ({ params }) =>
+ params.organizationId === 'org-a'
+ ? [200, { results: [{ id: 1, name: 'A project' }], next: null }]
+ : [500, { detail: 'boom' }],
+ },
+ })
+ const logic = oauthDeviceAuthorizeLogic()
+ logic.mount()
+ logic.actions.setOrganizationId('org-a')
+ await expectLogic(logic).toFinishAllListeners()
+
+ logic.actions.setOrganizationId('org-b')
+ await expectLogic(logic).toFinishAllListeners()
+
+ await expectLogic(logic).toMatchValues({ projects: [], projectsError: expect.any(String) })
+ })
+
+ it('approves the code the server returned, for the project the person picked', async () => {
+ useGrantMocks(GRANT)
+ const logic = oauthDeviceAuthorizeLogic()
+ logic.mount()
+ router.actions.push(urls.oauthDeviceAuthorize(), { code: 'bcdf ghjk' })
+ await expectLogic(logic).toFinishAllListeners()
+
+ logic.actions.setProjectId(42)
+ logic.actions.approve()
+ await expectLogic(logic).toFinishAllListeners()
+
+ expect(approvals).toEqual([{ user_code: 'BCDF-GHJK', project_id: 42 }])
+ await expectLogic(logic).toMatchValues({ decision: 'authorized' })
+ })
+
+ it('goes back to code entry when the code expired during review', async () => {
+ useMocks({
+ post: {
+ '/api/oauth_device/lookup/': () => [200, GRANT],
+ '/api/oauth_device/approve/': () => [
+ 400,
+ { error: 'invalid_code', error_description: 'This code is wrong, expired or already used.' },
+ ],
+ },
+ })
+ const logic = oauthDeviceAuthorizeLogic()
+ logic.mount()
+ router.actions.push(urls.oauthDeviceAuthorize(), { code: 'bcdf-ghjk' })
+ await expectLogic(logic).toFinishAllListeners()
+
+ logic.actions.setProjectId(42)
+ logic.actions.approve()
+ await expectLogic(logic).toFinishAllListeners()
+
+ await expectLogic(logic).toMatchValues({
+ deviceGrant: null,
+ error: 'This code is wrong, expired or already used.',
+ })
+ })
+})
diff --git a/frontend/src/scenes/authentication/device/oauthDeviceAuthorizeLogic.ts b/frontend/src/scenes/authentication/device/oauthDeviceAuthorizeLogic.ts
new file mode 100644
index 000000000000..a56081d95728
--- /dev/null
+++ b/frontend/src/scenes/authentication/device/oauthDeviceAuthorizeLogic.ts
@@ -0,0 +1,340 @@
+import { MakeLogicType, actions, afterMount, connect, kea, listeners, path, reducers, selectors } from 'kea'
+import { loaders } from 'kea-loaders'
+import { urlToAction } from 'kea-router'
+
+import { ApiError } from 'lib/api-error'
+import { getMinimumEquivalentScopes, getScopeDescription } from 'lib/scopes'
+import { userLogic } from 'scenes/userLogic'
+
+import {
+ oauthDeviceApproveCreate,
+ oauthDeviceDenyCreate,
+ oauthDeviceLookupCreate,
+ organizationsProjectsList,
+} from '~/generated/core/api'
+import type { DeviceDecisionEnumApi, DeviceGrantDetailsApi } from '~/generated/core/api.schemas'
+
+import type { OrganizationBasicType, UserType } from '../../../types'
+
+interface DeviceProject {
+ id: number
+ name: string
+}
+
+function deviceErrorMessage(error: unknown): string {
+ if (error instanceof ApiError) {
+ if (error.status === 429) {
+ return 'Too many attempts. Wait a minute, then try again.'
+ }
+ if (typeof error.data?.error_description === 'string') {
+ return error.data.error_description
+ }
+ if (error.detail) {
+ return error.detail
+ }
+ }
+ return "Couldn't reach PostHog. Check your connection and try again."
+}
+
+// The server's answer for a code that is wrong, expired or already used. Retrying it can't work.
+function isInvalidCode(error: unknown): boolean {
+ return error instanceof ApiError && error.data?.error === 'invalid_code'
+}
+
+// The project picker loads every page, so a project past the first page can still be picked.
+const PROJECTS_PAGE_SIZE = 100
+
+// The scopes a step-up asks for beyond what the person already granted in the chosen project. A
+// grant limited to another project or organization gives nothing here. Approving still grants every
+// requested scope, so the client's token keeps the ones it had.
+function addedScopes(grant: DeviceGrantDetailsApi, projectId: number | null, organizationId: string | null): string[] {
+ const granted = new Set(
+ grant.granted_scopes
+ .filter(
+ (entry) =>
+ (entry.project_id === null || entry.project_id === projectId) &&
+ (entry.organization_id === null || entry.organization_id === organizationId)
+ )
+ .flatMap((entry) => entry.scopes)
+ )
+ return grant.scopes.filter((scope) => !granted.has(scope))
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface oauthDeviceAuthorizeLogicValues {
+ user: UserType | null // userLogic
+ decision: DeviceDecisionEnumApi | null
+ decisionLoading: boolean
+ deviceGrant: DeviceGrantDetailsApi | null
+ deviceGrantLoading: boolean
+ error: string | null
+ isStepUp: boolean
+ organizationId: string | null
+ organizations: OrganizationBasicType[]
+ projectId: number | null
+ projects: DeviceProject[]
+ projectsError: string | null
+ projectsLoading: boolean
+ scopeDescriptions: string[]
+ userCode: string
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface oauthDeviceAuthorizeLogicActions {
+ approve: () => any
+ approveFailure: (
+ error: string,
+ errorObject?: any
+ ) => {
+ error: string
+ errorObject?: any
+ }
+ approveSuccess: (
+ decision: DeviceDecisionEnumApi | null,
+ payload?: any
+ ) => {
+ decision: DeviceDecisionEnumApi | null
+ payload?: any
+ }
+ deny: () => any
+ denyFailure: (
+ error: string,
+ errorObject?: any
+ ) => {
+ error: string
+ errorObject?: any
+ }
+ denySuccess: (
+ decision: DeviceDecisionEnumApi | null,
+ payload?: any
+ ) => {
+ decision: DeviceDecisionEnumApi | null
+ payload?: any
+ }
+ loadProjects: (organizationId: string) => string
+ loadProjectsFailure: (
+ error: string,
+ errorObject?: any
+ ) => {
+ error: string
+ errorObject?: any
+ }
+ loadProjectsSuccess: (
+ projects: DeviceProject[],
+ payload?: string
+ ) => {
+ projects: DeviceProject[]
+ payload?: string
+ }
+ lookUpCode: () => any
+ lookUpCodeFailure: (
+ error: string,
+ errorObject?: any
+ ) => {
+ error: string
+ errorObject?: any
+ }
+ lookUpCodeSuccess: (
+ deviceGrant: DeviceGrantDetailsApi,
+ payload?: any
+ ) => {
+ deviceGrant: DeviceGrantDetailsApi
+ payload?: any
+ }
+ setOrganizationId: (organizationId: string | null) => {
+ organizationId: string | null
+ }
+ setProjectId: (projectId: number | null) => {
+ projectId: number | null
+ }
+ setUserCode: (userCode: string) => {
+ userCode: string
+ }
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface oauthDeviceAuthorizeLogicMeta {
+ __keaTypeGenInternalSelectorTypes: {
+ organizations: (user: UserType | null) => OrganizationBasicType[]
+ isStepUp: (
+ deviceGrant: DeviceGrantDetailsApi | null,
+ projectId: number | null,
+ organizationId: string | null
+ ) => boolean
+ scopeDescriptions: (
+ deviceGrant: DeviceGrantDetailsApi | null,
+ projectId: number | null,
+ organizationId: string | null,
+ isStepUp: boolean
+ ) => string[]
+ }
+}
+
+export type oauthDeviceAuthorizeLogicType = MakeLogicType<
+ oauthDeviceAuthorizeLogicValues,
+ oauthDeviceAuthorizeLogicActions,
+ Record<string, any>,
+ oauthDeviceAuthorizeLogicMeta
+>
+
+export const oauthDeviceAuthorizeLogic = kea<oauthDeviceAuthorizeLogicType>([
+ path(['scenes', 'authentication', 'device', 'oauthDeviceAuthorizeLogic']),
+ connect(() => ({
+ values: [userLogic, ['user']],
+ })),
+ actions({
+ setUserCode: (userCode: string) => ({ userCode }),
+ setOrganizationId: (organizationId: string | null) => ({ organizationId }),
+ setProjectId: (projectId: number | null) => ({ projectId }),
+ }),
+ reducers({
+ userCode: ['', { setUserCode: (_, { userCode }) => userCode.toUpperCase() }],
+ organizationId: [null as string | null, { setOrganizationId: (_, { organizationId }) => organizationId }],
+ projectId: [
+ null as number | null,
+ {
+ setProjectId: (_, { projectId }) => projectId,
+ setOrganizationId: () => null,
+ },
+ ],
+ projectsError: [
+ null as string | null,
+ {
+ loadProjects: () => null,
+ loadProjectsFailure: (_, { errorObject }) => deviceErrorMessage(errorObject),
+ },
+ ],
+ error: [
+ null as string | null,
+ {
+ lookUpCodeFailure: (_, { errorObject }) => deviceErrorMessage(errorObject),
+ approveFailure: (_, { errorObject }) => deviceErrorMessage(errorObject),
+ denyFailure: (_, { errorObject }) => deviceErrorMessage(errorObject),
+ lookUpCode: () => null,
+ approve: () => null,
+ deny: () => null,
+ setUserCode: () => null,
+ },
+ ],
+ }),
+ loaders(({ values }) => ({
+ deviceGrant: [
+ null as DeviceGrantDetailsApi | null,
+ {
+ lookUpCode: async () => await oauthDeviceLookupCreate({ user_code: values.userCode }),
+ },
+ ],
+ projects: [
+ [] as DeviceProject[],
+ {
+ loadProjects: async (organizationId: string, breakpoint) => {
+ const projects: DeviceProject[] = []
+ for (let offset = 0; ; offset += PROJECTS_PAGE_SIZE) {
+ const page = await organizationsProjectsList(organizationId, {
+ limit: PROJECTS_PAGE_SIZE,
+ offset,
+ })
+ // Drops the answer for an organization the person already switched away from.
+ breakpoint()
+ projects.push(...page.results.map(({ id, name }) => ({ id, name })))
+ if (!page.next) {
+ return projects
+ }
+ }
+ },
+ },
+ ],
+ decision: [
+ null as DeviceDecisionEnumApi | null,
+ {
+ approve: async () => {
+ const { deviceGrant, projectId } = values
+ if (!deviceGrant || projectId === null) {
+ return null
+ }
+ return (await oauthDeviceApproveCreate({ user_code: deviceGrant.user_code, project_id: projectId }))
+ .status
+ },
+ deny: async () => {
+ if (!values.deviceGrant) {
+ return null
+ }
+ return (await oauthDeviceDenyCreate({ user_code: values.deviceGrant.user_code })).status
+ },
+ },
+ ],
+ })),
+ reducers({
+ // Another organization, or a failed load, must not leave the previous organization's projects
+ // selectable while the organization picker shows a different one.
+ projects: {
+ setOrganizationId: () => [],
+ loadProjectsFailure: () => [],
+ },
+ // A code that expired during review goes back to code entry, so the person can type the new one.
+ deviceGrant: {
+ approveFailure: (state, { errorObject }) => (isInvalidCode(errorObject) ? null : state),
+ denyFailure: (state, { errorObject }) => (isInvalidCode(errorObject) ? null : state),
+ },
+ }),
+ selectors({
+ organizations: [(s) => [s.user], (user: UserType | null) => user?.organizations ?? []],
+ isStepUp: [
+ (s) => [s.deviceGrant, s.projectId, s.organizationId],
+ // A login that adds nothing, such as logging in again for the same project, lists every scope.
+ (
+ deviceGrant: DeviceGrantDetailsApi | null,
+ projectId: number | null,
+ organizationId: string | null
+ ): boolean => {
+ const added = deviceGrant ? addedScopes(deviceGrant, projectId, organizationId).length : 0
+ return added > 0 && added < (deviceGrant?.scopes.length ?? 0)
+ },
+ ],
+ // The page lists one line per resource, at the highest level asked for.
+ scopeDescriptions: [
+ (s) => [s.deviceGrant, s.projectId, s.organizationId, s.isStepUp],
+ (
+ deviceGrant: DeviceGrantDetailsApi | null,
+ projectId: number | null,
+ organizationId: string | null,
+ isStepUp: boolean
+ ): string[] =>
+ deviceGrant
+ ? getMinimumEquivalentScopes(
+ isStepUp ? addedScopes(deviceGrant, projectId, organizationId) : deviceGrant.scopes
+ )
+ .map(getScopeDescription)
+ .filter((description): description is string => !!description)
+ : [],
+ ],
+ }),
+ listeners(({ actions, values }) => ({
+ setOrganizationId: ({ organizationId }) => {
+ if (organizationId) {
+ actions.loadProjects(organizationId)
+ }
+ },
+ loadProjectsSuccess: ({ projects }) => {
+ const currentProjectId = values.user?.team?.project_id
+ if (values.projectId === null && projects.some((project) => project.id === currentProjectId)) {
+ actions.setProjectId(currentProjectId ?? null)
+ }
+ },
+ })),
+ urlToAction(({ actions, values }) => ({
+ '/device': (_, searchParams) => {
+ const code = typeof searchParams.code === 'string' ? searchParams.code : ''
+ if (code && code.toUpperCase() !== values.userCode) {
+ actions.setUserCode(code)
+ actions.lookUpCode()
+ }
+ },
+ })),
+ afterMount(({ actions, values }) => {
+ const organizationId = values.user?.organization?.id ?? values.user?.organizations?.[0]?.id
+ if (organizationId) {
+ actions.setOrganizationId(organizationId)
+ }
+ }),
+])
diff --git a/frontend/src/scenes/authentication/shared/authScene/authNotes.ts b/frontend/src/scenes/authentication/shared/authScene/authNotes.ts
index 114cc368de03..3efee1d20439 100644
--- a/frontend/src/scenes/authentication/shared/authScene/authNotes.ts
+++ b/frontend/src/scenes/authentication/shared/authScene/authNotes.ts
@@ -11,6 +11,12 @@ export const AUTH_NOTES = {
createAccount: ['create an account', '1M events free, every month'],
signupProfile: ['almost there', 'last step'],
},
+ oauthDevice: {
+ enterCode: ['one code away', 'it is in your terminal'],
+ review: ['check the code', 'then approve'],
+ approved: ['approved', 'back to your terminal'],
+ denied: ['denied', 'nothing was shared'],
+ },
login2fa: {
default: ['one more step', "checking it's really you"],
},
diff --git a/frontend/src/scenes/sceneLogic.tsx b/frontend/src/scenes/sceneLogic.tsx
index e453b953ff68..0581b65488c3 100644
--- a/frontend/src/scenes/sceneLogic.tsx
+++ b/frontend/src/scenes/sceneLogic.tsx
@@ -177,6 +177,8 @@ const pathPrefixesOnboardingNotRequiredFor = [
'/agentic',
// /cli/authorize, /cli/live (CLI auth round-trip).
'/cli',
+ // /device, where a person approves an OAuth device login (urls.oauthDeviceAuthorize).
+ '/device',
// /stamphog/install/callback — GitHub App install round-trip carrying a one-time OAuth code;
// if /onboarding swallows it the installation completes on GitHub but no repos ever connect.
'/stamphog/install/callback',
diff --git a/frontend/src/scenes/sceneTypes.ts b/frontend/src/scenes/sceneTypes.ts
index dfe6d74a4140..3f0997ab211b 100644
--- a/frontend/src/scenes/sceneTypes.ts
+++ b/frontend/src/scenes/sceneTypes.ts
@@ -31,6 +31,7 @@ export enum Scene {
BusinessIntelligence = 'BusinessIntelligence',
Canvas = 'Canvas',
CLIAuthorize = 'CLIAuthorize',
+ OAuthDeviceAuthorize = 'OAuthDeviceAuthorize',
CLILive = 'CLILive',
Cohort = 'Cohort',
CohortCalculationHistory = 'CohortCalculationHistory',
diff --git a/frontend/src/scenes/scenes.ts b/frontend/src/scenes/scenes.ts
index 580d4765ea81..41895e5c63e3 100644
--- a/frontend/src/scenes/scenes.ts
+++ b/frontend/src/scenes/scenes.ts
@@ -106,6 +106,12 @@ export const sceneConfigurations: Record<Scene | string, SceneConfig> = {
organizationBased: false,
layout: 'plain',
},
+ [Scene.OAuthDeviceAuthorize]: {
+ name: 'Approve a login',
+ projectBased: false,
+ organizationBased: false,
+ layout: 'plain',
+ },
[Scene.CLILive]: {
name: 'Authorize Live',
projectBased: false,
@@ -897,6 +903,7 @@ export const routes: Record<string, [Scene | string, string]> = {
[urls.accountConnected(':kind')]: [Scene.AccountConnected, 'accountConnected'],
[urls.credentialReview()]: [Scene.CredentialReview, 'credentialReview'],
[urls.cliAuthorize()]: [Scene.CLIAuthorize, 'cliAuthorize'],
+ [urls.oauthDeviceAuthorize()]: [Scene.OAuthDeviceAuthorize, 'oauthDeviceAuthorize'],
[urls.cliLive()]: [Scene.CLILive, 'cliLive'],
[urls.preflight()]: [Scene.PreflightCheck, 'preflight'],
[urls.signup()]: [Scene.Signup, 'signup'],
diff --git a/frontend/src/scenes/urls.ts b/frontend/src/scenes/urls.ts
index c58eead0b7e1..51b769825c30 100644
--- a/frontend/src/scenes/urls.ts
+++ b/frontend/src/scenes/urls.ts
@@ -234,6 +234,8 @@ export const urls = {
credentialReview: (next?: string): string =>
`/account/credential-review${next ? `?next=${encodeURIComponent(next)}` : ''}`,
cliAuthorize: (): string => '/cli/authorize',
+ // pinned: the OAuth server sends devices here as verification_uri, see posthog/api/oauth/device.py
+ oauthDeviceAuthorize: (): string => '/device',
cliLive: (): string => '/cli/live',
passwordReset: (): string => '/reset',
passwordResetComplete: (userUuid: string, token: string): string => `/reset/${userUuid}/${token}`,
diff --git a/posthog/api/cli_auth.py b/posthog/api/cli_auth.py
index a652f9a0e17f..609b5b682edc 100644
--- a/posthog/api/cli_auth.py
+++ b/posthog/api/cli_auth.py
@@ -1,8 +1,15 @@
"""
-CLI Authentication API using OAuth2 Device Flow
+DEPRECATED: posthog-cli only. Do not add new clients to this flow.
-This implements the device authorization flow (RFC 8628) for the PostHog CLI.
-Users can authenticate without copying/pasting API keys.
+New clients, hog included, log in with the OAuth device authorization grant instead
+(`/oauth/device-authorization`, see `posthog/api/oauth/device.py`). That grant issues
+short-lived OAuth tokens scoped to one project. This flow mints a personal API key that never
+expires, and its codes live in the cache, not in the OAuth server. It stays only while PostHog
+supports the legacy posthog-cli. Remove it by July 1, 2027: move posthog-cli off this flow, or
+stop supporting posthog-cli, before then.
+
+CLI Authentication API, shaped like the device authorization flow (RFC 8628) but not built on
+the OAuth server. Users can authenticate without copying/pasting API keys.
Flow:
1. CLI requests device code
@@ -301,8 +308,8 @@ class CLIAuthViewSet(viewsets.ViewSet):
device_data["authorized_at"] = timezone.now().isoformat()
device_data["user_id"] = user.id
- # An agent can resume `hog auth login --wait` long after the person approves, so the key
- # stays until the code expires.
+ # A client can resume polling long after the person approves, so the key stays until the
+ # code expires.
cache.set(device_cache_key, device_data, timeout=remaining_device_code_seconds(device_data))
return Response(
diff --git a/posthog/api/oauth/cimd.py b/posthog/api/oauth/cimd.py
index 549a14580ea8..1cc114430415 100644
--- a/posthog/api/oauth/cimd.py
+++ b/posthog/api/oauth/cimd.py
@@ -35,6 +35,7 @@ from posthog.models.oauth import (
TokenEndpointAuthMethod,
find_cimd_verification_token,
normalize_cimd_url,
+ revoke_application_sessions,
)
from posthog.ph_client import ph_scoped_capture
from posthog.rate_limit import IPThrottle
@@ -362,6 +363,24 @@ def fetch_client_json_document(
return parsed, response
+def _resolve_grant_type(metadata: CIMDMetadataDocument) -> str:
+ """The one grant type the application row gets, from the document's `grant_types`.
+
+ An application holds a single grant type. `authorization_code` wins whenever the document
+ declares it, and a document without `grant_types` means `authorization_code` (RFC 7591
+ section 2), so every client registered before the device grant keeps its grant. Only a
+ document that declares the device grant without `authorization_code` gets the device grant.
+ """
+ grant_types = metadata.get("grant_types")
+ if (
+ isinstance(grant_types, list)
+ and AbstractApplication.GRANT_DEVICE_CODE in grant_types
+ and "authorization_code" not in grant_types
+ ):
+ return AbstractApplication.GRANT_DEVICE_CODE
+ return AbstractApplication.GRANT_AUTHORIZATION_CODE
+
+
def fetch_cimd_metadata(url: str) -> tuple[CIMDMetadataDocument, int]:
"""
Fetch and validate a CIMD metadata document.
@@ -378,9 +397,11 @@ def fetch_cimd_metadata(url: str) -> tuple[CIMDMetadataDocument, int]:
if metadata.get("client_id") != url:
raise CIMDValidationError("client_id in the metadata document does not match the URL it was fetched from")
- # redirect_uris required
- redirect_uris = metadata.get("redirect_uris")
- if not redirect_uris or not isinstance(redirect_uris, list) or len(redirect_uris) == 0:
+ # A client that only uses the device grant never receives a redirect, so it may leave
+ # redirect_uris out.
+ device_only = _resolve_grant_type(metadata) == AbstractApplication.GRANT_DEVICE_CODE
+ redirect_uris = metadata.get("redirect_uris", [])
+ if not isinstance(redirect_uris, list) or (not redirect_uris and not device_only):
raise CIMDValidationError("Metadata document must contain a non-empty redirect_uris array")
for uri in redirect_uris:
@@ -657,7 +678,7 @@ def _create_cimd_application(
# Escape the partner-controlled name so the stored value is HTML-safe in any sink.
client_name = sanitize_client_name(client_name)
- redirect_uris = " ".join(metadata.get("redirect_uris", []))
+ redirect_uris = " ".join(metadata.get("redirect_uris") or [])
logo_uri = _logo_uri_for(metadata, url)
verification = _resolve_verification_token(metadata, url, capture_ph_event=capture_ph_event)
resolved_scopes = _resolve_scopes(metadata)
@@ -676,7 +697,7 @@ def _create_cimd_application(
client_type=client_type,
jwks_uri=jwks_uri,
client_secret="",
- authorization_grant_type=AbstractApplication.GRANT_AUTHORIZATION_CODE,
+ authorization_grant_type=_resolve_grant_type(metadata),
algorithm="RS256",
skip_authorization=False,
is_cimd_client=True,
@@ -751,7 +772,9 @@ def _update_cimd_application(
except Exception:
pass # Keep existing name if new one is invalid
- app.redirect_uris = " ".join(metadata.get("redirect_uris", []))
+ app.redirect_uris = " ".join(metadata.get("redirect_uris") or [])
+ previous_grant_type = app.authorization_grant_type
+ app.authorization_grant_type = _resolve_grant_type(metadata)
# 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)
@@ -773,6 +796,7 @@ def _update_cimd_application(
update_fields = [
"name",
"redirect_uris",
+ "authorization_grant_type",
"logo_uri",
"cimd_metadata_last_fetched",
"client_type",
@@ -797,7 +821,14 @@ def _update_cimd_application(
try:
app.full_clean()
- app.save(update_fields=update_fields)
+ # One transaction, so a failed cleanup can't leave the new grant type saved while the sessions
+ # issued under the old one stay alive.
+ with transaction.atomic():
+ app.save(update_fields=update_fields)
+ if app.authorization_grant_type != previous_grant_type:
+ # The grant type decides how refresh tokens rotate and how a revoke sweeps them, and
+ # sessions issued under the old rule don't follow the new one. They end here.
+ revoke_application_sessions(app)
except ValidationError as e:
logger.warning("cimd_update_validation_failed", url=app.client_id, error=str(e))
capture_exception(e)
diff --git a/posthog/api/oauth/device.py b/posthog/api/oauth/device.py
index 5770641141e6..ba9093e3317e 100644
--- a/posthog/api/oauth/device.py
+++ b/posthog/api/oauth/device.py
@@ -52,7 +52,7 @@ from posthog.auth import SessionAuthentication
from posthog.helpers.two_factor_session import missing_two_factor_step
from posthog.helpers.verified_domain_enforcement import VERIFIED_DOMAIN_REQUIRED_ERROR
from posthog.models import Team, User
-from posthog.models.oauth import OAuthApplication, OAuthDeviceGrant
+from posthog.models.oauth import OAuthApplication, OAuthDeviceGrant, live_oauth_access_tokens, live_oauth_refresh_tokens
from posthog.models.organization_domain import OrganizationDomain
from posthog.rate_limit import IPThrottle
from posthog.scopes import clamp_scopes_to_ceiling, resolve_requested_scopes
@@ -356,6 +356,19 @@ class DeviceApprovalSerializer(DeviceUserCodeSerializer):
project_id = serializers.IntegerField(help_text="The project the token is scoped to.")
+class GrantedScopesSerializer(serializers.Serializer):
+ project_id = serializers.IntegerField(
+ allow_null=True,
+ help_text="The project these scopes work in. Null when the connection is not limited to projects.",
+ )
+ organization_id = serializers.CharField(
+ allow_null=True,
+ help_text="The organization these scopes work in, for a connection limited to organizations. Null when "
+ "the connection is not limited to organizations.",
+ )
+ scopes = serializers.ListField(child=serializers.CharField(), help_text="The scopes granted in the project.")
+
+
class DeviceGrantDetailsSerializer(serializers.Serializer):
user_code = serializers.CharField(help_text="The code, in the form the device shows it.")
client_id = serializers.CharField(help_text="The client that started the device grant.")
@@ -365,6 +378,11 @@ class DeviceGrantDetailsSerializer(serializers.Serializer):
scopes = serializers.ListField(
child=serializers.CharField(), help_text="The scopes the token will carry if the person approves."
)
+ granted_scopes = GrantedScopesSerializer(
+ many=True,
+ help_text="The scopes the person already gave this client, per project. A step-up in a project asks for "
+ "these plus new ones, and the page lists only the new ones.",
+ )
expires_at = serializers.DateTimeField(help_text="When the code expires.")
@@ -381,7 +399,10 @@ class DeviceDecisionSerializer(serializers.Serializer):
def _invalid_code() -> Response:
return Response(
- {"error": "invalid_code", "error_description": "This code is wrong, expired or already used."},
+ {
+ "error": "invalid_code",
+ "error_description": "This code is wrong, expired or already used. Check the code your terminal shows, or start the login again.",
+ },
status=status.HTTP_400_BAD_REQUEST,
)
@@ -393,6 +414,38 @@ def _unverified_client() -> Response:
)
+def _granted_scopes(user: User, application: OAuthApplication) -> list[dict[str, object]]:
+ """The scopes the user's standing connections to this client carry, per project, counted the way
+ the Connected applications page counts them. A scope granted in one project grants nothing in
+ another, so a step-up only hides scopes the chosen project already has."""
+ rows = [
+ *live_oauth_access_tokens(user)
+ .filter(application=application)
+ .values_list("scope", "scoped_teams", "scoped_organizations"),
+ *live_oauth_refresh_tokens(user)
+ .filter(application=application)
+ .values_list("access_token__scope", "access_token__scoped_teams", "access_token__scoped_organizations"),
+ ]
+ # Keyed by (project, organization). A connection limited to organizations counts only in them, and
+ # only a connection limited to neither counts everywhere.
+ granted: dict[tuple[int | None, str | None], set[str]] = {}
+ for scope, scoped_teams, scoped_organizations in rows:
+ if scoped_teams:
+ places: list[tuple[int | None, str | None]] = [(project_id, None) for project_id in scoped_teams]
+ elif scoped_organizations:
+ places = [(None, organization_id) for organization_id in scoped_organizations]
+ else:
+ places = [(None, None)]
+ for place in places:
+ granted.setdefault(place, set()).update((scope or "").split())
+ return [
+ {"project_id": project_id, "organization_id": organization_id, "scopes": sorted(scopes)}
+ for (project_id, organization_id), scopes in sorted(
+ granted.items(), key=lambda item: (item[0][0] or 0, item[0][1] or "")
+ )
+ ]
+
+
def _capture(request: Request, event: str, grant: OAuthDeviceGrant, **properties: object) -> None:
"""Device approval events share the `oauth_*` client properties, so they line up with
`oauth_token_issued` for the same client."""
@@ -453,6 +506,7 @@ class OAuthDeviceViewSet(viewsets.ViewSet):
"logo_uri": application.logo_uri or None,
"is_verified": application.is_verified,
"scopes": (grant.scope or "").split(),
+ "granted_scopes": _granted_scopes(cast(User, request.user), application),
"expires_at": grant.expires,
}
).data
diff --git a/posthog/api/oauth/test_cimd.py b/posthog/api/oauth/test_cimd.py
index bfd42e8eb9fb..ecee8c1bcd42 100644
--- a/posthog/api/oauth/test_cimd.py
+++ b/posthog/api/oauth/test_cimd.py
@@ -1,19 +1,25 @@
import json
import base64
import hashlib
+from datetime import timedelta
from typing import cast
from urllib.parse import urlencode
import pytest
+import time_machine
from posthog.test.base import APIBaseTest
from unittest.mock import MagicMock, patch
from django.core.cache import cache as real_cache
from django.test import SimpleTestCase
+from django.utils import timezone
from django.utils.html import escape
import requests
+from oauth2_provider.models import AbstractApplication
+from oauth2_provider.settings import oauth2_settings
from parameterized import parameterized
+from rest_framework import status
from posthog.api.oauth.cimd import (
CIMDFetchError,
@@ -33,11 +39,14 @@ from posthog.api.oauth.cimd import (
validate_fetchable_https_url,
)
from posthog.api.oauth.client_name import sanitize_client_name
+from posthog.api.oauth.device import DEVICE_CODE_GRANT_TYPE
from posthog.models import Organization
from posthog.models.oauth import (
+ OAuthAccessToken,
OAuthApplication,
OAuthApplicationAccessLevel,
OAuthGrant,
+ OAuthRefreshToken,
TokenEndpointAuthMethod,
create_cimd_verification_token,
)
@@ -393,6 +402,52 @@ class TestFetchAndUpsertCimdApplication(APIBaseTest):
self.assertIsNone(app.organization)
self.assertIsNone(app.user)
+ @parameterized.expand(
+ [
+ (
+ "a device-only client without redirect_uris",
+ {"grant_types": [DEVICE_CODE_GRANT_TYPE, "refresh_token"], "redirect_uris": None},
+ AbstractApplication.GRANT_DEVICE_CODE,
+ "",
+ ),
+ (
+ "a client declaring both grants",
+ {"grant_types": ["authorization_code", DEVICE_CODE_GRANT_TYPE]},
+ AbstractApplication.GRANT_AUTHORIZATION_CODE,
+ "http://127.0.0.1:3000/callback",
+ ),
+ (
+ "a client without grant_types",
+ {"grant_types": None},
+ AbstractApplication.GRANT_AUTHORIZATION_CODE,
+ "http://127.0.0.1:3000/callback",
+ ),
+ ]
+ )
+ @patch("posthog.api.oauth.cimd.requests.Session.get")
+ def test_derives_the_grant_type_from_grant_types(
+ self, _name, overrides, expected_grant_type, expected_redirect_uris, mock_get, _url_mock
+ ):
+ metadata = _make_metadata(**overrides)
+ for key in [key for key, value in overrides.items() if value is None]:
+ del metadata[key]
+ mock_get.return_value = _mock_response(metadata, headers={})
+
+ app = fetch_and_upsert_cimd_application(VALID_CIMD_URL)
+
+ assert app is not None
+ self.assertEqual(app.authorization_grant_type, expected_grant_type)
+ self.assertEqual(app.redirect_uris, expected_redirect_uris)
+
+ @patch("posthog.api.oauth.cimd.requests.Session.get")
+ def test_an_authorization_code_client_still_needs_redirect_uris(self, mock_get, _url_mock):
+ metadata = _make_metadata(grant_types=["authorization_code", DEVICE_CODE_GRANT_TYPE])
+ del metadata["redirect_uris"]
+ mock_get.return_value = _mock_response(metadata, headers={})
+
+ with self.assertRaises(CIMDValidationError):
+ fetch_and_upsert_cimd_application(VALID_CIMD_URL)
+
@parameterized.expand(
[
# A registered partner publishing a key set is the upgrade path with no
@@ -659,6 +714,25 @@ class TestGetOrCreateCimdApplication(APIBaseTest):
with self.assertRaises(CIMDFetchError):
get_or_create_cimd_application(VALID_CIMD_URL)
+ @time_machine.travel("2026-03-02 10:00:00", tick=False)
+ @patch("posthog.api.oauth.cimd.requests.Session.get")
+ def test_a_grant_type_change_ends_the_clients_sessions(self, mock_get, _url_mock):
+ mock_get.return_value = _mock_response(_make_metadata(), headers={})
+ app = fetch_and_upsert_cimd_application(VALID_CIMD_URL)
+ assert app is not None
+ OAuthAccessToken.objects.create(
+ user=self.user, application=app, token="pha_before", expires=timezone.now() + timedelta(days=1)
+ )
+ device_only = _make_metadata(grant_types=[DEVICE_CODE_GRANT_TYPE, "refresh_token"])
+ del device_only["redirect_uris"]
+ mock_get.return_value = _mock_response(device_only, headers={})
+
+ refresh_cimd_metadata_task(VALID_CIMD_URL)
+
+ app.refresh_from_db()
+ self.assertEqual(app.authorization_grant_type, AbstractApplication.GRANT_DEVICE_CODE)
+ self.assertFalse(OAuthAccessToken.objects.filter(token="pha_before").exists())
+
@patch("posthog.api.oauth.cimd.requests.Session.get")
def test_refresh_task_updates_metadata(self, mock_get, _url_mock):
metadata1 = _make_metadata(client_name="Original Name")
@@ -1196,6 +1270,92 @@ class TestCIMDVerificationRejectedCaptureEvent(APIBaseTest):
self.assertEqual(rejected[0].kwargs["properties"]["reason"], "app_url_missing")
+@mock_anti_ssrf_dns_lookup()
+class TestCIMDDeviceIntegration(APIBaseTest):
+ FORM = "application/x-www-form-urlencoded"
+
+ def _register_and_verify(self) -> None:
+ body = urlencode({"client_id": VALID_CIMD_URL, "scope": "insight:read"})
+ refused = self.client.post("/oauth/device-authorization/", body, content_type=self.FORM)
+ self.assertEqual(refused.json()["error"], "unauthorized_client", refused.content)
+ OAuthApplication.objects.filter(client_id=VALID_CIMD_URL).update(is_verified=True)
+
+ def _device_login(self, clock: time_machine.Traveller) -> dict:
+ started = self.client.post(
+ "/oauth/device-authorization/",
+ urlencode({"client_id": VALID_CIMD_URL, "scope": "insight:read"}),
+ content_type=self.FORM,
+ )
+ self.assertEqual(started.status_code, status.HTTP_200_OK, started.content)
+ approved = self.client.post(
+ "/api/oauth_device/approve/", {"user_code": started.json()["user_code"], "project_id": self.team.id}
+ )
+ self.assertEqual(approved.status_code, status.HTTP_200_OK, approved.content)
+
+ clock.shift(timedelta(seconds=6))
+ token = self.client.post(
+ "/oauth/token/",
+ urlencode(
+ {
+ "grant_type": DEVICE_CODE_GRANT_TYPE,
+ "device_code": started.json()["device_code"],
+ "client_id": VALID_CIMD_URL,
+ }
+ ),
+ content_type=self.FORM,
+ )
+ self.assertEqual(token.status_code, status.HTTP_200_OK, token.content)
+ return token.json()
+
+ def _refresh(self, refresh_token: str) -> dict:
+ body = {"grant_type": "refresh_token", "refresh_token": refresh_token, "client_id": VALID_CIMD_URL}
+ response = self.client.post("/oauth/token/", urlencode(body), content_type=self.FORM)
+ self.assertEqual(response.status_code, status.HTTP_200_OK, response.content)
+ return response.json()
+
+ @patch("posthog.api.oauth.cimd.requests.Session.get")
+ def test_a_device_only_cimd_client_logs_in_with_the_device_grant(self, mock_get, _url_mock):
+ metadata = _make_metadata(grant_types=[DEVICE_CODE_GRANT_TYPE, "refresh_token"])
+ del metadata["redirect_uris"]
+ mock_get.return_value = _mock_response(metadata)
+ self._register_and_verify()
+
+ with time_machine.travel("2026-03-02 10:00:00", tick=False) as clock:
+ token = self._device_login(clock)
+
+ self.assertEqual(token["scope"], "insight:read")
+ self.assertEqual(token["scoped_teams"], [self.team.id])
+ self.assertEqual(token["expires_in"], oauth2_settings.ACCESS_TOKEN_EXPIRE_SECONDS)
+
+ @parameterized.expand([("the current refresh token", "current"), ("the refresh token it replaced", "rotated")])
+ @patch("posthog.api.oauth.cimd.requests.Session.get")
+ def test_revoking_one_device_login_leaves_the_others(self, _name, revoked_token, mock_get, _url_mock):
+ metadata = _make_metadata(grant_types=[DEVICE_CODE_GRANT_TYPE, "refresh_token"])
+ del metadata["redirect_uris"]
+ mock_get.return_value = _mock_response(metadata)
+ self._register_and_verify()
+
+ with time_machine.travel("2026-03-02 10:00:00", tick=False) as clock:
+ laptop = self._device_login(clock)
+ desktop = self._device_login(clock)
+ refreshed = self._refresh(laptop["refresh_token"])
+ self.assertNotEqual(refreshed["refresh_token"], laptop["refresh_token"])
+
+ # A token rotated away still refreshes during the grace period, so revoking it ends the login too.
+ token = refreshed["refresh_token"] if revoked_token == "current" else laptop["refresh_token"]
+ revoke_body = {"token": token, "client_id": VALID_CIMD_URL}
+ revoked = self.client.post("/oauth/revoke/", urlencode(revoke_body), content_type=self.FORM)
+
+ self.assertEqual(revoked.status_code, status.HTTP_200_OK, revoked.content)
+ laptop_tokens = [laptop["access_token"], refreshed["access_token"]]
+ self.assertFalse(OAuthAccessToken.objects.filter(token__in=laptop_tokens).exists())
+ self.assertFalse(
+ OAuthRefreshToken.objects.filter(token__in=[laptop["refresh_token"], refreshed["refresh_token"]]).exists()
+ )
+ self.assertTrue(OAuthAccessToken.objects.filter(token=desktop["access_token"]).exists())
+ self.assertTrue(OAuthRefreshToken.objects.filter(token=desktop["refresh_token"], revoked=None).exists())
+
+
@mock_anti_ssrf_dns_lookup()
class TestCIMDAuthorizeIntegration(APIBaseTest):
"""Integration tests for the CIMD flow through /oauth/authorize/."""
diff --git a/posthog/api/oauth/test_device.py b/posthog/api/oauth/test_device.py
index 951d67ea2479..bece53b19618 100644
--- a/posthog/api/oauth/test_device.py
+++ b/posthog/api/oauth/test_device.py
@@ -19,7 +19,13 @@ from rest_framework import status
from posthog.api.oauth.client_assertion import CLIENT_ASSERTION_TYPE_JWT_BEARER
from posthog.api.oauth.device import DEVICE_CODE_GRANT_TYPE
from posthog.models import Organization, Team
-from posthog.models.oauth import OAuthAccessToken, OAuthApplication, OAuthDeviceGrant, revoke_oauth_session
+from posthog.models.oauth import (
+ OAuthAccessToken,
+ OAuthApplication,
+ OAuthDeviceGrant,
+ OAuthRefreshToken,
+ revoke_oauth_session,
+)
FORM = "application/x-www-form-urlencoded"
START = "2026-03-02 10:00:00"
@@ -89,6 +95,43 @@ class TestOAuthDeviceGrant(APIBaseTest):
clock.shift(timedelta(seconds=6))
self.assertEqual(self._poll(started["device_code"]).json()["error"], "invalid_grant")
+ @parameterized.expand(
+ [
+ ("a live token", 1, None, ["insight:read", "openid"]),
+ ("an expired token with a live refresh token", -1, False, ["insight:read", "openid"]),
+ ("an expired token whose refresh token was revoked", -1, True, []),
+ ]
+ )
+ @time_machine.travel(START, tick=False)
+ def test_lookup_lists_the_scopes_the_person_already_granted(
+ self, _name: str, expires_in_hours: int, refresh_revoked: bool | None, expected: list[str]
+ ) -> None:
+ access_token = OAuthAccessToken.objects.create(
+ user=self.user,
+ application=self.device_app,
+ token="existing-token",
+ scope="openid insight:read",
+ expires=timezone.now() + timedelta(hours=expires_in_hours),
+ scoped_teams=[self.team.id],
+ )
+ if refresh_revoked is not None:
+ OAuthRefreshToken.objects.create(
+ user=self.user,
+ application=self.device_app,
+ token="existing-refresh",
+ access_token=access_token,
+ revoked=timezone.now() if refresh_revoked else None,
+ )
+ started = self._start()
+
+ lookup = self.client.post("/api/oauth_device/lookup/", {"user_code": started["user_code"]})
+
+ # Scopes are listed per project, because a grant in one project grants nothing in another.
+ self.assertEqual(
+ lookup.json()["granted_scopes"],
+ [{"project_id": self.team.id, "organization_id": None, "scopes": expected}] if expected else [],
+ )
+
@parameterized.expand(
[
("pending", 6, None, "authorization_pending", False),
diff --git a/posthog/api/oauth/views.py b/posthog/api/oauth/views.py
index 6dc84db81e16..373f039fe7cd 100644
--- a/posthog/api/oauth/views.py
+++ b/posthog/api/oauth/views.py
@@ -92,6 +92,7 @@ from posthog.models.oauth import (
OAuthGrant,
OAuthRefreshToken,
lock_oauth_connection,
+ revoke_oauth_refresh_family,
revoke_oauth_session,
revoke_oauth_token_family,
)
@@ -515,6 +516,10 @@ class OAuthValidator(OAuth2Validator):
return getattr(request.client, "is_dcr_client", False) or getattr(request.client, "is_cimd_client", False)
return False
+ def _is_device_client(self, request) -> bool:
+ client = getattr(request, "client", None)
+ return getattr(client, "authorization_grant_type", None) == DEVICE_CODE_GRANT_TYPE
+
def _is_first_party_client(self, request) -> bool:
"""Check if the client is a first-party PostHog application."""
if hasattr(request, "client") and request.client:
@@ -919,9 +924,12 @@ class OAuthValidator(OAuth2Validator):
behavior of Google, Apple, Okta (for native apps), and AWS Cognito which
all issue non-rotating refresh tokens.
- Non-dynamic OAuth clients still get rotation per the default setting.
+ Non-dynamic OAuth clients still get rotation per the default setting, and so do
+ device-grant clients: they are command-line tools built to store each rotated token.
+ Rotation links every access token to its refresh token's family, which lets an RFC 7009
+ revoke end one login of a device client instead of all of them.
"""
- if self._is_dynamic_client(request):
+ if self._is_dynamic_client(request) and not self._is_device_client(request):
return False
return oauth2_settings.ROTATE_REFRESH_TOKEN
@@ -931,13 +939,17 @@ class OAuthValidator(OAuth2Validator):
Dynamically registered (DCR/CIMD) clients get an extended TTL since they
don't reliably refresh; first-party PostHog apps get the same extended TTL.
+ Device grant clients keep the default TTL: they often run on shared or headless
+ machines, and they refresh like any other client.
Impersonation-minted tokens are capped to the impersonation idle timeout so
they can't outlive the admin's session. That check comes first so an
impersonated first-party app can't inherit the longer window.
"""
if self._get_impersonator_id(request) is not None:
return settings.IMPERSONATION_IDLE_TIMEOUT_SECONDS
- if self._is_dynamic_client(request) or self._is_first_party_client(request):
+ if self._is_first_party_client(request) or (
+ self._is_dynamic_client(request) and not self._is_device_client(request)
+ ):
return EXTENDED_ACCESS_TOKEN_EXPIRE_SECONDS
return oauth2_settings.ACCESS_TOKEN_EXPIRE_SECONDS
@@ -1132,6 +1144,13 @@ class OAuthValidator(OAuth2Validator):
token_type="refresh_token" if rt else "access_token",
)
return
+ # A rotating family holds every access token of one login, so revoking it ends only that
+ # login. A token already rotated away still ends its family: during the grace period it can
+ # still refresh.
+ if rt and self._is_dynamic_client(request) and self.rotate_refresh_token(request):
+ revoke_oauth_refresh_family(rt)
+ return
+ # A non-rotating token can't be traced to its access tokens, so the whole connection goes.
if rt and rt.revoked is None and self._is_dynamic_client(request):
revoke_oauth_session(refresh_token=rt)
return
diff --git a/posthog/management/commands/setup_posthog_cimd_apps.py b/posthog/management/commands/setup_posthog_cimd_apps.py
new file mode 100644
index 000000000000..8a87e9daf431
--- /dev/null
+++ b/posthog/management/commands/setup_posthog_cimd_apps.py
@@ -0,0 +1,91 @@
+from typing import cast
+
+from django.conf import settings
+from django.core.management.base import BaseCommand
+
+from posthog.api.oauth.cimd import CIMDMetadataDocument, _create_cimd_application
+from posthog.models import OAuthApplication
+
+# The client metadata documents PostHog publishes from PostHog/posthog.com
+# (static/.well-known/oauth/<app>/client-metadata.json). A local stack can't count on reaching
+# posthog.com, so the seed creates each app from this copy. The first real use refreshes it from
+# the published document.
+POSTHOG_CIMD_DOCUMENTS: list[dict[str, object]] = [
+ {
+ "client_id": "https://posthog.com/.well-known/oauth/hog/client-metadata.json",
+ "client_name": "hog CLI for PostHog",
+ "logo_uri": "https://posthog.com/.well-known/oauth/hog/logo.png",
+ "grant_types": ["urn:ietf:params:oauth:grant-type:device_code", "refresh_token"],
+ "token_endpoint_auth_method": "none",
+ },
+ {
+ "client_id": "https://posthog.com/.well-known/oauth/hogli/client-metadata.json",
+ "client_name": "hogli CLI for PostHog",
+ "logo_uri": "https://posthog.com/.well-known/oauth/hogli/logo.png",
+ "redirect_uris": ["http://127.0.0.1/callback"],
+ "grant_types": ["authorization_code", "refresh_token"],
+ "response_types": ["code"],
+ "token_endpoint_auth_method": "none",
+ "com.posthog": {"scopes": ["engineering_analytics:read"]},
+ },
+ {
+ "client_id": "https://posthog.com/.well-known/oauth/webmcp/client-metadata.json",
+ "client_name": "PostHog WebMCP",
+ "logo_uri": "https://posthog.com/.well-known/oauth/webmcp/logo.png",
+ "redirect_uris": ["https://us.posthog.com/webmcp/callback", "https://eu.posthog.com/webmcp/callback"],
+ "grant_types": ["authorization_code"],
+ "response_types": ["code"],
+ "token_endpoint_auth_method": "none",
+ },
+ {
+ "client_id": "https://posthog.com/.well-known/oauth/visual-review/client-metadata.json",
+ "client_name": "PostHog Visual Review for GitHub",
+ "client_uri": "https://github.com/PostHog/visual-review-extension",
+ "logo_uri": "https://posthog.com/.well-known/oauth/visual-review/logo.png",
+ "redirect_uris": ["https://coegljbgaffjilmoampifafjigkdmjaf.chromiumapp.org/"],
+ "grant_types": ["authorization_code", "refresh_token"],
+ "response_types": ["code"],
+ "token_endpoint_auth_method": "none",
+ "com.posthog": {"scopes": ["visual_review:read", "user:read", "project:read", "organization:read"]},
+ },
+ {
+ "client_id": "https://posthog.com/.well-known/oauth/desktop-announcements-admin/client-metadata.json",
+ "client_name": "PostHog Desktop Announcements Admin",
+ "client_uri": "https://desktop-announcements-admin.hosthog.dev/",
+ "logo_uri": "https://posthog.com/.well-known/oauth/desktop-announcements-admin/logo.png",
+ "redirect_uris": ["https://desktop-announcements-admin.hosthog.dev/oauth/callback"],
+ "grant_types": ["authorization_code"],
+ "response_types": ["code"],
+ "token_endpoint_auth_method": "none",
+ "com.posthog": {"scopes": ["feature_flag:read", "feature_flag:write", "user:read"]},
+ },
+]
+
+
+class Command(BaseCommand):
+ help = "Create PostHog's own CIMD client applications, verified, for a local stack"
+
+ def handle(self, *args, **options):
+ # Verifying an app is a staff decision everywhere else, so only a local stack does it here.
+ site_url = settings.SITE_URL or ""
+ if (
+ not settings.DEBUG
+ or settings.CLOUD_DEPLOYMENT
+ or not ("//localhost" in site_url or "//127.0.0.1" in site_url)
+ ):
+ self.stdout.write("Skipping PostHog CIMD app setup; it only runs on a local stack")
+ return
+
+ for document in POSTHOG_CIMD_DOCUMENTS:
+ client_id = str(document["client_id"])
+ app = OAuthApplication.objects.filter(client_id=client_id).first()
+ if app is None:
+ app = _create_cimd_application(
+ client_id, cast(CIMDMetadataDocument, document), capture_ph_event=lambda **_: None
+ )
+ self.stdout.write(self.style.SUCCESS(f"Created CIMD app '{app.name}' ({client_id})"))
+ # A device client works only while it is verified, and staff verify PostHog's own apps.
+ if not app.is_verified:
+ app.is_verified = True
+ app.save(update_fields=["is_verified"])
+ self.stdout.write(self.style.SUCCESS(f"Verified CIMD app '{app.name}'"))
diff --git a/posthog/management/commands/test/test_setup_posthog_cimd_apps.py b/posthog/management/commands/test/test_setup_posthog_cimd_apps.py
new file mode 100644
index 000000000000..bcf446cb23a4
--- /dev/null
+++ b/posthog/management/commands/test/test_setup_posthog_cimd_apps.py
@@ -0,0 +1,43 @@
+from io import StringIO
+
+from django.core.management import call_command
+from django.test import TestCase, override_settings
+
+from parameterized import parameterized
+
+from posthog.management.commands.setup_posthog_cimd_apps import POSTHOG_CIMD_DOCUMENTS
+from posthog.models import OAuthApplication
+
+HOG_CLIENT_ID = "https://posthog.com/.well-known/oauth/hog/client-metadata.json"
+CLIENT_IDS = sorted(str(document["client_id"]) for document in POSTHOG_CIMD_DOCUMENTS)
+
+
+LOCAL = {"DEBUG": True, "CLOUD_DEPLOYMENT": None, "SITE_URL": "http://localhost:8010"}
+
+
+class TestSetupPostHogCIMDApps(TestCase):
+ @override_settings(**LOCAL)
+ def test_every_posthog_cimd_app_is_created_verified_and_a_rerun_verifies_an_existing_one(self) -> None:
+ call_command("setup_posthog_cimd_apps", stdout=StringIO())
+ OAuthApplication.objects.filter(client_id=HOG_CLIENT_ID).update(is_verified=False)
+
+ call_command("setup_posthog_cimd_apps", stdout=StringIO())
+
+ apps = OAuthApplication.objects.filter(client_id__in=CLIENT_IDS).order_by("client_id")
+ self.assertEqual([app.client_id for app in apps], CLIENT_IDS)
+ self.assertTrue(all(app.is_verified and app.is_cimd_client for app in apps))
+ hog = apps.get(client_id=HOG_CLIENT_ID)
+ self.assertEqual(hog.authorization_grant_type, OAuthApplication.GRANT_DEVICE_CODE)
+
+ @parameterized.expand(
+ [
+ ("without DEBUG", {**LOCAL, "DEBUG": False}),
+ ("in a cloud region", {**LOCAL, "CLOUD_DEPLOYMENT": "US"}),
+ ("on a public site URL", {**LOCAL, "SITE_URL": "https://posthog.example.com"}),
+ ]
+ )
+ def test_anything_but_a_local_stack_is_left_alone(self, _name: str, overrides: dict) -> None:
+ with override_settings(**overrides):
+ call_command("setup_posthog_cimd_apps", stdout=StringIO())
+
+ self.assertFalse(OAuthApplication.objects.filter(client_id__in=CLIENT_IDS).exists())
diff --git a/posthog/models/oauth.py b/posthog/models/oauth.py
index 661e608dc7c5..b4e28eb3e0ed 100644
--- a/posthog/models/oauth.py
+++ b/posthog/models/oauth.py
@@ -924,6 +924,33 @@ def revoke_oauth_session(
OAuthAccessToken.objects.filter(user=user, application=application).delete()
+def revoke_oauth_refresh_family(refresh_token: OAuthRefreshToken) -> None:
+ """End one login: delete every refresh token in the token's rotation family, and the access
+ tokens they issued.
+
+ Use this for an RFC 7009 revoke from a client that rotates refresh tokens. Rotation links each
+ access token to a refresh token of its family, so the user's other logins with the same client
+ keep working. Rows are deleted, not marked revoked, for the reason `revoke_oauth_session`
+ gives. A token without a family or a user falls back to `revoke_oauth_session`."""
+ if refresh_token.token_family is None or refresh_token.user_id is None:
+ revoke_oauth_session(refresh_token=refresh_token)
+ return
+ with transaction.atomic():
+ lock_oauth_connection(user_id=refresh_token.user_id, application_id=refresh_token.application_id)
+ family = OAuthRefreshToken.objects.filter(token_family=refresh_token.token_family)
+ family_rows = list(family.values_list("pk", "access_token_id"))
+ # Two indexed lookups rather than one OR across a join, which can't use either index.
+ access_token_ids = {access_token_id for _, access_token_id in family_rows if access_token_id}
+ access_token_ids.update(
+ OAuthAccessToken.objects.filter(source_refresh_token_id__in=[pk for pk, _ in family_rows]).values_list(
+ "pk", flat=True
+ )
+ )
+ # Refresh tokens go first, so a failure part way can't leave one able to mint a new access token.
+ family.delete()
+ OAuthAccessToken.objects.filter(pk__in=access_token_ids).delete()
+
+
def revoke_oauth_token_family(refresh_token: OAuthRefreshToken) -> None:
"""Revoke every live member of a refresh token's family in a constant number of
queries, and delete the access tokens still linked to them.
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 673208bc2d2e..801e6d2b3c41 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -34960,6 +34960,21 @@ export namespace Schemas {
status: DeviceDecisionEnum;
}
+ export interface GrantedScopes {
+ /**
+ * The project these scopes work in. Null when the connection is not limited to projects.
+ * @nullable
+ */
+ project_id: number | null;
+ /**
+ * The organization these scopes work in, for a connection limited to organizations. Null when the connection is not limited to organizations.
+ * @nullable
+ */
+ organization_id: string | null;
+ /** The scopes granted in the project. */
+ scopes: string[];
+ }
+
export interface DeviceGrantDetails {
/** The code, in the form the device shows it. */
user_code: string;
@@ -34976,6 +34991,8 @@ export namespace Schemas {
is_verified: boolean;
/** The scopes the token will carry if the person approves. */
scopes: string[];
+ /** The scopes the person already gave this client, per project. A step-up in a project asks for these plus new ones, and the page lists only the new ones. */
+ granted_scopes: GrantedScopes[];
/** When the code expires. */
expires_at: string;
}
diff --git a/services/mcp/src/tools/links/app-url-manifest.json b/services/mcp/src/tools/links/app-url-manifest.json
index 581943842caf..7797f3bf7d0b 100644
--- a/services/mcp/src/tools/links/app-url-manifest.json
+++ b/services/mcp/src/tools/links/app-url-manifest.json
@@ -1319,6 +1319,11 @@
"params": [],
"scope": "global"
},
+ "oauthDeviceAuthorize": {
+ "template": "/device",
+ "params": [],
+ "scope": "global"
+ },
"onboarding": {
"template": "/onboarding",
"params": [],
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/generate-app-url.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/generate-app-url.json
index 285efc0e5c10..98b91f991dcb 100644
--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/generate-app-url.json
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/generate-app-url.json
@@ -13,7 +13,7 @@
"type": "object"
},
"url": {
- "description": "A path template copied verbatim from the catalog below (e.g. `/persons/{uuid}`). Its `{placeholders}` are filled from `params`. These slugs come from PostHog's canonical route table, so they are always correct — never pass a path that is not in this list.\n\n/account-connected/{kind}\n/account/credential-review\n/account/social-connected\n/activity-logs\n/activity/{tab}\n/agentic/account-mismatch\n/agentic/authorize\n/ai\n/ai-enrichment\n/ai-evals/evaluations\n/ai-evals/evaluations/offline/datasets/{id}\n/ai-evals/evaluations/offline/experiments\n/ai-evals/evaluations/offline/experiments/{experimentId}\n/ai-evals/evaluations/offline/experiments?tab=datasets\n/ai-evals/evaluations/scorers\n/ai-evals/evaluations/scorers/{scorerId}\n/ai-evals/evaluations/scorers/{scorerId}/offline\n/ai-evals/evaluations/templates\n/ai-evals/evaluations/{id}\n/ai-evals/taggers\n/ai-evals/taggers/{id}\n/ai-observability/clusters\n/ai-observability/clusters/{runId}/{clusterId}\n/ai-observability/dashboard\n/ai-observability/errors\n/ai-observability/generations\n/ai-observability/playground\n/ai-observability/reviews\n/ai-observability/self-driving\n/ai-observability/sentiment\n/ai-observability/sessions\n/ai-observability/sessions/{id}\n/ai-observability/tools\n/ai-observability/traces\n/ai-observability/traces/{id}\n/ai-observability/users\n/ai/history\n/alerts\n/analytics\n/analytics/all\n/analytics/mine\n/analytics/product-analytics\n/analytics/spaces\n/application-observability\n/approvals/{id}\n/autoresearch\n/autoresearch/new\n/autoresearch/{id}\n/bi\n/bi/new\n/bi/{insightShortId}\n/billing/authorization_status\n/broadcasts\n/broadcasts/library/templates/{id}\n/broadcasts/new\n/broadcasts/{id}\n/business-knowledge\n/business-knowledge/playground\n/business-knowledge/settings\n/business-knowledge/{id}\n/canvas\n/canvases\n/canvases/new\n/canvases/{id}\n/cli/authorize\n/cli/live\n/code-review\n/code/canvas/{channelId}/{dashboardId}\n/code/channel/{channelId}\n/code/loop/{loopId}\n/code/task/{taskId}\n/cohorts\n/cohorts/{id}\n/cohorts/{id}/calculation-history\n/connect/vercel/link\n/coupons/{campaign}\n/create-organization\n/cross-project-dashboards\n/cross-project-dashboards/{id}\n/customer_analytics\n/customer_analytics/accounts\n/customer_analytics/accounts/by-external-id/{externalId}\n/customer_analytics/accounts/{accountId}\n/customer_analytics/announcements\n/customer_analytics/configuration\n/customer_analytics/dashboard\n/customer_analytics/feature-requests\n/customer_analytics/feed\n/customer_analytics/journeys\n/customer_analytics/journeys/new\n/customer_analytics/journeys/templates\n/customer_analytics/journeys/{id}/edit\n/customer_analytics/notes\n/customer_analytics/tasks\n/dashboard\n/dashboard/templates/{templateId}/copy-to-project\n/dashboard/{id}\n/dashboard/{id}/sharing\n/dashboard/{id}/subscriptions\n/dashboard/{id}/subscriptions/{subscriptionId}\n/dashboard/{id}/tiles/{tileId}\n/data-catalog\n/data-catalog/metrics/{name}\n/data-catalog/new-metric\n/data-management/actions\n/data-management/actions/new\n/data-management/actions/new/\n/data-management/actions/{id}\n/data-management/annotations\n/data-management/annotations/{id}\n/data-management/core-events\n/data-management/database\n/data-management/destinations\n/data-management/event-filtering\n/data-management/events\n/data-management/events/{id}\n/data-management/events/{id}/edit\n/data-management/history\n/data-management/ingestion-warnings\n/data-management/ingestion-warnings-v2\n/data-management/managed-viewsets\n/data-management/materialized-columns\n/data-management/properties\n/data-management/properties/{id}\n/data-management/properties/{id}/edit\n/data-management/revenue\n/data-management/schema\n/data-management/sources\n/data-management/sources/{id}/schemas\n/data-management/sources/{sourceId}/schemas/{schemaId}\n/data-management/transformations\n/data-management/variables\n/data-management/variables/{id}\n/data-management/variables/{id}/edit\n/data-management/warehouse-destinations\n/data-management/warehouse-properties\n/data-ops\n/data-warehouse/connect\n/data-warehouse/new-source\n/debug\n/debug/hog\n/debug/precompute\n/early_access_features\n/early_access_features/{id}\n/embedded/{token}\n/endpoints\n/endpoints/{name}\n/engineering-analytics/authors\n/engineering-analytics/authors/{handle}\n/engineering-analytics/deploys\n/engineering-analytics/overview\n/engineering-analytics/pull-requests\n/engineering-analytics/repos/{repoOwner}/{repoName}/actions/runs/{runId}\n/engineering-analytics/repos/{repoOwner}/{repoName}/actions/workflows/{workflowName}\n/engineering-analytics/repos/{repoOwner}/{repoName}/pull-requests/{number}\n/engineering-analytics/repos/{repoOwner}/{repoName}/pull-requests/{number}/ci-explorer\n/engineering-analytics/teams\n/engineering-analytics/teams/{ownerTeam}\n/engineering-analytics/tests\n/engineering-analytics/workflows\n/error-tracking\n/error-tracking/alerts/new/{templateId}\n/error-tracking/alerts/{id}\n/error-tracking/fingerprint/{fingerprint}\n/error-tracking/{id}\n/etl\n/events/{id}/{timestamp}\n/experiments\n/experiments/shared-metrics\n/experiments/shared-metrics/{id}\n/experiments/staff\n/experiments/{id}\n/exports\n/feature-flags\n/feature-flags/new\n/feature-flags/staff\n/feature-flags/staff/cohorts\n/feature-flags/templates\n/feature-flags/{id}\n/files\n/functions/new/{templateId}\n/functions/{id}\n/games/368hedgehogs\n/games/flappyhog\n/games/shipit\n/groups/{groupTypeIndex}\n/groups/{groupTypeIndex}/new\n/groups/{groupTypeIndex}/{groupKey}\n/health\n/health/alerts\n/health/pipeline-status\n/health/sdk-health\n/health/{category}\n/heatmaps\n/heatmaps/new\n/heatmaps/recording\n/heatmaps/{id}\n/home\n/identity-matching\n/inbox\n/inbox/reports/triage\n/inbox/scout-trials\n/inbox/scouts/findings\n/inbox/scouts/runs\n/inbox/scouts/scratchpad\n/inbox/scouts/{skillName}\n/inbox/{tab}/{reportId}\n/insights\n/insights/new\n/insights/quick-start\n/insights/{id}\n/insights/{id}/edit\n/insights/{id}/sharing\n/insights/{id}/subscriptions\n/insights/{id}/subscriptions/{subscriptionId}\n/insights/{insightShortId}/alerts\n/instance/async_migrations\n/instance/async_migrations/future\n/instance/async_migrations/settings\n/instance/dead_letter_queue\n/instance/kafka_inspector\n/instance/metrics\n/instance/settings\n/instance/staff_users\n/instance/status\n/integrations/slack/{integrationId}/setup\n/integrations/stripe/confirm-install\n/integrations/vercel/link-error\n/integrations/{kind}/callback\n/integrations/{slug}\n/legal\n/legal/new/{type}\n/login\n/login/2fa\n/login/2fa_setup\n/logs\n/logs/alerts/{alertId}/notifications/{hogFunctionId}\n/logs/alerts/{id}\n/logs/drop-rules/new\n/logs/drop-rules/{id}\n/logs/retention-rules/new\n/logs/retention-rules/{id}\n/managed_migrations\n/managed_migrations/new\n/marketing\n/mcp-analytics\n/mcp-analytics/activity\n/mcp-analytics/dashboard\n/mcp-analytics/intent-clustering\n/mcp-analytics/missing-capabilities\n/mcp-analytics/notifications\n/mcp-analytics/sessions\n/mcp-analytics/tool-quality\n/mcp-analytics/tool-quality/{toolName}\n/mcp-registry\n/mcp-servers\n/mcp-servers/agent/{id}\n/mcp-servers/member/{id}\n/mcp-servers/server/{id}\n/mcp-servers/{tab}\n/metrics\n/metrics/dashboard-review\n/models\n/models/{id}\n/move-to-cloud\n/my-tickets\n/notebooks\n/notebooks/widgets/{widgetId}\n/notebooks/{shortId}\n/oauth/authorize\n/onboarding\n/onboarding/simple\n/organization-deactivated\n/organization-pending-deletion\n/organization/billing\n/organization/billing/overview\n/organization/billing/real-time-usage\n/organization/confirm-creation\n/organization/create-project\n/organization/legal\n/organization/startups\n/person/{id}\n/persons\n/persons/{uuid}\n/pipeline/batch-exports/new/{service}\n/pipeline/batch-exports/{id}\n/pipeline/new/\n/pipeline/plugins/{id}\n/platform-alerts\n/platform-alerts/{id}\n/preflight\n/product_tours\n/product_tours/{id}\n/project-pending-deletion\n/prompt-management/prompts\n/prompt-management/prompts/{name}\n/pulse\n/replay-vision\n/replay-vision/new/goal\n/replay-vision/observations/{observationId}\n/replay-vision/{id}/budget\n/replay-vision/{id}/configure\n/replay-vision/{id}/details\n/replay-vision/{id}/goal\n/replay-vision/{id}/overview\n/replay-vision/{id}/triggers\n/replay/file-playback\n/replay/home\n/replay/kiosk\n/replay/playlists/{id}\n/replay/settings\n/replay/{id}\n/reset\n/reset/{userUuid}/{token}\n/reset_2fa/{userUuid}/{token}\n/resource-transfer/{resourceKind}/{resourceId}\n/sessions/{id}\n/settings/environment-approvals\n/settings/organization-authentication/{feature}/{configId}\n/settings/project\n/settings/user-feature-previews\n/shared/{token}\n/shared_dashboard/{shareToken}\n/signup\n/signup/{id}\n/site/{url}\n/skills\n/skills/community\n/skills/{categoryTab}\n/skills/{name}\n/slack-task-context\n/spaces\n/spaces/new\n/spaces/{id}\n/spaces/{id}/canvases\n/spaces/{id}/new\n/spaces/{id}/settings\n/sql\n/stamphog\n/stamphog/digests\n/stamphog/install/callback\n/stamphog/runs\n/startups\n/streamlit-apps\n/streamlit-apps/new\n/streamlit-apps/{id}\n/streamlit-apps/{id}/edit\n/subscriptions\n/subscriptions/new\n/subscriptions/{id}\n/subscriptions/{id}/edit\n/support\n/support/settings\n/support/tickets\n/support/tickets/{ticketId}\n/surveys\n/surveys/form/new\n/surveys/guided/new\n/surveys/{id}\n/tasks\n/tasks/new\n/tasks/{taskId}\n/terminal\n/themes/custom-css\n/toolbar\n/tools\n/tracing\n/tracing/retention-rules/new\n/tracing/retention-rules/{id}\n/transactional\n/transactional/library/templates/{id}\n/transactional/new\n/unsubscribe\n/uptime-monitoring\n/verify_email\n/visual-review\n/visual-review/repos/{repoOwner}/{repoName}/flakiness\n/visual-review/repos/{repoOwner}/{repoName}/runs\n/visual-review/repos/{repoOwner}/{repoName}/runs/{runId}\n/visual-review/repos/{repoOwner}/{repoName}/snapshots\n/visual-review/repos/{repoOwner}/{repoName}/{runType}/snapshots/{identifier}\n/visual-review/runs/{runId}\n/visual-review/settings\n/web\n/web-scripts\n/web-scripts/new\n/web/agents\n/web/bots\n/web/content-autopilot\n/web/health\n/web/live\n/web/marketing\n/web/page-performance\n/web/page-reports\n/web/recap\n/web/session-attribution-explorer\n/web/web-vitals\n/welcome\n/wizard/runs\n/workflows\n/workflows/channels/email/{id}\n/workflows/library/messages/{id}\n/workflows/library/templates/new\n/workflows/library/templates/{id}\n/workflows/new/workflow\n/workflows/{id}/{tab}",
+ "description": "A path template copied verbatim from the catalog below (e.g. `/persons/{uuid}`). Its `{placeholders}` are filled from `params`. These slugs come from PostHog's canonical route table, so they are always correct — never pass a path that is not in this list.\n\n/account-connected/{kind}\n/account/credential-review\n/account/social-connected\n/activity-logs\n/activity/{tab}\n/agentic/account-mismatch\n/agentic/authorize\n/ai\n/ai-enrichment\n/ai-evals/evaluations\n/ai-evals/evaluations/offline/datasets/{id}\n/ai-evals/evaluations/offline/experiments\n/ai-evals/evaluations/offline/experiments/{experimentId}\n/ai-evals/evaluations/offline/experiments?tab=datasets\n/ai-evals/evaluations/scorers\n/ai-evals/evaluations/scorers/{scorerId}\n/ai-evals/evaluations/scorers/{scorerId}/offline\n/ai-evals/evaluations/templates\n/ai-evals/evaluations/{id}\n/ai-evals/taggers\n/ai-evals/taggers/{id}\n/ai-observability/clusters\n/ai-observability/clusters/{runId}/{clusterId}\n/ai-observability/dashboard\n/ai-observability/errors\n/ai-observability/generations\n/ai-observability/playground\n/ai-observability/reviews\n/ai-observability/self-driving\n/ai-observability/sentiment\n/ai-observability/sessions\n/ai-observability/sessions/{id}\n/ai-observability/tools\n/ai-observability/traces\n/ai-observability/traces/{id}\n/ai-observability/users\n/ai/history\n/alerts\n/analytics\n/analytics/all\n/analytics/mine\n/analytics/product-analytics\n/analytics/spaces\n/application-observability\n/approvals/{id}\n/autoresearch\n/autoresearch/new\n/autoresearch/{id}\n/bi\n/bi/new\n/bi/{insightShortId}\n/billing/authorization_status\n/broadcasts\n/broadcasts/library/templates/{id}\n/broadcasts/new\n/broadcasts/{id}\n/business-knowledge\n/business-knowledge/playground\n/business-knowledge/settings\n/business-knowledge/{id}\n/canvas\n/canvases\n/canvases/new\n/canvases/{id}\n/cli/authorize\n/cli/live\n/code-review\n/code/canvas/{channelId}/{dashboardId}\n/code/channel/{channelId}\n/code/loop/{loopId}\n/code/task/{taskId}\n/cohorts\n/cohorts/{id}\n/cohorts/{id}/calculation-history\n/connect/vercel/link\n/coupons/{campaign}\n/create-organization\n/cross-project-dashboards\n/cross-project-dashboards/{id}\n/customer_analytics\n/customer_analytics/accounts\n/customer_analytics/accounts/by-external-id/{externalId}\n/customer_analytics/accounts/{accountId}\n/customer_analytics/announcements\n/customer_analytics/configuration\n/customer_analytics/dashboard\n/customer_analytics/feature-requests\n/customer_analytics/feed\n/customer_analytics/journeys\n/customer_analytics/journeys/new\n/customer_analytics/journeys/templates\n/customer_analytics/journeys/{id}/edit\n/customer_analytics/notes\n/customer_analytics/tasks\n/dashboard\n/dashboard/templates/{templateId}/copy-to-project\n/dashboard/{id}\n/dashboard/{id}/sharing\n/dashboard/{id}/subscriptions\n/dashboard/{id}/subscriptions/{subscriptionId}\n/dashboard/{id}/tiles/{tileId}\n/data-catalog\n/data-catalog/metrics/{name}\n/data-catalog/new-metric\n/data-management/actions\n/data-management/actions/new\n/data-management/actions/new/\n/data-management/actions/{id}\n/data-management/annotations\n/data-management/annotations/{id}\n/data-management/core-events\n/data-management/database\n/data-management/destinations\n/data-management/event-filtering\n/data-management/events\n/data-management/events/{id}\n/data-management/events/{id}/edit\n/data-management/history\n/data-management/ingestion-warnings\n/data-management/ingestion-warnings-v2\n/data-management/managed-viewsets\n/data-management/materialized-columns\n/data-management/properties\n/data-management/properties/{id}\n/data-management/properties/{id}/edit\n/data-management/revenue\n/data-management/schema\n/data-management/sources\n/data-management/sources/{id}/schemas\n/data-management/sources/{sourceId}/schemas/{schemaId}\n/data-management/transformations\n/data-management/variables\n/data-management/variables/{id}\n/data-management/variables/{id}/edit\n/data-management/warehouse-destinations\n/data-management/warehouse-properties\n/data-ops\n/data-warehouse/connect\n/data-warehouse/new-source\n/debug\n/debug/hog\n/debug/precompute\n/device\n/early_access_features\n/early_access_features/{id}\n/embedded/{token}\n/endpoints\n/endpoints/{name}\n/engineering-analytics/authors\n/engineering-analytics/authors/{handle}\n/engineering-analytics/deploys\n/engineering-analytics/overview\n/engineering-analytics/pull-requests\n/engineering-analytics/repos/{repoOwner}/{repoName}/actions/runs/{runId}\n/engineering-analytics/repos/{repoOwner}/{repoName}/actions/workflows/{workflowName}\n/engineering-analytics/repos/{repoOwner}/{repoName}/pull-requests/{number}\n/engineering-analytics/repos/{repoOwner}/{repoName}/pull-requests/{number}/ci-explorer\n/engineering-analytics/teams\n/engineering-analytics/teams/{ownerTeam}\n/engineering-analytics/tests\n/engineering-analytics/workflows\n/error-tracking\n/error-tracking/alerts/new/{templateId}\n/error-tracking/alerts/{id}\n/error-tracking/fingerprint/{fingerprint}\n/error-tracking/{id}\n/etl\n/events/{id}/{timestamp}\n/experiments\n/experiments/shared-metrics\n/experiments/shared-metrics/{id}\n/experiments/staff\n/experiments/{id}\n/exports\n/feature-flags\n/feature-flags/new\n/feature-flags/staff\n/feature-flags/staff/cohorts\n/feature-flags/templates\n/feature-flags/{id}\n/files\n/functions/new/{templateId}\n/functions/{id}\n/games/368hedgehogs\n/games/flappyhog\n/games/shipit\n/groups/{groupTypeIndex}\n/groups/{groupTypeIndex}/new\n/groups/{groupTypeIndex}/{groupKey}\n/health\n/health/alerts\n/health/pipeline-status\n/health/sdk-health\n/health/{category}\n/heatmaps\n/heatmaps/new\n/heatmaps/recording\n/heatmaps/{id}\n/home\n/identity-matching\n/inbox\n/inbox/reports/triage\n/inbox/scout-trials\n/inbox/scouts/findings\n/inbox/scouts/runs\n/inbox/scouts/scratchpad\n/inbox/scouts/{skillName}\n/inbox/{tab}/{reportId}\n/insights\n/insights/new\n/insights/quick-start\n/insights/{id}\n/insights/{id}/edit\n/insights/{id}/sharing\n/insights/{id}/subscriptions\n/insights/{id}/subscriptions/{subscriptionId}\n/insights/{insightShortId}/alerts\n/instance/async_migrations\n/instance/async_migrations/future\n/instance/async_migrations/settings\n/instance/dead_letter_queue\n/instance/kafka_inspector\n/instance/metrics\n/instance/settings\n/instance/staff_users\n/instance/status\n/integrations/slack/{integrationId}/setup\n/integrations/stripe/confirm-install\n/integrations/vercel/link-error\n/integrations/{kind}/callback\n/integrations/{slug}\n/legal\n/legal/new/{type}\n/login\n/login/2fa\n/login/2fa_setup\n/logs\n/logs/alerts/{alertId}/notifications/{hogFunctionId}\n/logs/alerts/{id}\n/logs/drop-rules/new\n/logs/drop-rules/{id}\n/logs/retention-rules/new\n/logs/retention-rules/{id}\n/managed_migrations\n/managed_migrations/new\n/marketing\n/mcp-analytics\n/mcp-analytics/activity\n/mcp-analytics/dashboard\n/mcp-analytics/intent-clustering\n/mcp-analytics/missing-capabilities\n/mcp-analytics/notifications\n/mcp-analytics/sessions\n/mcp-analytics/tool-quality\n/mcp-analytics/tool-quality/{toolName}\n/mcp-registry\n/mcp-servers\n/mcp-servers/agent/{id}\n/mcp-servers/member/{id}\n/mcp-servers/server/{id}\n/mcp-servers/{tab}\n/metrics\n/metrics/dashboard-review\n/models\n/models/{id}\n/move-to-cloud\n/my-tickets\n/notebooks\n/notebooks/widgets/{widgetId}\n/notebooks/{shortId}\n/oauth/authorize\n/onboarding\n/onboarding/simple\n/organization-deactivated\n/organization-pending-deletion\n/organization/billing\n/organization/billing/overview\n/organization/billing/real-time-usage\n/organization/confirm-creation\n/organization/create-project\n/organization/legal\n/organization/startups\n/person/{id}\n/persons\n/persons/{uuid}\n/pipeline/batch-exports/new/{service}\n/pipeline/batch-exports/{id}\n/pipeline/new/\n/pipeline/plugins/{id}\n/platform-alerts\n/platform-alerts/{id}\n/preflight\n/product_tours\n/product_tours/{id}\n/project-pending-deletion\n/prompt-management/prompts\n/prompt-management/prompts/{name}\n/pulse\n/replay-vision\n/replay-vision/new/goal\n/replay-vision/observations/{observationId}\n/replay-vision/{id}/budget\n/replay-vision/{id}/configure\n/replay-vision/{id}/details\n/replay-vision/{id}/goal\n/replay-vision/{id}/overview\n/replay-vision/{id}/triggers\n/replay/file-playback\n/replay/home\n/replay/kiosk\n/replay/playlists/{id}\n/replay/settings\n/replay/{id}\n/reset\n/reset/{userUuid}/{token}\n/reset_2fa/{userUuid}/{token}\n/resource-transfer/{resourceKind}/{resourceId}\n/sessions/{id}\n/settings/environment-approvals\n/settings/organization-authentication/{feature}/{configId}\n/settings/project\n/settings/user-feature-previews\n/shared/{token}\n/shared_dashboard/{shareToken}\n/signup\n/signup/{id}\n/site/{url}\n/skills\n/skills/community\n/skills/{categoryTab}\n/skills/{name}\n/slack-task-context\n/spaces\n/spaces/new\n/spaces/{id}\n/spaces/{id}/canvases\n/spaces/{id}/new\n/spaces/{id}/settings\n/sql\n/stamphog\n/stamphog/digests\n/stamphog/install/callback\n/stamphog/runs\n/startups\n/streamlit-apps\n/streamlit-apps/new\n/streamlit-apps/{id}\n/streamlit-apps/{id}/edit\n/subscriptions\n/subscriptions/new\n/subscriptions/{id}\n/subscriptions/{id}/edit\n/support\n/support/settings\n/support/tickets\n/support/tickets/{ticketId}\n/surveys\n/surveys/form/new\n/surveys/guided/new\n/surveys/{id}\n/tasks\n/tasks/new\n/tasks/{taskId}\n/terminal\n/themes/custom-css\n/toolbar\n/tools\n/tracing\n/tracing/retention-rules/new\n/tracing/retention-rules/{id}\n/transactional\n/transactional/library/templates/{id}\n/transactional/new\n/unsubscribe\n/uptime-monitoring\n/verify_email\n/visual-review\n/visual-review/repos/{repoOwner}/{repoName}/flakiness\n/visual-review/repos/{repoOwner}/{repoName}/runs\n/visual-review/repos/{repoOwner}/{repoName}/runs/{runId}\n/visual-review/repos/{repoOwner}/{repoName}/snapshots\n/visual-review/repos/{repoOwner}/{repoName}/{runType}/snapshots/{identifier}\n/visual-review/runs/{runId}\n/visual-review/settings\n/web\n/web-scripts\n/web-scripts/new\n/web/agents\n/web/bots\n/web/content-autopilot\n/web/health\n/web/live\n/web/marketing\n/web/page-performance\n/web/page-reports\n/web/recap\n/web/session-attribution-explorer\n/web/web-vitals\n/welcome\n/wizard/runs\n/workflows\n/workflows/channels/email/{id}\n/workflows/library/messages/{id}\n/workflows/library/templates/new\n/workflows/library/templates/{id}\n/workflows/new/workflow\n/workflows/{id}/{tab}",
"type": "string"
}
},