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.

fix(command-palette): guard palette navigation against pushState failures (#94764)

posthog[bot]5f8baa8f525e
diff --git a/.semgrep/rules/devex/router-no-raw-href-push.test.ts b/.semgrep/rules/devex/router-no-raw-href-push.test.ts
new file mode 100644
index 000000000000..7b37f45dfe85
--- /dev/null
+++ b/.semgrep/rules/devex/router-no-raw-href-push.test.ts
@@ -0,0 +1,33 @@
+// @ts-nocheck
+// Test fixture for the router-no-raw-href-push rule.
+
+// ruleid: router-no-raw-href-push
+router.actions.push(item.href)
+
+// ruleid: router-no-raw-href-push
+router.actions.replace(item.href)
+
+// ruleid: router-no-raw-href-push
+router.actions.push(product.href)
+
+// ruleid: router-no-raw-href-push
+router.actions.push(notification.record.href)
+
+// ruleid: router-no-raw-href-push
+router.actions.push(item.href, searchParams)
+
+// A path built from `urls.*` is same-origin by construction, so it stays allowed.
+// ok: router-no-raw-href-push
+router.actions.push(urls.insightView(insight.short_id))
+
+// ok: router-no-raw-href-push
+router.actions.push('/project/1/dashboard')
+
+// ok: router-no-raw-href-push
+router.actions.push(urls.ai(undefined, searchValue.trim()))
+
+// ok: router-no-raw-href-push
+navigateToHref(item.href)
+
+// ok: router-no-raw-href-push
+newInternalTab(item.href)
diff --git a/.semgrep/rules/devex/router-no-raw-href-push.yaml b/.semgrep/rules/devex/router-no-raw-href-push.yaml
new file mode 100644
index 000000000000..cbeb7b628324
--- /dev/null
+++ b/.semgrep/rules/devex/router-no-raw-href-push.yaml
@@ -0,0 +1,39 @@
+rules:
+ - id: router-no-raw-href-push
+ message: |
+ An href read off a data object is pushed straight into the router. `router.actions.push`
+ reaches `history.pushState`, which accepts only a same-origin path, so a value that came
+ from the API rather than from `urls.*` breaks in three ways:
+
+ • an off-origin href (`https://...`) gets rewritten into a broken in-app path, because
+ the router prefixes it with the current project
+ • a `'#'` placeholder href, which several search items carry when they have no
+ destination, navigates to a dead route
+ • a `javascript:` href reaches a navigation sink, and a rejected `pushState` throws a
+ `SecurityError` out of the click handler as an uncaught exception
+
+ Use, in order of preference:
+ • `Link` / `LinkPrimitive` (`lib/lemon-ui/Link`) when you render the target as a link -
+ it resolves the href and routes on click
+ • `navigateToHref` (`lib/utils/navigateToHref`) when you have an href but no anchor to
+ click, such as a command palette item or a keyboard selection
+ • `newInternalTab` (`lib/utils/newInternalTab`) to open the target in a new tab
+
+ Pushing a path you built yourself with `urls.*` is fine and this rule does not match it.
+ If a raw push is genuinely right here, add `// nosemgrep: router-no-raw-href-push` with a
+ short reason.
+ severity: ERROR
+ languages: [typescript]
+ paths:
+ include:
+ - frontend/src
+ - products
+ exclude:
+ - frontend/src/lib/utils/navigateToHref.ts
+ - '**/*.test.ts'
+ - '**/*.test.tsx'
+ pattern-either:
+ - pattern: router.actions.push($X.href, ...)
+ - pattern: router.actions.replace($X.href, ...)
+ metadata:
+ category: best-practice
diff --git a/frontend/src/lib/components/Command/Command.tsx b/frontend/src/lib/components/Command/Command.tsx
index 23faa479f730..4638b38a716d 100644
--- a/frontend/src/lib/components/Command/Command.tsx
+++ b/frontend/src/lib/components/Command/Command.tsx
@@ -1,8 +1,8 @@
import { useActions, useValues } from 'kea'
-import { router } from 'kea-router'
import { useCallback } from 'react'
import { DialogPrimitive, DialogPrimitiveTitle } from 'lib/ui/DialogPrimitive/DialogPrimitive'
+import { navigateToHref } from 'lib/utils/navigateToHref'
import { newInternalTab } from 'lib/utils/newInternalTab'
import { Search } from '../Search/Search'
@@ -24,7 +24,7 @@ export function Command(): JSX.Element {
if (openInNewTab) {
newInternalTab(item.href)
} else {
- router.actions.push(item.href)
+ navigateToHref(item.href)
}
}
},
diff --git a/frontend/src/lib/components/Search/Search.tsx b/frontend/src/lib/components/Search/Search.tsx
index 369d2e9bf232..b2a90fd04333 100644
--- a/frontend/src/lib/components/Search/Search.tsx
+++ b/frontend/src/lib/components/Search/Search.tsx
@@ -1,7 +1,6 @@
import { Autocomplete } from '@base-ui/react/autocomplete'
import { useActions, useValues } from 'kea'
import { capitalizeFirstLetter } from 'kea-forms'
-import { router } from 'kea-router'
import {
Fragment,
type MutableRefObject,
@@ -30,6 +29,7 @@ import { ContextMenu, ContextMenuContent, ContextMenuGroup, ContextMenuTrigger }
import { Label } from 'lib/ui/Label/Label'
import { WrappingLoadingSkeleton } from 'lib/ui/WrappingLoadingSkeleton/WrappingLoadingSkeleton'
import { cn } from 'lib/utils/css-classes'
+import { navigateToHref } from 'lib/utils/navigateToHref'
import { newInternalTab } from 'lib/utils/newInternalTab'
import { urls } from 'scenes/urls'
import { userLogic } from 'scenes/userLogic'
@@ -528,7 +528,7 @@ function SearchRoot({
return
}
if (item.href) {
- router.actions.push(item.href)
+ navigateToHref(item.href)
return
}
}
@@ -538,7 +538,7 @@ function SearchRoot({
if (openInNewTab) {
newInternalTab(item.href)
} else {
- router.actions.push(item.href)
+ navigateToHref(item.href)
}
}
},
@@ -697,7 +697,7 @@ function SearchInput({ autoFocus, className }: SearchInputProps): JSX.Element {
if (e.key === 'Tab' && showAskAiLink && searchValue.trim()) {
e.preventDefault()
onAskAiClick?.()
- router.actions.push(urls.ai(undefined, searchValue.trim()))
+ navigateToHref(urls.ai(undefined, searchValue.trim()))
return
}
// Cmd/Ctrl+Enter opens the highlighted result in a new tab. Base UI's combobox input
@@ -765,7 +765,7 @@ function SearchInput({ autoFocus, className }: SearchInputProps): JSX.Element {
variant="panel"
onClick={() => {
onAskAiClick?.()
- router.actions.push(urls.ai(undefined, searchValue.trim()))
+ navigateToHref(urls.ai(undefined, searchValue.trim()))
}}
tooltip="Click or press Tab to ask AI"
>
diff --git a/frontend/src/lib/components/Search/searchLogic.tsx b/frontend/src/lib/components/Search/searchLogic.tsx
index b4452bf74fb0..1cb6127b35b7 100644
--- a/frontend/src/lib/components/Search/searchLogic.tsx
+++ b/frontend/src/lib/components/Search/searchLogic.tsx
@@ -14,6 +14,7 @@ import { getEntryAccessDisabledReason, getProductAccessDisabledReason } from 'li
import { uuid } from 'lib/utils/dom'
import { GroupQueryResult, mapGroupQueryResponse } from 'lib/utils/groups'
import { removeProjectIdIfPresent } from 'lib/utils/kea-router'
+import { PLACEHOLDER_HREF } from 'lib/utils/navigateToHref'
import { newInternalTab } from 'lib/utils/newInternalTab'
import { capitalizeFirstLetter, toSentenceCase } from 'lib/utils/strings'
import { billingLogic } from 'scenes/billing/billingLogic'
@@ -102,7 +103,7 @@ const fileSystemEntryToSearchItem = (
return {
name: itemName,
displayName,
- href: item.href || '#',
+ href: item.href || PLACEHOLDER_HREF,
lastViewedAt: item.last_viewed_at ?? null,
itemType,
record: { ...item, iconColor: productIconColor },
@@ -903,7 +904,7 @@ export const searchLogic = kea<searchLogicType>([
displayName: product.displayLabel ?? product.path,
category: 'tools',
productCategory: product.category || null,
- href: product.href || '#',
+ href: product.href || PLACEHOLDER_HREF,
itemType: product.iconType || product.type || null,
tags: product.tags,
searchKeywords: productSearchKeywords[product.path],
@@ -977,7 +978,7 @@ export const searchLogic = kea<searchLogicType>([
displayName: item.path,
category: 'data-management',
productCategory: item.category || null,
- href: item.href || '#',
+ href: item.href || PLACEHOLDER_HREF,
itemType: item.iconType || item.type || null,
tags: item.tags,
searchKeywords: item.category ? categorySearchKeywords[item.category] : undefined,
@@ -1047,7 +1048,7 @@ export const searchLogic = kea<searchLogicType>([
displayName,
category: 'create',
productCategory: item.category || null,
- href: item.href || '#',
+ href: item.href || PLACEHOLDER_HREF,
itemType: item.iconType || item.type || null,
tags: item.tags,
record: {
@@ -1097,7 +1098,7 @@ export const searchLogic = kea<searchLogicType>([
displayName: item.path,
category: 'people',
productCategory: item.category || null,
- href: item.href || '#',
+ href: item.href || PLACEHOLDER_HREF,
itemType: item.iconType || item.type || null,
tags: item.tags,
lastViewedAt: item.sceneKey ? (sceneLogViewsByRef[item.sceneKey] ?? null) : null,
@@ -1236,7 +1237,7 @@ export const searchLogic = kea<searchLogicType>([
id: `playlist-${item.id}`,
name: name ? unescapePath(name) : item.path,
category: 'session_recording_playlist',
- href: item.href || '#',
+ href: item.href || PLACEHOLDER_HREF,
itemType: 'session_recording_playlist',
disabledReason: getEntryAccessDisabledReason(item),
record: item as unknown as Record<string, unknown>,
diff --git a/frontend/src/lib/components/Search/utils.test.ts b/frontend/src/lib/components/Search/utils.test.ts
index 5cf0e6f068be..78fd224c35c5 100644
--- a/frontend/src/lib/components/Search/utils.test.ts
+++ b/frontend/src/lib/components/Search/utils.test.ts
@@ -1,3 +1,5 @@
+import { PLACEHOLDER_HREF } from 'lib/utils/navigateToHref'
+
import { SETTINGS_THEME_ITEM_ID, canOpenInNewTab, filterSearchItems, shouldSearchTickets } from './utils'
interface TestItem {
@@ -122,6 +124,7 @@ describe('canOpenInNewTab', () => {
false,
],
['blocks a result with nothing to open', { id: 'no-href' }, false],
+ ['blocks a result whose href is the placeholder', { id: 'starred-1', href: PLACEHOLDER_HREF }, false],
]
it.each(cases)('%s', (_label, item, expected) => {
diff --git a/frontend/src/lib/components/Search/utils.ts b/frontend/src/lib/components/Search/utils.ts
index 72a26fae5653..2bc12b7fc798 100644
--- a/frontend/src/lib/components/Search/utils.ts
+++ b/frontend/src/lib/components/Search/utils.ts
@@ -1,5 +1,6 @@
import { Dayjs, dayjs } from 'lib/dayjs'
import { createFuse } from 'lib/utils/fuseSearch'
+import { PLACEHOLDER_HREF } from 'lib/utils/navigateToHref'
import { pluralize } from 'lib/utils/strings'
/** Synthetic result that jumps to the theme setting, or toggles the theme outright. */
@@ -48,9 +49,10 @@ interface NewTabCandidate {
* navigate qualify. An item carrying `onSelect`, and the theme row, run an action instead,
* so treating the modifier as "open in a new tab" would fire that action rather than open
* anything, which is merely surprising for most items but destructive for "Log out".
+ * A placeholder href goes nowhere, so it would open an empty tab.
*/
export const canOpenInNewTab = (item: NewTabCandidate): boolean =>
- !!item.href && !item.onSelect && item.id !== SETTINGS_THEME_ITEM_ID
+ !!item.href && item.href !== PLACEHOLDER_HREF && !item.onSelect && item.id !== SETTINGS_THEME_ITEM_ID
/** Optional leading `#` and nothing but digits — the shape the ticket endpoint resolves with an
* exact ticket-number lookup rather than a text scan (`is_ticket_number_search` server-side). */
diff --git a/frontend/src/lib/lemon-ui/Link/Link.tsx b/frontend/src/lib/lemon-ui/Link/Link.tsx
index 93da949dc569..a826dad8d4bc 100644
--- a/frontend/src/lib/lemon-ui/Link/Link.tsx
+++ b/frontend/src/lib/lemon-ui/Link/Link.tsx
@@ -9,7 +9,7 @@ import { ButtonPrimitiveProps, buttonPrimitiveVariants } from 'lib/ui/Button/But
import { cn } from 'lib/utils/css-classes'
import { getCurrentTeamId } from 'lib/utils/getAppContext'
import { addProjectIdIfMissing, removeProjectIdIfPresent } from 'lib/utils/kea-router'
-import { isExternalLink } from 'lib/utils/url'
+import { hasDangerousScheme, isExternalLink } from 'lib/utils/url'
import { urlToResource } from 'scenes/urls'
import { Tooltip, TooltipProps } from '../Tooltip'
@@ -94,14 +94,6 @@ const isDirectLink = (url: string): boolean => {
return /^(mailto:|https?:\/\/|:\/\/)/.test(url)
}
-const hasDangerousScheme = (url: string): boolean => {
- // Browsers ignore leading control chars/whitespace and any tabs/newlines embedded in the scheme,
- // so strip them all before matching. javascript:/vbscript: targets must never become an href —
- // not even when disableClientSideRouting would otherwise skip the routing rewrite.
- const normalized = url.replace(/[\u0000-\u0020]/g, '').toLowerCase()
- return /^(javascript|vbscript):/.test(normalized)
-}
-
/** Resolve a `to` target into a concrete href string. */
function resolveHref(to: LinkPrimitiveProps['to'], disableClientSideRouting?: boolean): string | undefined {
if (!to) {
@@ -110,6 +102,8 @@ function resolveHref(to: LinkPrimitiveProps['to'], disableClientSideRouting?: bo
if (typeof to !== 'string') {
return '#'
}
+ // Never let a javascript:/vbscript: target become an href, not even when
+ // disableClientSideRouting would otherwise skip the routing rewrite below.
if (hasDangerousScheme(to)) {
return '#'
}
diff --git a/frontend/src/lib/utils/navigateToHref.test.ts b/frontend/src/lib/utils/navigateToHref.test.ts
new file mode 100644
index 000000000000..aeb0c06ce20e
--- /dev/null
+++ b/frontend/src/lib/utils/navigateToHref.test.ts
@@ -0,0 +1,93 @@
+import { router } from 'kea-router'
+
+import { navigateToHref } from 'lib/utils/navigateToHref'
+
+import { AppContext } from '~/types'
+
+jest.mock('kea-router', () => ({
+ router: { actions: { push: jest.fn() } },
+}))
+
+const push = router.actions.push as jest.Mock
+
+describe('navigateToHref', () => {
+ const originalLocation = window.location
+ const originalAppContext = window.POSTHOG_APP_CONTEXT
+
+ beforeEach(() => {
+ push.mockReset()
+ Object.defineProperty(window, 'location', {
+ value: { ...window.location, href: 'https://us.posthog.com/project/997/dashboard' },
+ configurable: true,
+ })
+ window.POSTHOG_APP_CONTEXT = { current_team: { id: 997 } } as unknown as AppContext
+ })
+
+ afterEach(() => {
+ Object.defineProperty(window, 'location', { value: originalLocation, configurable: true })
+ window.POSTHOG_APP_CONTEXT = originalAppContext
+ })
+
+ it('routes an in-app path client-side', () => {
+ navigateToHref('/insights/abc123')
+
+ expect(push).toHaveBeenCalledWith('/insights/abc123')
+ expect(window.location.href).toEqual('https://us.posthog.com/project/997/dashboard')
+ })
+
+ it.each([undefined, '', '#'])('navigates nowhere for %p', (href) => {
+ navigateToHref(href)
+
+ expect(push).not.toHaveBeenCalled()
+ expect(window.location.href).toEqual('https://us.posthog.com/project/997/dashboard')
+ })
+
+ // A search item href is team-writable, so a script target must never reach the router or a
+ // page load. `javascript:/api/...` is the reachable shape: `addProjectIdIfMissing` leaves it
+ // intact, so it fails the same-origin check in `pushState` and lands in the fallback below.
+ it.each([
+ 'javascript:alert(1)',
+ 'javascript:/api/,alert(document.cookie)',
+ 'JaVaScRiPt:/login/,alert(1)',
+ '\t java\nscript:/me/,alert(1)',
+ 'vbscript:/api/,msgbox(1)',
+ ])('refuses to navigate to %p', (href) => {
+ push.mockImplementation(() => {
+ throw new DOMException('The operation is insecure.', 'SecurityError')
+ })
+
+ navigateToHref(href)
+
+ expect(push).not.toHaveBeenCalled()
+ expect(window.location.href).toEqual('https://us.posthog.com/project/997/dashboard')
+ })
+
+ it.each(['https://posthog.com/docs', 'mailto:[email protected]', '/api/projects/997/exports/1'])(
+ 'loads %p as a page instead of routing it',
+ (href) => {
+ navigateToHref(href)
+
+ expect(push).not.toHaveBeenCalled()
+ expect(window.location.href).toEqual(href)
+ }
+ )
+
+ it('falls back to a project-scoped page load when the History API rejects the push', () => {
+ push.mockImplementation(() => {
+ throw new DOMException('The operation is insecure.', 'SecurityError')
+ })
+
+ navigateToHref('/insights/abc123')
+
+ expect(window.location.href).toEqual('/project/997/insights/abc123')
+ })
+
+ it('lets an error from a logic reacting to the navigation through', () => {
+ push.mockImplementation(() => {
+ throw new Error('a scene logic blew up')
+ })
+
+ expect(() => navigateToHref('/insights/abc123')).toThrow('a scene logic blew up')
+ expect(window.location.href).toEqual('https://us.posthog.com/project/997/dashboard')
+ })
+})
diff --git a/frontend/src/lib/utils/navigateToHref.ts b/frontend/src/lib/utils/navigateToHref.ts
new file mode 100644
index 000000000000..1b12acd34c87
--- /dev/null
+++ b/frontend/src/lib/utils/navigateToHref.ts
@@ -0,0 +1,42 @@
+import { router } from 'kea-router'
+
+import { addProjectIdIfMissing } from 'lib/utils/kea-router'
+import { hasDangerousScheme, isExternalLink } from 'lib/utils/url'
+
+/** Search items with no real destination carry this href, so it must never be navigated to. */
+export const PLACEHOLDER_HREF = '#'
+
+/**
+ * Navigate to an href the way `Link` does, for call sites that have an href but no anchor to
+ * click — a command palette item, a menu row, a keyboard selection.
+ *
+ * `router.actions.push` reaches `history.pushState`, which rejects a cross-origin URL and, in
+ * Safari, rate-limits repeat calls. Both raise a `SecurityError` that escapes the click handler
+ * as an uncaught exception, so a page load is the fallback: the person still gets where they
+ * asked to go.
+ *
+ * An href reaches this from team-writable data, so a `javascript:` target has to go nowhere.
+ * `addProjectIdIfMissing` does not make one safe: it prefixes most paths into the current
+ * project, but passes through anything whose second segment names a project-less route, so
+ * `javascript:/api/...` survives intact, fails the same-origin check in `pushState`, and would
+ * reach the page-load fallback below.
+ */
+export function navigateToHref(href?: string): void {
+ if (!href || href === PLACEHOLDER_HREF || hasDangerousScheme(href)) {
+ return
+ }
+ if (isExternalLink(href)) {
+ window.location.href = href
+ return
+ }
+ try {
+ router.actions.push(href)
+ } catch (error) {
+ // Any other error comes from a logic reacting to the navigation, which already happened.
+ // Reloading the page over it would hide the real failure.
+ if (!(error instanceof DOMException) || error.name !== 'SecurityError') {
+ throw error
+ }
+ window.location.href = addProjectIdIfMissing(href)
+ }
+}
diff --git a/frontend/src/lib/utils/url.ts b/frontend/src/lib/utils/url.ts
index afd9e97a7bde..d8558f53140c 100644
--- a/frontend/src/lib/utils/url.ts
+++ b/frontend/src/lib/utils/url.ts
@@ -165,6 +165,14 @@ export function isExternalLink(input: any): boolean {
return !!input.trim().match(regexp)
}
+/** True for a target the browser runs as script, so it must never become an href or a navigation. */
+export function hasDangerousScheme(url: string): boolean {
+ // Browsers ignore leading control chars/whitespace and any tabs/newlines embedded in the scheme,
+ // so strip them all before matching.
+ const normalized = url.replace(/[\u0000-\u0020]/g, '').toLowerCase()
+ return /^(javascript|vbscript):/.test(normalized)
+}
+
/**
* True for a value that parses as an `https://` URL. Whitespace around the value is ignored,
* because `new URL()` ignores it too. A caller that needs a host allowlist, or that wants to
diff --git a/frontend/src/scenes/new-tab/NewTabScene.tsx b/frontend/src/scenes/new-tab/NewTabScene.tsx
index 6a2af7c8ff32..7e13dd8b0fb4 100644
--- a/frontend/src/scenes/new-tab/NewTabScene.tsx
+++ b/frontend/src/scenes/new-tab/NewTabScene.tsx
@@ -4,6 +4,7 @@ import { useCallback } from 'react'
import { Search } from 'lib/components/Search/Search'
import { SearchItem } from 'lib/components/Search/searchLogic'
+import { navigateToHref } from 'lib/utils/navigateToHref'
import { newInternalTab } from 'lib/utils/newInternalTab'
import { SceneExport } from 'scenes/sceneTypes'
import { urls } from 'scenes/urls'
@@ -21,7 +22,7 @@ export function NewTabScene(): JSX.Element {
if (openInNewTab) {
newInternalTab(item.href)
} else {
- router.actions.push(item.href)
+ navigateToHref(item.href)
}
}, [])
diff --git a/frontend/src/scenes/project-homepage/ai-first/aiFirstHomepageLogic.ts b/frontend/src/scenes/project-homepage/ai-first/aiFirstHomepageLogic.ts
index be1da79c17c0..69637816aead 100644
--- a/frontend/src/scenes/project-homepage/ai-first/aiFirstHomepageLogic.ts
+++ b/frontend/src/scenes/project-homepage/ai-first/aiFirstHomepageLogic.ts
@@ -3,6 +3,7 @@ import { actionToUrl, router, urlToAction } from 'kea-router'
import posthog from 'posthog-js'
import { tabUiStateLogic } from 'lib/logic/tabUiStateLogic'
+import { navigateToHref } from 'lib/utils/navigateToHref'
import { handsFreeLogic } from 'scenes/max/handsFreeLogic'
import { type PhaiViewMode, maxGlobalLogic } from 'scenes/max/maxGlobalLogic'
import { maxLogic, parseCommandString } from 'scenes/max/maxLogic'
@@ -526,7 +527,7 @@ export const aiFirstHomepageLogic = kea<aiFirstHomepageLogicType>([
}
}, 'suggestionTyping')
} else if (item.href) {
- router.actions.push(item.href)
+ navigateToHref(item.href)
}
},
setQuery: ({ query }) => {