: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(frontend): load the app as a new page from a signed-out login page (#124668)
Paul D'Ambrad0f558cac500
diff --git a/frontend/src/lib/utils/url.test.ts b/frontend/src/lib/utils/url.test.tsindex ab678993e931..5286ee882972 100644--- a/frontend/src/lib/utils/url.test.ts+++ b/frontend/src/lib/utils/url.test.ts@@ -182,9 +182,14 @@ describe('url utils', () => {['/\\evil.com/path', '/-then-backslash'],['/\\\\evil.com/path', '/-then-two-backslashes'],['%2F%5Cevil.com%2Fpath', 'encoded /-then-backslash'],- ])('returns null for backslash external bypass (%s — %s)', (input) => {- // Browsers normalize backslashes in special-scheme URLs per WHATWG, so /\\evil.com- // resolves to //evil.com and escapes the origin.+ ['/.//evil.com/path', 'dot segment then //'],+ ['/a/..//evil.com/path', 'parent segment then //'],+ ['/../\\evil.com/path', 'parent segment then backslash'],+ ['%2F.%2F%2Fevil.com%2Fpath', 'encoded dot segment then //'],+ ['https://us.posthog.com/.//evil.com/path', 'same-origin absolute URL with dot segment then //'],+ ])('returns null for a path that normalizes to protocol-relative (%s — %s)', (input) => {+ // Browsers normalize backslashes and dot segments in special-scheme URLs per WHATWG, so+ // each input resolves to //evil.com and escapes the origin.expect(getRelativeNextPath(input, location)).toBeNull()})})diff --git a/frontend/src/lib/utils/url.ts b/frontend/src/lib/utils/url.tsindex 42beffe7b713..271cf53d0a5d 100644--- a/frontend/src/lib/utils/url.ts+++ b/frontend/src/lib/utils/url.ts@@ -212,6 +212,15 @@ export function parseGithubRepoURL(url: string): Record<string, string> {return { user, repo, type, path }}+function pathOf(url: URL): string | null {+ // Dot-segment removal can turn '/.//evil.com' into the pathname '//evil.com', which a browser+ // then loads as a protocol-relative URL on another origin.+ if (url.pathname.startsWith('//')) {+ return null+ }+ return url.pathname + url.search + url.hash+}+function resolveSameOriginPath(candidate: string, location: Location): string | null {// Protocol-relative URLs (e.g., //evil.com/test) are not allowedif (candidate.startsWith('//')) {@@ -227,7 +236,7 @@ function resolveSameOriginPath(candidate: string, location: Location): string |if (url.origin !== location.origin) {return null}- return url.pathname + url.search + url.hash+ return pathOf(url)} catch {return null}@@ -237,7 +246,7 @@ function resolveSameOriginPath(candidate: string, location: Location): string |try {const url = new URL(candidate)if ((url.protocol === 'http:' || url.protocol === 'https:') && url.origin === location.origin) {- return url.pathname + url.search + url.hash+ return pathOf(url)}return null} catch {diff --git a/frontend/src/scenes/authentication/auth/loginLogic.test.ts b/frontend/src/scenes/authentication/auth/loginLogic.test.tsindex 04aa0c8ec968..f87ed131d645 100644--- a/frontend/src/scenes/authentication/auth/loginLogic.test.ts+++ b/frontend/src/scenes/authentication/auth/loginLogic.test.ts@@ -542,12 +542,15 @@ describe('loginLogic', () => {const originalContext = window.POSTHOG_APP_CONTEXTconst originalLocation = window.locationlet hrefSpy: jest.Mock+ let replaceSpy: jest.MockbeforeEach(() => {initKeaTests()// getCurrentTeamIdOrNone() reads the current project from the app context.window.POSTHOG_APP_CONTEXT = { current_team: { id: 5 } } as any+ window.sessionStorage.clear()hrefSpy = jest.fn()+ replaceSpy = jest.fn()Object.defineProperty(window, 'location', {value: {origin: 'http://localhost',@@ -557,6 +560,7 @@ describe('loginLogic', () => {set href(url: string) {hrefSpy(url)},+ replace: replaceSpy,},configurable: true,})@@ -580,6 +584,56 @@ describe('loginLogic', () => {expect(hrefSpy).not.toHaveBeenCalled()})+ it('does a full navigation from a page rendered for a signed-out visitor', () => {+ // That page holds only the signed-out part of the stable chunk import map, so a client-side+ // route to an app scene fails to import its chunk.+ window.POSTHOG_APP_CONTEXT = { anonymous: true, current_team: { id: 5 } } as any+ router.actions.push(`/login?next=${encodeURIComponent('/project/5/dashboard/1')}`)+ handleLoginRedirect()+ // A replace (not an href assignment) so the stale signed-out document leaves history.+ expect(replaceSpy).toHaveBeenCalledWith('/project/5/dashboard/1')+ })++ it('stays client-side when the full navigation came straight back signed out', () => {+ // A server that keeps rendering the session signed out sends the new document back to /login.+ window.POSTHOG_APP_CONTEXT = { anonymous: true, current_team: { id: 5 } } as any+ router.actions.push(`/login?next=${encodeURIComponent('/project/5/dashboard/1')}`)+ handleLoginRedirect()+ router.actions.push(`/login?next=${encodeURIComponent('/project/5/dashboard/1')}`)+ handleLoginRedirect()++ expect(replaceSpy).toHaveBeenCalledTimes(1)+ expect(posthog.capture).toHaveBeenCalledWith('signed-out page redirect repeated')+ })++ it('stays client-side when sessionStorage is blocked, so it cannot reload forever', () => {+ window.POSTHOG_APP_CONTEXT = { anonymous: true, current_team: { id: 5 } } as any+ const getItem = jest.spyOn(Storage.prototype, 'getItem').mockImplementation(() => {+ throw new Error('blocked')+ })+ try {+ router.actions.push(`/login?next=${encodeURIComponent('/project/5/dashboard/1')}`)+ handleLoginRedirect()+ } finally {+ getItem.mockRestore()+ }++ expect(replaceSpy).not.toHaveBeenCalled()+ expect(posthog.capture).toHaveBeenCalledWith('signed-out page redirect skipped', {+ reason: 'storage_unavailable',+ })+ })++ it.each(['/.//evil.example/path', '/a/..//evil.example/path', '/../\\evil.example/path'])(+ 'keeps the signed-out full load on our origin for next=%s',+ (next) => {+ window.POSTHOG_APP_CONTEXT = { anonymous: true, current_team: { id: 5 } } as any+ router.actions.push(`/login?next=${encodeURIComponent(next)}`)+ handleLoginRedirect()+ expect(replaceSpy).toHaveBeenCalledWith('/')+ }+ )+it('does a full navigation for a project token the middleware resolves server-side', () => {// A `phc_` key or a legacy allowlisted api_token can't be compared to the numeric team id,// so it must reach AutoProjectMiddleware for resolution — client-side routing wouldn't switch.diff --git a/frontend/src/scenes/authentication/auth/loginLogic.ts b/frontend/src/scenes/authentication/auth/loginLogic.tsindex c9d885097d1e..4716445bfe5b 100644--- a/frontend/src/scenes/authentication/auth/loginLogic.ts+++ b/frontend/src/scenes/authentication/auth/loginLogic.ts@@ -13,7 +13,7 @@ import { getSocialLoginUrl } from 'lib/components/SocialLoginButton/socialLoginUimport { lemonToast } from 'lib/lemon-ui/LemonToast'import { featureFlagLogic } from 'lib/logic/featureFlagLogic'import { isWebKitBrowser } from 'lib/utils/dom'-import { getCurrentTeamIdOrNone } from 'lib/utils/getAppContext'+import { getCurrentTeamIdOrNone, isUserLoggedIn } from 'lib/utils/getAppContext'import { getRelativeNextPath, isEmail } from 'lib/utils/url'import { devLoginLogic } from 'scenes/authentication/shared/devLoginLogic'import {@@ -123,12 +123,50 @@ function loginRedirectTarget(): string {return '/'}+const SIGNED_OUT_PAGE_FULL_LOAD_KEY = 'ph_signed_out_page_full_load'+const SIGNED_OUT_PAGE_FULL_LOAD_WINDOW_MS = 30_000++type SignedOutPageFullLoadClaim = 'claimed' | 'repeated' | 'storage_unavailable'++/** A server that keeps rendering the session signed out would send the new document straight back to+ * /login, so a target gets one full load per window and the next attempt stays client-side. */+function claimFullLoadFromSignedOutPage(nextURL: string): SignedOutPageFullLoadClaim {+ try {+ const previous = JSON.parse(window.sessionStorage.getItem(SIGNED_OUT_PAGE_FULL_LOAD_KEY) ?? 'null')+ if (previous?.url === nextURL && Date.now() - previous.at < SIGNED_OUT_PAGE_FULL_LOAD_WINDOW_MS) {+ return 'repeated'+ }+ window.sessionStorage.setItem(SIGNED_OUT_PAGE_FULL_LOAD_KEY, JSON.stringify({ url: nextURL, at: Date.now() }))+ return 'claimed'+ } catch {+ // Without storage there is no loop guard, and an unguarded full load can reload forever.+ return 'storage_unavailable'+ }+}+/** Leave the login screen for a session that is already authenticated, e.g. someone opening- * `/login` in a second tab. The app context in this document is already the logged-in one, so the+ * `/login` in a second tab. When the app context in this document is already the logged-in one, the* redirect can stay client-side. Straight after authenticating, use `redirectAfterLogin` instead. */export function handleLoginRedirect(): void {const nextURL = loginRedirectTarget()+ // The server rendered this page for a signed-out visitor, so its app context has no user and its+ // stable chunk import map holds only the signed-out scenes. The app must arrive as a new document.+ if (!isUserLoggedIn()) {+ const claim = claimFullLoadFromSignedOutPage(nextURL)+ if (claim === 'claimed') {+ // Replace rather than assign so the stale signed-out document doesn't stay in history —+ // otherwise Back would return to /login, or redirect into the app again.+ window.location.replace(nextURL)+ return+ }+ if (claim === 'repeated') {+ posthog.capture('signed-out page redirect repeated')+ } else {+ posthog.capture('signed-out page redirect skipped', { reason: claim })+ }+ }+// Check if this is a backend-only route that shouldn't go through the React routerif (BACKEND_ONLY_ROUTES.some((route) => nextURL.startsWith(route))) {window.location.href = nextURL