: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
fix(oauth): load the consent screen once when the URL ends in a slash (#103524)
posthog[bot]6215dc8eb315
diff --git a/frontend/src/initKea.ts b/frontend/src/initKea.tsindex e7d8418694dc..e776e3a56514 100644--- a/frontend/src/initKea.ts+++ b/frontend/src/initKea.ts@@ -16,6 +16,7 @@ import {ensureRoutablePathname,removeProjectIdIfPresent,stripTrailingSlash,+ stripTrailingSlashFromUrl,} from 'lib/utils/kea-router'import { identifierToHuman } from 'lib/utils/strings'@@ -146,7 +147,11 @@ export function initKea({// Runs before kea-router's `decodeURI(pathname)` on every navigation (initial// load, push/replace, popstate). Keep the path decodable so a malformed `%`// routes to 404 instead of crashing the router.- return addProjectIdIfMissing(ensureRoutablePathname(path))+ // Drop the trailing slash here too, so the router's location matches the path+ // `pathFromWindowToRoutes` matches routes against. The address bar is then+ // corrected by a silent `replaceState` on mount, rather than by a second+ // navigation that runs every `urlToAction` of the scene again.+ return addProjectIdIfMissing(stripTrailingSlashFromUrl(ensureRoutablePathname(path)))},pathFromWindowToRoutes: (path) => {return stripTrailingSlash(removeProjectIdIfPresent(path))diff --git a/frontend/src/lib/utils/kea-router.test.ts b/frontend/src/lib/utils/kea-router.test.tsindex 350bb97e7952..3030b300d1f1 100644--- a/frontend/src/lib/utils/kea-router.test.ts+++ b/frontend/src/lib/utils/kea-router.test.ts@@ -3,6 +3,7 @@ import {ensureRoutablePathname,removeProjectIdIfPresent,stripTrailingSlash,+ stripTrailingSlashFromUrl,} from 'lib/utils/kea-router'describe('router-utils', () => {@@ -108,6 +109,18 @@ describe('router-utils', () => {})})+ describe('stripTrailingSlashFromUrl', () => {+ it.each([+ ['/oauth/authorize/', '/oauth/authorize'],+ ['/oauth/authorize/?client_id=abc', '/oauth/authorize?client_id=abc'],+ ['/login?next=/oauth/authorize/', '/login?next=/oauth/authorize/'],+ ['/insights/abc/#panel=/', '/insights/abc#panel=/'],+ ['/', '/'],+ ])('turns %s into %s', (input, expected) => {+ expect(stripTrailingSlashFromUrl(input)).toEqual(expected)+ })+ })+describe('ensureRoutablePathname', () => {// kea-router runs decodeURI(pathname) while matching; a stray `%` used to throw URIError// and crash routing before any scene loaded. Whatever we return must be decodeURI-safe.diff --git a/frontend/src/lib/utils/kea-router.ts b/frontend/src/lib/utils/kea-router.tsindex 07a8b18ec180..2a1007083c5d 100644--- a/frontend/src/lib/utils/kea-router.ts+++ b/frontend/src/lib/utils/kea-router.ts@@ -124,6 +124,18 @@ export function stripTrailingSlash(path: string): string {return path}+/**+ * Strips the trailing slash of the path only, so a query string or hash that ends in a slash+ * (e.g. `?next=/oauth/authorize/`) survives. Safe on a full URL as well as a bare path.+ */+export function stripTrailingSlashFromUrl(url: string): string {+ const separator = url.search(/[?#]/)+ if (separator === -1) {+ return stripTrailingSlash(url)+ }+ return stripTrailingSlash(url.slice(0, separator)) + url.slice(separator)+}+export function removeFlagIdIfPresent(path: string): string {if (path.match(/^\/feature_flags\/\d+/)) {return path.replace(/(feature_flags).*$/, '$1/')diff --git a/frontend/src/scenes/agentic/agenticAuthorizeLogic.ts b/frontend/src/scenes/agentic/agenticAuthorizeLogic.tsindex dc32b12de24d..5c1aec497fca 100644--- a/frontend/src/scenes/agentic/agenticAuthorizeLogic.ts+++ b/frontend/src/scenes/agentic/agenticAuthorizeLogic.ts@@ -391,7 +391,6 @@ export const agenticAuthorizeLogic = kea<agenticAuthorizeLogicType>([return {'/agentic/authorize': handleAuthorize,- '/agentic/authorize/': handleAuthorize,}}),])diff --git a/frontend/src/scenes/oauth/oauthAuthorizeLogic.ts b/frontend/src/scenes/oauth/oauthAuthorizeLogic.tsindex 7c3b2fabf2e2..f7f91d99115e 100644--- a/frontend/src/scenes/oauth/oauthAuthorizeLogic.ts+++ b/frontend/src/scenes/oauth/oauthAuthorizeLogic.ts@@ -950,7 +950,6 @@ export const oauthAuthorizeLogic = kea<oauthAuthorizeLogicType>([return {'/oauth/authorize': handleAuthorize,- '/oauth/authorize/': handleAuthorize,}}),])diff --git a/frontend/src/scenes/sceneLogic.test.tsx b/frontend/src/scenes/sceneLogic.test.tsxindex d4f7de1f2aef..13f8c688af16 100644--- a/frontend/src/scenes/sceneLogic.test.tsx+++ b/frontend/src/scenes/sceneLogic.test.tsx@@ -2,7 +2,7 @@ import { MOCK_USER_UUID } from 'lib/api.mock'import { kea, path } from 'kea'import { router } from 'kea-router'-import { expectLogic, partial, truth } from 'kea-test-utils'+import { expectLogic, partial, testUtilsContext, truth } from 'kea-test-utils'import api from 'lib/api'import { featureFlagLogic } from 'lib/logic/featureFlagLogic'@@ -89,6 +89,25 @@ describe('sceneLogic', () => {})})+ // A trailing slash used to reach the scene, then get replaced out of the address bar. That+ // second navigation re-ran every `urlToAction` of the scene, so the OAuth consent screen+ // reloaded its data and blanked while the person was reading it.+ it('opens a scene once when the URL carries a trailing slash', async () => {+ router.actions.push(urls.settings('user'))+ await expectLogic(logic).delay(1)++ const from = testUtilsContext().recordedHistory.length+ router.actions.push(`${urls.eventDefinitions()}/`)+ await expectLogic(logic).delay(1)+ const openScenes = testUtilsContext()+ .recordedHistory.slice(from)+ .filter((recorded) => recorded.action.type === logic.actionTypes.openScene)++ expect(openScenes).toHaveLength(1)+ expect(logic.values.activeSceneId).toEqual(Scene.DataManagement)+ expect(removeProjectIdIfPresent(router.values.location.pathname)).toEqual(urls.eventDefinitions())+ })+it('redirects the hyphenated /feature-flags path to the underscore scene route', async () => {router.actions.push('/feature-flags')await expectLogic(logic).delay(1)diff --git a/frontend/src/scenes/sceneLogic.tsx b/frontend/src/scenes/sceneLogic.tsxindex aacfc631efeb..2cc52d5434b1 100644--- a/frontend/src/scenes/sceneLogic.tsx+++ b/frontend/src/scenes/sceneLogic.tsx@@ -13,7 +13,6 @@ import {selectors,} from 'kea'import { combineUrl, router, urlToAction } from 'kea-router'-import type { LocationChangedPayload } from 'kea-router/lib/types'import posthog from 'posthog-js'import { useEffect, useState } from 'react'@@ -24,12 +23,7 @@ import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'import { Spinner } from 'lib/lemon-ui/Spinner'import { getAppContext } from 'lib/utils/getAppContext'import { isChunkLoadError } from 'lib/utils/isChunkLoadError'-import {- addProjectIdIfMissing,- getProjectIdentifierInPath,- removeProjectIdIfPresent,- stripTrailingSlash,-} from 'lib/utils/kea-router'+import { addProjectIdIfMissing, getProjectIdentifierInPath, removeProjectIdIfPresent } from 'lib/utils/kea-router'import { retryImport } from 'lib/utils/retryImport'import { identifierToHuman } from 'lib/utils/strings'import { getRelativeNextPath } from 'lib/utils/url'@@ -270,27 +264,6 @@ export interface sceneLogicActions {hideInviteModal: () => {value: true} // inviteLogic- locationChanged: ({- method,- pathname,- search,- searchParams,- hash,- hashParams,- initial,- url,- routerState,- }: LocationChangedPayload) => {- hash: string- hashParams: Record<string, any>- initial: boolean- method: 'POP' | 'PUSH' | 'REPLACE'- pathname: string- routerState: Record<string, any>- search: string- searchParams: Record<string, any>- url: string- } // routerloadScene: (sceneId: string,sceneKey: string | undefined,@@ -406,7 +379,7 @@ export const sceneLogic = kea<sceneLogicType>([connect(() => ({logic: [router, userLogic, preflightLogic, teamLogic],- actions: [router, ['locationChanged'], inviteLogic, ['hideInviteModal']],+ actions: [inviteLogic, ['hideInviteModal']],values: [billingLogic, ['billing'], organizationLogic, ['organizationBeingDeleted']],})),afterMount(({ cache }) => {@@ -738,17 +711,6 @@ export const sceneLogic = kea<sceneLogicType>([console.error('Failed to persist homepage', error)})},- locationChanged: ({ pathname, search, hash }) => {- pathname = addProjectIdIfMissing(pathname)-- // Remove trailing slash from the address bar. Route matching itself is handled- // upstream via `pathFromWindowToRoutes` in initKea.ts so the scene loads even- // before this replace runs.- const stripped = stripTrailingSlash(pathname)- if (stripped !== pathname) {- router.actions.replace(stripped, search, hash)- }- },setScene: ({ sceneKey, sceneId, exportedScene, params, scrollToTop }, _, __, previousState) => {const {sceneId: lastSceneId,diff --git a/frontend/src/scenes/scenes.ts b/frontend/src/scenes/scenes.tsindex bbadba20d28a..9bbc0306b7cc 100644--- a/frontend/src/scenes/scenes.ts+++ b/frontend/src/scenes/scenes.ts@@ -911,9 +911,7 @@ export const routes: Record<string, [Scene | string, string]> = {[urls.startups()]: [Scene.StartupProgram, 'startupProgram'],[urls.startups(':referrer')]: [Scene.StartupProgram, 'startupProgramWithReferrer'],[urls.agenticAuthorize()]: [Scene.AgenticAuthorize, 'agenticAuthorize'],- [`${urls.agenticAuthorize()}/`]: [Scene.AgenticAuthorize, 'agenticAuthorize'],[urls.oauthAuthorize()]: [Scene.OAuthAuthorize, 'oauthAuthorize'],- [`${urls.oauthAuthorize()}/`]: [Scene.OAuthAuthorize, 'oauthAuthorize'],[urls.dataPipelinesNew(':kind' as any)]: [Scene.DataPipelinesNew, 'dataPipelinesNew'],[urls.batchExportNew(':service')]: [Scene.BatchExportNew, 'batchExportNew'],[urls.batchExport(':id')]: [Scene.BatchExport, 'batchExport'],