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(toolbar): guard against non-Response fetch results in OAuth chain (#64975)

posthog[bot]cc7af737af8b
diff --git a/frontend/src/toolbar/toolbarAuth.ts b/frontend/src/toolbar/toolbarAuth.ts
index 34c212c7ea59..3b9207ef1b42 100644
--- a/frontend/src/toolbar/toolbarAuth.ts
+++ b/frontend/src/toolbar/toolbarAuth.ts
@@ -2,7 +2,7 @@ import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'
import { toolbarLogger } from '~/toolbar/toolbarLogger'
import { captureToolbarException, toolbarPosthogJS } from '~/toolbar/toolbarPosthogJS'
-import { asNonEmptyString } from '~/toolbar/utils'
+import { asNonEmptyString, safeFetch } from '~/toolbar/utils'
import { toolbarConfigLogic } from './toolbarConfigLogic'
@@ -22,7 +22,7 @@ export async function refreshOAuthTokens(
refreshPromise = (async () => {
const startTime = performance.now()
try {
- const response = await fetch(`${uiHost}/api/user/toolbar_oauth_refresh/`, {
+ const response = await safeFetch(`${uiHost}/api/user/toolbar_oauth_refresh/`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ refresh_token: currentRefreshToken, client_id: clientId }),
@@ -67,7 +67,9 @@ export async function withTokenRefresh(
const clientId = logic?.values.clientId
const uiHost = logic?.values.uiHost
- if (response.status !== 401 || !accessToken || !refreshToken || !clientId || !uiHost) {
+ // `response?.status` (not `response.status`) so a non-Response value from a customer-page
+ // `fetch` wrapper can't throw here — callers that don't route through `safeFetch` stay safe too.
+ if (response?.status !== 401 || !accessToken || !refreshToken || !clientId || !uiHost) {
return response
}
diff --git a/frontend/src/toolbar/toolbarConfigLogic.test.ts b/frontend/src/toolbar/toolbarConfigLogic.test.ts
index 6e090bebeda3..658a9012b5ce 100644
--- a/frontend/src/toolbar/toolbarConfigLogic.test.ts
+++ b/frontend/src/toolbar/toolbarConfigLogic.test.ts
@@ -905,6 +905,26 @@ describe('toolbar toolbarConfigLogic', () => {
expect((global.fetch as jest.Mock).mock.calls).toHaveLength(1)
expect(logic.values.accessToken).toBe('access-token')
})
+
+ it('does not throw when a customer fetch wrapper resolves to undefined', async () => {
+ const logic = toolbarConfigLogic.build({
+ apiURL: 'http://localhost',
+ accessToken: 'access-token',
+ refreshToken: 'refresh-token',
+ clientId: 'client-id',
+ })
+ logic.mount()
+ // A site-level `window.fetch` wrapper that returns `undefined` instead of a Response
+ // used to crash the OAuth chain with "Cannot read properties of undefined (reading 'status')".
+ ;(global.fetch as jest.Mock).mockImplementation(() => Promise.resolve(undefined))
+
+ const response = await toolbarFetch('/api/projects/@current/actions/')
+
+ // Normalized into a synthetic failed response so callers can degrade gracefully.
+ expect(response).toBeInstanceOf(Response)
+ expect(response.ok).toBe(false)
+ expect(logic.values.accessToken).toBe('access-token')
+ })
})
describe('authorization code extraction and hash cleanup', () => {
diff --git a/frontend/src/toolbar/toolbarConfigLogic.ts b/frontend/src/toolbar/toolbarConfigLogic.ts
index 2a1cb6e95f6f..c88d8b497ee1 100644
--- a/frontend/src/toolbar/toolbarConfigLogic.ts
+++ b/frontend/src/toolbar/toolbarConfigLogic.ts
@@ -17,6 +17,7 @@ import {
OAUTH_LOCALSTORAGE_KEY,
PKCE_STORAGE_KEY,
readToolbarAuthHash,
+ safeFetch,
} from './utils'
export type ApiHostSource = 'posthog_api_host' | 'api_url' | 'fallback_rejected' | 'fallback_absent'
@@ -860,7 +861,7 @@ export async function toolbarFetch(
const startTime = performance.now()
let didRetry = false
- let response = await fetch(fullUrl, {
+ let response = await safeFetch(fullUrl, {
method,
headers: buildHeaders(accessToken),
...(body !== undefined ? { body } : {}),
@@ -868,7 +869,7 @@ export async function toolbarFetch(
response = await withTokenRefresh(response, async (newAccessToken) => {
didRetry = true
- return await fetch(fullUrl, {
+ return await safeFetch(fullUrl, {
method,
headers: buildHeaders(newAccessToken),
...(body !== undefined ? { body } : {}),
diff --git a/frontend/src/toolbar/utils.test.ts b/frontend/src/toolbar/utils.test.ts
index 019a53966e1b..7706dfcad9b7 100644
--- a/frontend/src/toolbar/utils.test.ts
+++ b/frontend/src/toolbar/utils.test.ts
@@ -1,4 +1,4 @@
-import { asNonEmptyString, joinWithUiHost, slashDotDataAttrUnescape } from './utils'
+import { asNonEmptyString, joinWithUiHost, safeFetch, slashDotDataAttrUnescape } from './utils'
describe('utils', () => {
describe('asNonEmptyString', () => {
@@ -96,4 +96,43 @@ describe('utils', () => {
})
})
})
+
+ describe('safeFetch', () => {
+ const originalFetch = global.fetch
+
+ afterEach(() => {
+ global.fetch = originalFetch
+ })
+
+ it('passes a real Response through unchanged', async () => {
+ const realResponse = new Response('{}', { status: 200 })
+ global.fetch = jest.fn(() => Promise.resolve(realResponse)) as jest.Mock
+
+ const result = await safeFetch('https://example.com/api')
+
+ expect(result).toBe(realResponse)
+ })
+
+ it('passes a response-like object through unchanged', async () => {
+ const responseLike = { status: 200, ok: true, json: () => Promise.resolve({}) }
+ global.fetch = jest.fn(() => Promise.resolve(responseLike)) as jest.Mock
+
+ const result = await safeFetch('https://example.com/api')
+
+ expect(result).toBe(responseLike)
+ })
+
+ it.each([undefined, null, 'not-a-response'])(
+ 'normalizes a non-object value (%p) into a synthetic failed response',
+ async (resolved) => {
+ global.fetch = jest.fn(() => Promise.resolve(resolved)) as jest.Mock
+
+ const result = await safeFetch('https://example.com/api')
+
+ expect(result).toBeInstanceOf(Response)
+ expect(result.ok).toBe(false)
+ expect(result.status).toBe(502)
+ }
+ )
+ })
})
diff --git a/frontend/src/toolbar/utils.ts b/frontend/src/toolbar/utils.ts
index eea66c9f5b41..15845be78f7e 100644
--- a/frontend/src/toolbar/utils.ts
+++ b/frontend/src/toolbar/utils.ts
@@ -18,6 +18,19 @@ export const TOOLBAR_ID = '__POSTHOG_TOOLBAR__'
// load-bearing at runtime — verify before storing strings that flow into auth headers.
export const asNonEmptyString = (v: unknown): string | null => (typeof v === 'string' && v.length > 0 ? v : null)
+// `fetch` that always resolves to something safe to read `.status`/`.ok`/`.json()` off. A
+// site-level `window.fetch` wrapper on the customer page can resolve to `undefined`/`null` (or
+// another non-object), which makes every downstream `.status` access throw a TypeError. Normalize
+// any non-object value into a synthetic failed response so the toolbar's OAuth chain and its
+// callers can treat it as an ordinary request failure rather than crashing.
+export async function safeFetch(input: RequestInfo | URL, init?: RequestInit): Promise<Response> {
+ const response = await fetch(input, init)
+ if (response && typeof response === 'object') {
+ return response
+ }
+ return new Response(JSON.stringify({ results: [], detail: 'invalid_fetch_response' }), { status: 502 })
+}
+
const elementToQueryCache = new WeakMap<HTMLElement, string | undefined>()
export const TOOLBAR_CONTAINER_CLASS = 'toolbar-global-fade-container'
export const LOCALSTORAGE_KEY = '_postHogToolbarParams'