: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
feat(web-analytics): detect pages that block embedding or return errors (#75702)
Jordan Mryyan634bad0710c6
diff --git a/frontend/src/scenes/heatmaps/components/HeatmapHeader.tsx b/frontend/src/scenes/heatmaps/components/HeatmapHeader.tsxindex 213625d427d6..7bd7a7827021 100644--- a/frontend/src/scenes/heatmaps/components/HeatmapHeader.tsx+++ b/frontend/src/scenes/heatmaps/components/HeatmapHeader.tsx@@ -101,8 +101,7 @@ export function HeatmapHeader(): JSX.Element {onClick: () => changeCaptureMethod('screenshot'),}}>- This page didn't load in the live preview. It may block embedding. If it is public,- switch to Screenshot. If it requires login, use a session recording below.+ {iframeBanner.message}</LemonBanner>{displayUrl && !displayUrlIsPattern ? <HeatmapRecordingFallback url={displayUrl} /> : null}</div>diff --git a/frontend/src/scenes/heatmaps/components/heatmapsBrowserLogic.test.ts b/frontend/src/scenes/heatmaps/components/heatmapsBrowserLogic.test.tsindex 04faad859ce4..f3fb5d828bd5 100644--- a/frontend/src/scenes/heatmaps/components/heatmapsBrowserLogic.test.ts+++ b/frontend/src/scenes/heatmaps/components/heatmapsBrowserLogic.test.ts@@ -5,7 +5,12 @@ import api from 'lib/api'import { initKeaTests } from '~/test/init'-import { heatmapsBrowserLogic, normalizeHeatmapDataUrl } from './heatmapsBrowserLogic'+import {+ PagePreflight,+ heatmapsBrowserLogic,+ normalizeHeatmapDataUrl,+ preflightBannerMessage,+} from './heatmapsBrowserLogic'describe('heatmapsBrowserLogic', () => {describe('normalizeHeatmapDataUrl', () => {@@ -25,6 +30,49 @@ describe('heatmapsBrowserLogic', () => {})})+ describe('preflightBannerMessage', () => {+ const base: PagePreflight = {+ url: 'https://shop.example.com/p',+ framing: 'allowed',+ blocked_by: null,+ http_status: 200,+ body_excerpt: null,+ }++ it.each([+ ['blocked by csp', { framing: 'blocked', blocked_by: 'frame_ancestors' }, 'content security policy'],+ ['blocked by xfo', { framing: 'blocked', blocked_by: 'x_frame_options' }, 'X-Frame-Options'],+ ] as const)('explains why the live preview cannot load when %s', (_name, overrides, expected) => {+ const message = preflightBannerMessage({ ...base, ...overrides })+ expect(message).toContain('shop.example.com')+ expect(message).toContain(expected)+ })++ it('attributes a non-2xx to the customer host and quotes what it returned', () => {+ const message = preflightBannerMessage({+ ...base,+ framing: 'unknown',+ http_status: 429,+ body_excerpt: 'local_rate_limited',+ })++ expect(message).toContain('429')+ expect(message).toContain('local_rate_limited')+ expect(message).toContain('host or CDN')+ expect(message).not.toContain('embedding')+ })++ it.each([+ ['a healthy page', base],+ ['an inconclusive probe', { ...base, framing: 'unknown', http_status: null }],+ // A redirect is how a healthy page normally answers, and the browser follows it, so it+ // must never be reported as the customer's host refusing us.+ ['a redirect', { ...base, framing: 'unknown', http_status: 301 }],+ ] as const)('stays silent for %s', (_name, preflight) => {+ expect(preflightBannerMessage(preflight)).toBeNull()+ })+ })+describe('page URL query-param sync', () => {beforeEach(() => {initKeaTests()@@ -52,4 +100,45 @@ describe('heatmapsBrowserLogic', () => {expect(router.values.searchParams.pageURL).toBeUndefined()})})++ describe('iframeBanner', () => {+ beforeEach(() => {+ initKeaTests()+ jest.spyOn(api, 'queryHogQL').mockResolvedValue({ results: [] } as any)+ router.actions.push('/heatmaps/abc123')+ })++ afterEach(() => {+ jest.restoreAllMocks()+ })++ // A frame blocked by X-Frame-Options still fires onload, and onIframeLoad nulls the load-timeout+ // banner via stopTrackingLoading. Before the probe result outranked it, that wiped the explanation+ // and the user was left with a blank frame and no message at all.+ it('keeps explaining a blocked page after the iframe reports it loaded', async () => {+ const logic = heatmapsBrowserLogic({ iframeRef: { current: null } })+ logic.mount()+ await expectLogic(logic).toFinishAllListeners()++ logic.actions.setDisplayUrl('https://shop.example.com/p')+ logic.actions.checkPagePreflightSuccess({+ url: 'https://shop.example.com/p',+ framing: 'blocked',+ blocked_by: 'x_frame_options',+ http_status: 200,+ body_excerpt: null,+ })+ logic.actions.onIframeLoad()+ await expectLogic(logic).toFinishAllListeners()++ expect(logic.values.loadTimeoutBanner).toBeNull()+ expect(logic.values.iframeBanner?.level).toBe('error')+ expect(logic.values.iframeBanner?.message).toContain('X-Frame-Options')++ // Editing the URL must drop the old verdict rather than blaming the new page for it.+ logic.actions.setDisplayUrl('https://other.example.com/p')+ await expectLogic(logic).toFinishAllListeners()+ expect(logic.values.iframeBanner).toBeNull()+ })+ })})diff --git a/frontend/src/scenes/heatmaps/components/heatmapsBrowserLogic.ts b/frontend/src/scenes/heatmaps/components/heatmapsBrowserLogic.tsindex b0b192862197..ed7b51a52f49 100644--- a/frontend/src/scenes/heatmaps/components/heatmapsBrowserLogic.ts+++ b/frontend/src/scenes/heatmaps/components/heatmapsBrowserLogic.ts@@ -30,9 +30,13 @@ import { LemonBannerProps } from 'lib/lemon-ui/LemonBanner'import { FeatureFlagsSet, featureFlagLogic } from 'lib/logic/featureFlagLogic'import { objectsEqual } from 'lib/utils/objects'import { removeReplayIframeDataFromLocalStorage } from 'scenes/session-recordings/player/sessionRecordingPlayerLogic'+import { teamLogic } from 'scenes/teamLogic'import { hogql } from '~/queries/utils'+import { savedPreflightCreate } from 'products/web_analytics/frontend/generated/api'+import type { HeatmapPreflightResponseApi } from 'products/web_analytics/frontend/generated/api.schemas'+import type { KeyedAppUrl } from '../../../lib/components/AuthorizedUrlList/authorizedUrlListLogic'import type { HrefMatchType } from '../../../lib/components/heatmaps/heatmapDataLogic'import type { HeatmapFilters } from '../../../lib/components/heatmaps/types'@@ -46,6 +50,46 @@ export interface IFrameBanner {message: string | JSX.Element}+export interface PagePreflight extends HeatmapPreflightResponseApi {+ url: string+}++function hostOf(url: string): string {+ try {+ return new URL(url).host+ } catch {+ return 'This page'+ }+}++export function preflightBannerMessage(preflight: PagePreflight | null): string | null {+ if (!preflight) {+ return null+ }+ const host = hostOf(preflight.url)++ // Only a 4xx or 5xx is the host refusing. Anything else it answered with, the browser handles+ // on its own, and blaming the customer's CDN for it sends them after a problem they don't have.+ if (preflight.http_status !== null && preflight.http_status >= 400) {+ const said = preflight.body_excerpt ? ` It said: "${preflight.body_excerpt}".` : ''+ return (+ `${host} returned ${preflight.http_status} when we tried to load this page.${said} ` ++ `This came from your site's host or CDN, not from PostHog. ` ++ `Check its rate limits and firewall rules, then try again.`+ )+ }++ if (preflight.framing === 'blocked') {+ const header = preflight.blocked_by === 'x_frame_options' ? 'X-Frame-Options' : 'a content security policy'+ return (+ `${host} uses ${header} to stop other sites embedding it, so the live preview cannot load. ` ++ `Use a screenshot background instead.`+ )+ }++ return null+}+export interface ReplayIframeData {html: stringwidth: number // NB this should be meta width@@ -97,10 +141,12 @@ export interface heatmapsBrowserLogicValues {hrefMatchType: HrefMatchType // heatmapDataLogicisHeightCapped: boolean // heatmapDataLogicwidthOverride: number // heatmapDataLogic+ currentTeamIdStrict: number | string // teamLogicbrowserSearchResults: string[] | nullbrowserSearchResultsLoading: booleanbrowserSearchTerm: stringbrowserUrlSearchOptions: string[] | null+ currentPagePreflight: PagePreflight | nulldataUrl: string | nulldisplayUrl: string | nullfilterPanelCollapsed: boolean@@ -108,8 +154,12 @@ export interface heatmapsBrowserLogicValues {iframeBanner: IFrameBanner | nullisBrowserUrlAuthorized: booleanisBrowserUrlValid: boolean+ loadTimeoutBanner: IFrameBanner | nullloading: booleannoPageviews: boolean+ pagePreflight: PagePreflight | null+ pagePreflightLoading: boolean+ preflightMessage: string | nullreplayIframeData: ReplayIframeData | nulltopUrls:| {@@ -151,6 +201,27 @@ export interface heatmapsBrowserLogicActions {setWindowWidthOverride: (widthOverride: number | null) => {widthOverride: number | null} // heatmapDataLogic+ checkPagePreflight: (url: string | null) => {+ url: string | null+ }+ checkPagePreflightFailure: (+ error: string,+ errorObject?: any+ ) => {+ error: string+ errorObject?: any+ }+ checkPagePreflightSuccess: (+ pagePreflight: PagePreflight | null,+ payload?: {+ url: string | null+ }+ ) => {+ pagePreflight: PagePreflight | null+ payload?: {+ url: string | null+ }+ }loadBrowserSearchResults: () => {value: true}@@ -247,6 +318,9 @@ export interface heatmapsBrowserLogicActions {// Generated by kea-typegen. Update if you're an agent, ignore if you're human.export interface heatmapsBrowserLogicMeta {__keaTypeGenInternalSelectorTypes: {+ currentPagePreflight: (pagePreflight: PagePreflight | null, displayUrl: string | null) => PagePreflight | null+ preflightMessage: (currentPagePreflight: PagePreflight | null) => string | null+ iframeBanner: (preflightMessage: string | null, loadTimeoutBanner: IFrameBanner | null) => IFrameBanner | nullbrowserUrlSearchOptions: (browserSearchResults: string[] | null,topUrls:@@ -313,6 +387,8 @@ export const heatmapsBrowserLogic = kea<heatmapsBrowserLogicType>([],featureFlagLogic,['featureFlags'],+ teamLogic,+ ['currentTeamIdStrict'],],actions: [heatmapDataLogic({ context: 'in-app' }),@@ -348,6 +424,7 @@ export const heatmapsBrowserLogic = kea<heatmapsBrowserLogicType>([stopTrackingLoading: true,setReplayIframeData: (replayIframeData: ReplayIframeData | null) => ({ replayIframeData }),setReplayIframeDataURL: (url: string | null) => ({ url }),+ checkPagePreflight: (url: string | null) => ({ url }),}),loaders(({ values }) => ({@@ -395,6 +472,30 @@ export const heatmapsBrowserLogic = kea<heatmapsBrowserLogicType>([},},],++ pagePreflight: [+ null as PagePreflight | null,+ {+ checkPagePreflight: async ({ url }, breakpoint): Promise<PagePreflight | null> => {+ if (!url) {+ return null+ }+ if (values.pagePreflight?.url === url) {+ return values.pagePreflight+ }+ await breakpoint(500)+ let result: HeatmapPreflightResponseApi+ try {+ result = await savedPreflightCreate(String(values.currentTeamIdStrict), { url })+ } catch {+ // The probe is only ever used to explain a failure, so it must never create one.+ return null+ }+ breakpoint()+ return { url, ...result }+ },+ },+ ],})),reducers({@@ -446,7 +547,7 @@ export const heatmapsBrowserLogic = kea<heatmapsBrowserLogicType>([stopTrackingLoading: () => false,},],- iframeBanner: [+ loadTimeoutBanner: [null as IFrameBanner | null,{setIframeBanner: (_, { banner }) => banner,@@ -467,6 +568,23 @@ export const heatmapsBrowserLogic = kea<heatmapsBrowserLogicType>([}),selectors({+ // Stale results are ignored so a verdict for a previous URL can't linger after the user edits it.+ currentPagePreflight: [+ (s) => [s.pagePreflight, s.displayUrl],+ (pagePreflight: PagePreflight | null, displayUrl: string | null): PagePreflight | null =>+ pagePreflight?.url === displayUrl ? pagePreflight : null,+ ],+ preflightMessage: [+ (s) => [s.currentPagePreflight],+ (currentPagePreflight: PagePreflight | null): string | null => preflightBannerMessage(currentPagePreflight),+ ],+ // Derived rather than pushed into loadTimeoutBanner, because stopTrackingLoading nulls that+ // banner as soon as the iframe fires onload, which a blocked frame does immediately.+ iframeBanner: [+ (s) => [s.preflightMessage, s.loadTimeoutBanner],+ (preflightMessage: string | null, loadTimeoutBanner: IFrameBanner | null): IFrameBanner | null =>+ preflightMessage ? { level: 'error', message: preflightMessage } : loadTimeoutBanner,+ ],browserUrlSearchOptions: [(s) => [s.browserSearchResults, s.topUrls, s.browserSearchTerm],(@@ -649,7 +767,9 @@ export const heatmapsBrowserLogic = kea<heatmapsBrowserLogicType>([posthog.capture('in-app heatmap load failed')actions.setIframeBanner({level: 'error',- message: 'The heatmap failed to load (or is very slow).',+ message:+ 'The live preview did not load, or is very slow. If this page is public, use a ' ++ 'screenshot instead. If it needs a login, pick a session recording below.',})}, 7500)return () => clearTimeout(timerId)diff --git a/frontend/src/scenes/heatmaps/scenes/heatmap/HeatmapNewScene.tsx b/frontend/src/scenes/heatmaps/scenes/heatmap/HeatmapNewScene.tsxindex a27cb54d5ef9..480b0b1cfa49 100644--- a/frontend/src/scenes/heatmaps/scenes/heatmap/HeatmapNewScene.tsx+++ b/frontend/src/scenes/heatmaps/scenes/heatmap/HeatmapNewScene.tsx@@ -263,7 +263,7 @@ function PublicBackgroundChoice(): JSX.Element {const logic = heatmapLogic({ id: 'new' })const { type } = useValues(logic)const { setType } = useActions(logic)- const { isDisplayUrlAuthorized, authorizationDisabledReason } = useValues(heatmapCreationLogic)+ const { isDisplayUrlAuthorized, authorizationDisabledReason, preflightMessage } = useValues(heatmapCreationLogic)const { authorizeDisplayUrl } = useActions(heatmapCreationLogic)const { currentTeamLoading } = useValues(teamLogic)@@ -315,6 +315,15 @@ function PublicBackgroundChoice(): JSX.Element {</LemonBanner>) : null}+ {type === 'iframe' && preflightMessage ? (+ <LemonBanner+ type="error"+ action={{ children: 'Switch to screenshot', onClick: () => setType('screenshot') }}+ >+ {preflightMessage}+ </LemonBanner>+ ) : null}+{type === 'screenshot' ? (<HeatmapAdvancedSettingsdataUrlPlaceholderFallback=""diff --git a/frontend/src/scenes/heatmaps/scenes/heatmap/heatmapCreationLogic.ts b/frontend/src/scenes/heatmaps/scenes/heatmap/heatmapCreationLogic.tsindex 7fe601977340..2105d1773265 100644--- a/frontend/src/scenes/heatmaps/scenes/heatmap/heatmapCreationLogic.ts+++ b/frontend/src/scenes/heatmaps/scenes/heatmap/heatmapCreationLogic.ts@@ -36,6 +36,7 @@ import { savedPrewarmCreate } from 'products/web_analytics/frontend/generated/apimport type { TeamPublicType, TeamType } from '../../../../types'import type { SessionPlayerModalContext } from '../../../session-recordings/player/modal/sessionPlayerModalLogic'+import type { PagePreflight } from '../../components/heatmapsBrowserLogic'import { HeatmapCreationContext, heatmapLogic } from './heatmapLogic'export type HeatmapCreationStep = 'page' | 'background' | 'review'@@ -193,6 +194,8 @@ export interface heatmapCreationLogicValues {isDisplayUrlValid: boolean // heatmapLogicloading: boolean // heatmapLogictype: HeatmapType // heatmapLogic+ currentPagePreflight: PagePreflight | null // heatmapsBrowserLogic+ preflightMessage: string | null // heatmapsBrowserLogicmodalContext: SessionPlayerModalContext // sessionPlayerModalLogiccurrentTeam: TeamPublicType | TeamType | null // teamLogicanalyticsBackgroundType: HeatmapType | 'recording'@@ -239,6 +242,22 @@ export interface heatmapCreationLogicActions {setType: (type: HeatmapType) => {type: HeatmapType} // heatmapLogic+ checkPagePreflight: (url: string | null) => {+ url: string | null+ } // heatmapsBrowserLogic+ checkPagePreflightSuccess: (+ pagePreflight: PagePreflight | null,+ payload?:+ | {+ url: string | null+ }+ | undefined+ ) => {+ pagePreflight: PagePreflight | null+ payload?: {+ url: string | null+ }+ } // heatmapsBrowserLogicsetReplayIframeData: (replayIframeData: ReplayIframeData | null) => {replayIframeData: ReplayIframeData | null} // heatmapsBrowserLogic@@ -387,6 +406,8 @@ export const heatmapCreationLogic = kea<heatmapCreationLogicType>([['modalContext'],featureFlagLogic,['featureFlags'],+ heatmapsBrowserLogic,+ ['currentPagePreflight', 'preflightMessage'],],actions: [heatmapLogic({ id: 'new' }),@@ -394,7 +415,7 @@ export const heatmapCreationLogic = kea<heatmapCreationLogicType>([authorizedUrlsLogic,['addUrl'],heatmapsBrowserLogic,- ['setReplayIframeData'],+ ['setReplayIframeData', 'checkPagePreflight', 'checkPagePreflightSuccess'],sessionPlayerModalLogic,['completeHeatmapBackgroundSelection'],],@@ -668,6 +689,22 @@ export const heatmapCreationLogic = kea<heatmapCreationLogicType>([actions.setType('screenshot')}},+ setType: ({ type }) => {+ if (type === 'iframe') {+ actions.checkPagePreflight(values.displayUrl)+ }+ },+ checkPagePreflightSuccess: () => {+ const preflight = values.currentPagePreflight+ if (!preflight) {+ return+ }+ posthog.capture('in-app heatmap creation framing checked', {+ framing: preflight.framing,+ blocked_by: preflight.blocked_by,+ http_status: preflight.http_status,+ })+ },resetForPageChange: () => {actions.setType('screenshot')},diff --git a/frontend/src/scenes/heatmaps/scenes/heatmap/heatmapLogic.ts b/frontend/src/scenes/heatmaps/scenes/heatmap/heatmapLogic.tsindex 14bfdb8aa255..2a58d3135fe5 100644--- a/frontend/src/scenes/heatmaps/scenes/heatmap/heatmapLogic.ts+++ b/frontend/src/scenes/heatmaps/scenes/heatmap/heatmapLogic.ts@@ -150,6 +150,9 @@ export interface heatmapLogicActions {setWindowWidthOverride: (widthOverride: number | null) => {widthOverride: number | null} // heatmapDataLogic+ checkPagePreflight: (url: string | null) => {+ url: string | null+ } // heatmapsBrowserLogiconIframeLoad: () => {value: true} // heatmapsBrowserLogic@@ -290,7 +293,7 @@ export const heatmapLogic = kea<heatmapLogicType>([],actions: [heatmapsBrowserLogic,- ['setDataUrl', 'setDisplayUrl', 'onIframeLoad', 'setDataUrlUserTouched'],+ ['setDataUrl', 'setDisplayUrl', 'onIframeLoad', 'setDataUrlUserTouched', 'checkPagePreflight'],heatmapsSceneLogic,['loadSavedHeatmaps'],heatmapDataLogic({ context: 'in-app' }),@@ -407,6 +410,8 @@ export const heatmapLogic = kea<heatmapLogicType>([actions.setScreenshotError(null)actions.pollScreenshotStatus(desiredWidth)}+ } else if (item.type === 'iframe') {+ actions.checkPagePreflight(item.url)}} finally {actions.setLoading(false)diff --git a/posthog/rate_limit.py b/posthog/rate_limit.pyindex c79920f4a88a..ae753fa31d77 100644--- a/posthog/rate_limit.py+++ b/posthog/rate_limit.py@@ -480,20 +480,16 @@ class CopyFlagsSustainedRateThrottle(PersonalApiKeyOrUserRateThrottle):rate = "300/hour"-# The batch session-context endpoint computes experiment context for up to 20 recordings per-# call, in up to several per-day ClickHouse scan sets — heavier than most ClickHouse endpoints-# — and its primary caller is the session-authenticated replay/experiment UI, which the-# ClickHouse*RateThrottle pair deliberately does not cover. PersonalApiKeyOrUserRateThrottle-# applies regardless of auth method. The UI fires at most one prefetch per user action (page-# load, filter change — debounced client-side — or recording open), and repeats hit the-# server-side cache, so these rates clear a whole project's worth of concurrent viewers while-# capping a scripted loop of cold batches.-class _SessionContextsRateThrottleBase(PersonalApiKeyOrUserRateThrottle):+class _TeamBucketRateThrottle(PersonalApiKeyOrUserRateThrottle):+ """One bucket per project regardless of auth method, for endpoints whose cost has to be capped+ project-wide rather than per credential.++ The parent idents personal-API-key requests by key hash, so each key a user mints would+ otherwise get its own full budget of whatever the endpoint spends. Same reasoning as+ ProjectSecretApiKeyTeamRateThrottle's team-wide bucket.+ """+def get_cache_key(self, request: "Request", view: "APIView") -> str:- # One bucket per project regardless of auth method. The parent idents personal-API-key- # requests by key hash, so each minted key would get its own budget of this expensive- # compute — the sum must be capped project-wide instead, the same reasoning as- # ProjectSecretApiKeyTeamRateThrottle's team-wide bucket.team_id = self.safely_get_team_id_from_view(view)if team_id is not None:ident = team_id@@ -504,12 +500,35 @@ class _SessionContextsRateThrottleBase(PersonalApiKeyOrUserRateThrottle):return self.cache_format % {"scope": self.scope, "ident": ident}-class SessionContextsBurstRateThrottle(_SessionContextsRateThrottleBase):+# The heatmap page pre-flight makes one outbound fetch of a caller-supplied page per uncached probe,+# holding a web worker for as long as that page takes to answer, so its budget is about worker+# occupancy rather than about protecting our own datastores. A legitimate caller needs one probe per+# heatmap view or per capture-method switch in the wizard, and settled verdicts are cached, so these+# rates clear a team's worth of concurrent viewers while capping a scripted loop of cold probes.+class HeatmapPreflightBurstRateThrottle(_TeamBucketRateThrottle):+ scope = "heatmap_preflight_burst"+ rate = "30/minute"+++class HeatmapPreflightSustainedRateThrottle(_TeamBucketRateThrottle):+ scope = "heatmap_preflight_sustained"+ rate = "300/hour"+++# The batch session-context endpoint computes experiment context for up to 20 recordings per+# call, in up to several per-day ClickHouse scan sets — heavier than most ClickHouse endpoints+# — and its primary caller is the session-authenticated replay/experiment UI, which the+# ClickHouse*RateThrottle pair deliberately does not cover. PersonalApiKeyOrUserRateThrottle+# applies regardless of auth method. The UI fires at most one prefetch per user action (page+# load, filter change — debounced client-side — or recording open), and repeats hit the+# server-side cache, so these rates clear a whole project's worth of concurrent viewers while+# capping a scripted loop of cold batches.+class SessionContextsBurstRateThrottle(_TeamBucketRateThrottle):scope = "session_contexts_burst"rate = "60/minute"-class SessionContextsSustainedRateThrottle(_SessionContextsRateThrottleBase):+class SessionContextsSustainedRateThrottle(_TeamBucketRateThrottle):scope = "session_contexts_sustained"rate = "600/hour"diff --git a/posthog/security/pinned_requests.py b/posthog/security/pinned_requests.pyindex 5ba7fd9138b0..e2b2f6ae4832 100644--- a/posthog/security/pinned_requests.py+++ b/posthog/security/pinned_requests.py@@ -6,6 +6,8 @@ so a rebinding DNS record can pass validation and still connect internally.``PinnedIPAdapter`` closes that window by connecting to the exact IPs that werevalidated, and ``pinned_request`` packages the validate → pin → send sequencefor callers that make one-shot requests to externally controlled URLs.+``pinned_session`` exposes the same sequence for callers that need to stream a+response, which requires the session to outlive the request call.Redirects are never followed automatically — a redirect target has not beenvalidated. Callers that need to follow one must re-enter ``pinned_request``@@ -14,6 +16,8 @@ with the new URL so every hop is validated and pinned.import ipaddressimport urllib.parse as urlparse+from collections.abc import Iterator+from contextlib import contextmanagerimport idnaimport requests@@ -146,19 +150,15 @@ class PinnedIPAdapter(HTTPAdapter):conn.conn_kw["server_hostname"] = original # ty: ignore[invalid-assignment]-def pinned_request(- method: str,- url: str,- *,- timeout: float | tuple[float, float],- headers: dict[str, str] | None = None,- json: object | None = None,-) -> requests.Response:- """Send one SSRF-validated HTTP request over a connection pinned to the validated IPs.+@contextmanager+def pinned_session(url: str) -> Iterator[requests.Session]:+ """Yield a session whose connections are pinned to ``url``'s validated IPs.- Never follows redirects. Raises ``SSRFBlockedError`` when the URL fails- validation and lets ``requests.RequestException`` propagate on transport- failures.+ Raises ``SSRFBlockedError`` when the URL fails validation. Callers own the+ request and must pass ``allow_redirects=False`` — a redirect target has not+ been validated, so following one must re-enter this helper. Prefer+ ``pinned_request`` unless you need to stream the response, which requires the+ session to outlive the call."""allowed, reason, pinned_ips = validate_url_and_pin_ips(url)if not allowed:@@ -174,6 +174,24 @@ def pinned_request(session.mount("http://", adapter) # nosemgrep: request-session-with-httpsession.mount("https://", adapter)try:- return session.request(method, url, headers=headers, json=json, timeout=timeout, allow_redirects=False)+ yield sessionfinally:session.close()+++def pinned_request(+ method: str,+ url: str,+ *,+ timeout: float | tuple[float, float],+ headers: dict[str, str] | None = None,+ json: object | None = None,+) -> requests.Response:+ """Send one SSRF-validated HTTP request over a connection pinned to the validated IPs.++ Never follows redirects. Raises ``SSRFBlockedError`` when the URL fails+ validation and lets ``requests.RequestException`` propagate on transport+ failures.+ """+ with pinned_session(url) as session:+ return session.request(method, url, headers=headers, json=json, timeout=timeout, allow_redirects=False)diff --git a/posthog/security/url_validation.py b/posthog/security/url_validation.pyindex 55608a48ef52..965b41e8afea 100644--- a/posthog/security/url_validation.py+++ b/posthog/security/url_validation.py@@ -168,6 +168,22 @@ def has_authority_bypass_chars(url: str) -> bool:return False+def strip_userinfo(url: str) -> str:+ """+ Remove `user:pass@` from the authority. Userinfo in URLs is a known SSRF+ smuggling vector (some libraries interpret it as the host when stricter+ parsers don't), and a customer-supplied URL can carry a credential or a+ signed token that must not reach an outbound request or a log line.+ """+ parsed = urlparse.urlparse(url)+ if parsed.username is None and parsed.password is None:+ return url+ netloc = parsed.hostname or ""+ if parsed.port:+ netloc = f"{netloc}:{parsed.port}"+ return urlparse.urlunparse(parsed._replace(netloc=netloc))++def _dev_bypass_enabled() -> bool:"""Dev mode short-circuits is_url_allowed.diff --git a/products/business_knowledge/backend/url_fetch.py b/products/business_knowledge/backend/url_fetch.pyindex 078cadea136b..863215e56408 100644--- a/products/business_knowledge/backend/url_fetch.py+++ b/products/business_knowledge/backend/url_fetch.py@@ -23,7 +23,7 @@ import requestsimport structlogfrom posthog.security.pinned_requests import PinnedIPAdapter-from posthog.security.url_validation import validate_url_and_pin_ips+from posthog.security.url_validation import strip_userinfo, validate_url_and_pin_ipsfrom .constants import URL_CONNECT_TIMEOUT, URL_MAX_BYTES, URL_MAX_REDIRECTS, URL_READ_TIMEOUT, URL_USER_AGENT@@ -43,22 +43,6 @@ class FetchResult:final_url: str-def strip_userinfo(url: str) -> str:- """- Remove `user:pass@` from authority. Userinfo in URLs is a known SSRF- smuggling vector (some libraries interpret it as the host when stricter- parsers don't).- """-- parsed = urlparse.urlparse(url)- if parsed.username is None and parsed.password is None:- return url- netloc = parsed.hostname or ""- if parsed.port:- netloc = f"{netloc}:{parsed.port}"- return urlparse.urlunparse(parsed._replace(netloc=netloc))--def normalize_url(raw: str) -> str:"""Canonicalize a user-submitted URL before validating or storing it.diff --git a/products/web_analytics/backend/api/heatmaps_api.py b/products/web_analytics/backend/api/heatmaps_api.pyindex 792470af571b..53cea1ce295f 100644--- a/products/web_analytics/backend/api/heatmaps_api.py+++ b/products/web_analytics/backend/api/heatmaps_api.py@@ -1,6 +1,6 @@from datetime import date, datetime, timedeltafrom json import JSONDecodeError, loads-from typing import Any, List, Literal, cast # noqa: UP035+from typing import Any, List, Literal, cast, get_args # noqa: UP035from django.core.exceptions import FieldErrorfrom django.db import transaction@@ -30,6 +30,7 @@ from posthog.hogql.parser import parse_expr, parse_selectfrom posthog.hogql.query import execute_hogql_queryfrom posthog.api.forbid_destroy_model import ForbidDestroyModel+from posthog.api.mixins import ValidatedRequest, validated_requestfrom posthog.api.routing import TeamAndOrgViewSetMixinfrom posthog.api.shared import UserBasicSerializerfrom posthog.api.utils import action@@ -44,9 +45,11 @@ from posthog.rate_limit import (AISustainedRateThrottle,ClickHouseBurstRateThrottle,ClickHouseSustainedRateThrottle,+ HeatmapPreflightBurstRateThrottle,+ HeatmapPreflightSustainedRateThrottle,)from posthog.rbac.access_control_api_mixin import AccessControlViewSetMixin-from posthog.rbac.user_access_control import UserAccessControlSerializerMixin+from posthog.rbac.user_access_control import AccessControlLevel, UserAccessControlSerializerMixinfrom posthog.security.url_validation import is_url_allowedfrom posthog.utils import relative_date_parse_with_delta_mapping@@ -56,7 +59,9 @@ from products.web_analytics.backend.api.heatmaps_utils import (MAX_TARGET_WIDTHS,PREWARM_PREVIEW_WIDTH,PREWARM_TTL,+ heatmaps_flag_enabled,)+from products.web_analytics.backend.heatmap_preflight import BlockedBy, Framing, preflight_pagefrom products.web_analytics.backend.models import HeatmapSnapshot, SavedHeatmapfrom products.web_analytics.backend.tasks.heatmap_screenshot import generate_heatmap_screenshot@@ -74,24 +79,12 @@ HEATMAP_CONTENT_REQUESTS = Counter(def _heatmaps_cohort_filter_enabled(user: User, team: Team) -> bool:- distinct_id = getattr(user, "distinct_id", None)- if not distinct_id:- return False- try:- return bool(- posthoganalytics.feature_enabled(- HEATMAPS_COHORT_FILTER_FLAG,- str(distinct_id),- groups={"organization": str(team.organization_id), "project": str(team.id)},- group_properties={- "organization": {"id": str(team.organization_id)},- "project": {"id": str(team.id)},- },- send_feature_flag_events=False,- )- )- except Exception:- return False+ return heatmaps_flag_enabled(+ HEATMAPS_COHORT_FILTER_FLAG,+ str(getattr(user, "distinct_id", "") or ""),+ team_id=team.id,+ organization_id=str(team.organization_id),+ )DEFAULT_QUERY = """@@ -1099,24 +1092,67 @@ class HeatmapPrewarmRequestSerializer(serializers.Serializer):return validate_page_url(value)-class HeatmapPrewarmResourceAccessPermission(BasePermission):- message = "You do not have editor access to this resource."+class HeatmapPreflightRequestSerializer(serializers.Serializer):+ url = serializers.CharField(+ help_text="Exact page URL to probe. Wildcards are not allowed. This is the URL that would be loaded in the "+ "live preview iframe, not the data URL used to look up heatmap events."+ )++ def validate_url(self, value: str) -> str:+ return validate_page_url(value)+++class HeatmapPreflightResponseSerializer(serializers.Serializer):+ framing = serializers.ChoiceField(+ choices=list(get_args(Framing)),+ help_text="Whether the page can be embedded in the live preview iframe. 'blocked' means the site's own "+ "headers forbid it, so only a screenshot or session recording background can work. 'unknown' means we "+ "could not tell, for example because the page was unreachable or redirected.",+ )+ blocked_by = serializers.ChoiceField(+ choices=list(get_args(BlockedBy)),+ allow_null=True,+ help_text="Which response header forbids embedding, when framing is 'blocked'. Null otherwise.",+ )+ http_status = serializers.IntegerField(+ allow_null=True,+ help_text="HTTP status the page returned to us. A 4xx or 5xx here points at the customer's host or CDN "+ "rather than at PostHog. Null when the page could not be reached at all.",+ )+ body_excerpt = serializers.CharField(+ allow_null=True,+ help_text="Short whitespace-collapsed excerpt of the response body, only present for non-2xx responses, so "+ "the user can see what their host returned. Truncated.",+ )+++# AccessControlPermission lets a collection action through on a grant over any single heatmap, which+# for an action that spends something on a caller-supplied URL rather than reading one heatmap is not+# the boundary we want. These two need resource-level access to the whole kind instead.+_RESOURCE_LEVEL_ACTIONS: dict[str, AccessControlLevel] = {"prewarm": "editor", "preflight": "viewer"}++class HeatmapResourceAccessPermission(BasePermission):def has_permission(self, request: request.Request, view: APIView) -> bool:saved_heatmap_view = cast("SavedHeatmapViewSet", view)- if saved_heatmap_view.action != "prewarm" or is_service_auth(request):+ required_level = _RESOURCE_LEVEL_ACTIONS.get(saved_heatmap_view.action or "")+ if required_level is None or is_service_auth(request):return True- return saved_heatmap_view.user_access_control.check_access_level_for_resource(- "heatmap", required_level="editor"- )+ if not saved_heatmap_view.user_access_control.check_access_level_for_resource(+ "heatmap", required_level=required_level+ ):+ self.message = f"You do not have {required_level} access to this resource."+ return False++ return Trueclass SavedHeatmapViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixin, ForbidDestroyModel, viewsets.GenericViewSet):scope_object = "heatmap"- permission_classes = [HeatmapPrewarmResourceAccessPermission]+ permission_classes = [HeatmapResourceAccessPermission]throttle_classes = [ClickHouseBurstRateThrottle, ClickHouseSustainedRateThrottle]serializer_class = HeatmapScreenshotResponseSerializerqueryset = SavedHeatmap.objects.all()@@ -1129,6 +1165,9 @@ class SavedHeatmapViewSet(if self.action in ("create", "prewarm"):# More restrictive rate limiting for expensive screenshot generationreturn [AIBurstRateThrottle(), AISustainedRateThrottle()]+ if self.action == "preflight":+ # One outbound page fetch per uncached probe, blocking a web worker while it runs.+ return [HeatmapPreflightBurstRateThrottle(), HeatmapPreflightSustainedRateThrottle()]return super().get_throttles()def safely_get_queryset(self, queryset):@@ -1366,6 +1405,24 @@ class SavedHeatmapViewSet(response_serializer = HeatmapScreenshotResponseSerializer(obj, context=self.get_serializer_context())return response.Response(response_serializer.data, status=status.HTTP_200_OK)+ @validated_request(+ request_serializer=HeatmapPreflightRequestSerializer,+ responses={200: OpenApiResponse(response=HeatmapPreflightResponseSerializer)},+ summary="Check whether a page can back a heatmap",+ description="Fetch a page URL server-side and report whether it allows being embedded in the live preview "+ "iframe, plus the HTTP status it returned. The live preview loads the customer's site directly in their "+ "browser, so a site that sends X-Frame-Options or a restrictive frame-ancestors will never render, and a "+ "4xx or 5xx from the site's own host or CDN leaves an empty frame with no explanation. This endpoint makes "+ "both cases explainable. The fetch comes from PostHog's own network rather than from the screenshot "+ "renderer, so a host that varies its response by IP or user agent can answer this differently than it "+ "answers a screenshot render. Settled verdicts are cached briefly, so repeat checks for the same URL do "+ "not refetch it.",+ )+ @action(methods=["POST"], detail=False, required_scopes=["heatmap:read"])+ def preflight(self, request: ValidatedRequest, *args: Any, **kwargs: Any) -> response.Response:+ result = preflight_page(request.validated_data["url"])+ return response.Response(HeatmapPreflightResponseSerializer(result).data, status=status.HTTP_200_OK)+def _regenerate(self, obj: SavedHeatmap) -> None:obj.status = SavedHeatmap.Status.PROCESSINGobj.exception = Nonediff --git a/products/web_analytics/backend/api/heatmaps_utils.py b/products/web_analytics/backend/api/heatmaps_utils.pyindex 58332e23e5ea..fe3e800e84ec 100644--- a/products/web_analytics/backend/api/heatmaps_utils.py+++ b/products/web_analytics/backend/api/heatmaps_utils.py@@ -1,5 +1,7 @@from datetime import timedelta+import posthoganalytics+DEFAULT_TARGET_WIDTHS = [320, 375, 425, 768, 1024, 1440, 1920]# Each width is one screenshot render (one Browserless session on the cloud path), so cap how many a# single heatmap can fan out to.@@ -7,3 +9,22 @@ MAX_TARGET_WIDTHS = 16PREWARM_PREVIEW_WIDTH = 1024PREWARM_TTL = timedelta(minutes=15)+++def heatmaps_flag_enabled(flag: str, distinct_id: str, *, team_id: int, organization_id: str) -> bool:+ """Evaluate a flag with the org/project group context, failing closed when it can't be read."""+ if not distinct_id:+ return False+ groups = {"organization": organization_id, "project": str(team_id)}+ try:+ return bool(+ posthoganalytics.feature_enabled(+ flag,+ distinct_id,+ groups=groups,+ group_properties={key: {"id": value} for key, value in groups.items()},+ send_feature_flag_events=False,+ )+ )+ except Exception:+ return Falsediff --git a/products/web_analytics/backend/heatmap_preflight.py b/products/web_analytics/backend/heatmap_preflight.pynew file mode 100644index 000000000000..9ded6a6e8108--- /dev/null+++ b/products/web_analytics/backend/heatmap_preflight.py@@ -0,0 +1,215 @@+import re+import time+from dataclasses import dataclass+from hashlib import sha256+from typing import Literal+from urllib.parse import SplitResult, urljoin, urlsplit++from django.conf import settings+from django.core.cache import cache++import requests+import structlog++from posthog.security.pinned_requests import SSRFBlockedError, pinned_session+from posthog.security.url_validation import strip_userinfo++logger = structlog.get_logger(__name__)++Framing = Literal["allowed", "blocked", "unknown"]+BlockedBy = Literal["x_frame_options", "frame_ancestors"]++PREFLIGHT_CONNECT_TIMEOUT_SECONDS = 5.0+PREFLIGHT_READ_TIMEOUT_SECONDS = 10.0+PREFLIGHT_TOTAL_BUDGET_SECONDS = 15.0+# Only a short excerpt is ever used, so cap the read far below anything that could pressure a web worker.+PREFLIGHT_MAX_BODY_BYTES = 64 * 1024+BODY_EXCERPT_MAX_CHARS = 200+PREFLIGHT_CACHE_TTL_SECONDS = 300+PREFLIGHT_MAX_REDIRECTS = 5++_FRAME_ANCESTORS_RE = re.compile(r"(?:^|;)\s*frame-ancestors\s+([^;]+)", re.IGNORECASE)+_SCHEME_SOURCE_RE = re.compile(r"^[a-z][a-z0-9+.\-]*:$")+_DEFAULT_PORTS = {"http": 80, "https": 443}+_REDIRECT_STATUSES = frozenset({301, 302, 303, 307, 308})+++@dataclass(frozen=True)+class PreflightResult:+ framing: Framing+ blocked_by: BlockedBy | None+ http_status: int | None+ body_excerpt: str | None+++# Carries no status on purpose: the UI reads a status as the host's own answer about the page, and+# a status from a hop that never resolved into a page is not that.+_INCONCLUSIVE = PreflightResult("unknown", None, None, None)+++def _effective_port(parts: SplitResult, scheme: str) -> int | None:+ try:+ port = parts.port+ except ValueError:+ return None+ return port or _DEFAULT_PORTS.get(scheme)+++def _origin_parts(origin: str) -> tuple[str, str, int | None]:+ parts = urlsplit(origin)+ scheme = parts.scheme.lower()+ return scheme, (parts.hostname or "").lower(), _effective_port(parts, scheme)+++def _source_matches_origin(source: str, scheme: str, host: str, port: int | None) -> bool:+ source = source.strip().lower()+ # Keyword sources are quoted ('none', 'self', 'unsafe-inline'). None of them can name the app,+ # which is always a different origin than the customer's site.+ if source.startswith("'") or source.startswith('"'):+ return False+ if not source:+ return False+ if source == "*":+ return True+ # A scheme-source ("https:") allows every origin on that scheme.+ if _SCHEME_SOURCE_RE.match(source):+ return source[:-1] == scheme++ any_port = source.endswith(":*")+ authority = source[:-2] if any_port else source+ candidate = urlsplit(authority if "//" in authority else f"//{authority}")+ source_host = (candidate.hostname or "").lower()+ source_scheme = (candidate.scheme or "").lower()+ if not source_host:+ return False+ if source_scheme and source_scheme != scheme:+ return False+ # A source with no port means that scheme's default port, so one naming a different port is a+ # different origin to the browser even when the host matches.+ if not any_port and _effective_port(candidate, source_scheme or scheme) != port:+ return False++ if source_host.startswith("*."):+ return host == source_host[2:] or host.endswith(f".{source_host[2:]}")+ return host == source_host+++def _frame_ancestors_verdict(directive: str, scheme: str, host: str, port: int | None) -> Framing:+ sources = directive.split()+ if not sources:+ return "unknown"+ return "allowed" if any(_source_matches_origin(s, scheme, host, port) for s in sources) else "blocked"+++def analyze_framing_headers(headers: dict[str, str]) -> tuple[Framing, BlockedBy | None]:+ """Decide whether the PostHog app may embed a page in an iframe, from its response headers."""+ scheme, host, port = _origin_parts(settings.SITE_URL)+ lowered = {k.lower(): v for k, v in headers.items()}++ # CSP frame-ancestors supersedes X-Frame-Options wherever both are present. A response can carry+ # more than one policy, either comma-separated or as repeated headers that requests joins the+ # same way, and each applies on its own, so any one of them blocking is decisive.+ csp = lowered.get("content-security-policy")+ if csp:+ verdicts: list[Framing] = []+ for policy in csp.split(","):+ match = _FRAME_ANCESTORS_RE.search(policy)+ if match:+ verdicts.append(_frame_ancestors_verdict(match.group(1), scheme, host, port))+ if "blocked" in verdicts:+ return "blocked", "frame_ancestors"+ if verdicts:+ return ("allowed", None) if all(v == "allowed" for v in verdicts) else ("unknown", None)++ # Neither DENY nor SAMEORIGIN can ever name the app. ALLOW-FROM is not handled because no+ # browser we support ever implemented it, and an unrecognized value is ignored by browsers,+ # so it tells us nothing.+ xfo = lowered.get("x-frame-options", "").strip().lower()+ if xfo in ("deny", "sameorigin"):+ return "blocked", "x_frame_options"++ return "allowed", None+++def _body_excerpt(response: requests.Response, deadline: float) -> str | None:+ # The read timeout bounds the gap between chunks, not the total transfer, so a host that+ # trickles bytes indefinitely would otherwise hold a web worker and grow unboundedly.+ chunks: list[bytes] = []+ total = 0+ for chunk in response.iter_content(chunk_size=4096):+ chunks.append(chunk)+ total += len(chunk)+ if total >= PREFLIGHT_MAX_BODY_BYTES or time.monotonic() > deadline:+ break+ text = b"".join(chunks)[:PREFLIGHT_MAX_BODY_BYTES].decode(response.encoding or "utf-8", errors="replace")+ return " ".join(text[:BODY_EXCERPT_MAX_CHARS].split()) or None+++def _probe(url: str) -> PreflightResult:+ # One budget for the whole chain, so following a redirect can't multiply how long a web worker+ # is held.+ deadline = time.monotonic() + PREFLIGHT_TOTAL_BUDGET_SECONDS+ current = url++ for _ in range(PREFLIGHT_MAX_REDIRECTS + 1):+ read_timeout = min(PREFLIGHT_READ_TIMEOUT_SECONDS, deadline - time.monotonic())+ if read_timeout <= 0:+ return _INCONCLUSIVE+ try:+ with pinned_session(current) as session:+ res = session.request(+ "GET",+ current,+ timeout=(PREFLIGHT_CONNECT_TIMEOUT_SECONDS, read_timeout),+ allow_redirects=False,+ stream=True,+ )+ if 200 <= res.status_code < 300:+ framing, blocked_by = analyze_framing_headers(dict(res.headers))+ return PreflightResult(framing, blocked_by, res.status_code, None)++ if res.status_code in _REDIRECT_STATUSES:+ location = res.headers.get("location")+ if not location:+ return _INCONCLUSIVE+ # An iframe follows redirects too, so the page that decides framing is the one+ # at the end of the chain, and reporting the 3xx instead would accuse a healthy+ # host of failing. Re-entering pinned_session per hop is what keeps every target+ # SSRF-validated and pinned to the address it was validated against.+ current = strip_userinfo(urljoin(current, location))+ continue++ # The headers on any other non-2xx belong to the host's error response rather than+ # to the page, so they say nothing about framing either way. The status is the+ # answer worth reporting.+ return PreflightResult("unknown", None, res.status_code, _body_excerpt(res, deadline))+ except SSRFBlockedError as e:+ logger.info("heatmap_preflight.url_blocked", reason=str(e))+ return _INCONCLUSIVE+ except requests.RequestException:+ # Deliberately not logging the exception or the URL: both routinely echo the full target,+ # and a customer-supplied URL can carry credentials or a signed token.+ logger.info("heatmap_preflight.request_failed")+ return _INCONCLUSIVE++ return _INCONCLUSIVE+++def preflight_page(url: str) -> PreflightResult:+ """Explain why a page can't back a live-preview heatmap.++ Never raises for a remote-side problem: an unreachable or hostile host is an answer, not an+ error, so callers always get a verdict to show the user. Settled verdicts are cached briefly so+ repeat checks for the same page don't refetch it; an inconclusive one isn't, so a transient+ failure can be retried.+ """+ url = strip_userinfo(url)+ cache_key = f"heatmap_preflight:{sha256(url.encode()).hexdigest()}"+ cached = cache.get(cache_key)+ if isinstance(cached, PreflightResult):+ return cached++ result = _probe(url)+ if result.framing != "unknown":+ cache.set(cache_key, result, PREFLIGHT_CACHE_TTL_SECONDS)+ return resultdiff --git a/products/web_analytics/backend/tasks/heatmap_screenshot.py b/products/web_analytics/backend/tasks/heatmap_screenshot.pyindex a36aae02603f..cd465fd788e0 100644--- a/products/web_analytics/backend/tasks/heatmap_screenshot.py+++ b/products/web_analytics/backend/tasks/heatmap_screenshot.py@@ -77,6 +77,10 @@ class BrowserlessPermanentError(BrowserlessError):"""A failure that will not be fixed by retrying (4xx, misconfiguration, oversized output)."""+class PageHttpStatusError(BrowserlessPermanentError):+ """The customer's page answered the render with a non-2xx, so the capture is a picture of that."""++def _width_bucket(width: int) -> str:if width < 500:return "mobile"@@ -90,6 +94,8 @@ def _width_bucket(width: int) -> str:def _classify_failure(e: BaseException) -> str:if isinstance(e, SoftTimeLimitExceeded):return "soft_time_limit"+ if isinstance(e, PageHttpStatusError):+ return "page_http_status"if isinstance(e, BrowserlessError):if e.cause == "not_configured":return "not_configured"@@ -363,7 +369,20 @@ def _validate_screenshot_response(response: requests.Response, endpoint_url: strreturn content-def _browserless_screenshot(endpoint_url: str, page_url: str, width: int, block_consent_modals: bool) -> bytes:+def _page_status_from(response: requests.Response) -> int | None:+ # Browserless answers 200 with a valid JPEG even when the page it rendered returned 429 or 403,+ # so this header is the only thing separating a heatmap from a picture of the customer's error+ # page. It is documented under Browserless' Request Configuration rather than on the Screenshot+ # API page. Absent or unparseable means we don't know, which must not fail an otherwise fine render.+ try:+ return int(response.headers["x-response-code"])+ except (KeyError, TypeError, ValueError):+ return None+++def _browserless_screenshot(+ endpoint_url: str, page_url: str, width: int, block_consent_modals: bool+) -> tuple[bytes, int | None]:# Render one width via the Browserless /screenshot REST API. viewport.width sets the captured width;# scrollPage triggers lazy-loaded content and blockConsentModals dismisses cookie banners server-side.body: dict[str, object] = {@@ -450,16 +469,18 @@ def _browserless_screenshot(endpoint_url: str, page_url: str, width: int, block_)raise+ page_status = _page_status_from(response)HEATMAP_BROWSERLESS_REQUEST_SECONDS.labels(outcome="ok", width_bucket=width_bucket).observe(elapsed)logger.info("heatmap_screenshot.browserless_request",width=width,browserless_status=status_code,+ page_status=page_status,latency_ms=round(elapsed * 1000),bytes=len(content),outcome="ok",)- return content+ return content, page_statusdef _resolve_widths(screenshot: SavedHeatmap) -> list[int]:@@ -536,12 +557,24 @@ def _generate_browserless_screenshots(screenshot: SavedHeatmap, widths: list[int)count = 0for w in pending:- image_data = _browserless_screenshot(endpoint_url, screenshot.url, w, screenshot.block_consent_modals)+ image_data, page_status = _browserless_screenshot(+ endpoint_url, screenshot.url, w, screenshot.block_consent_modals+ )+ if page_status is not None and not 200 <= page_status < 300:+ raise PageHttpStatusError(+ f"{_host_of(screenshot.url)} returned {page_status} when we loaded the page, so the capture "+ f"is a picture of that response. This comes from the site's host or CDN, not from PostHog.",+ cause="page_http_status",+ )_persist_snapshot(screenshot, w, image_data)count += 1return count+def _host_of(url: str) -> str:+ return urlsplit(url).hostname or "The page"++@shared_task(ignore_result=True, queue=CeleryQueue.EXPORTS.value)@skip_team_scope_auditdef report_stuck_heatmap_screenshots() -> int:diff --git a/products/web_analytics/backend/tasks/test/test_heatmap_screenshot.py b/products/web_analytics/backend/tasks/test/test_heatmap_screenshot.pyindex 6230b48ace1a..4749c190a348 100644--- a/products/web_analytics/backend/tasks/test/test_heatmap_screenshot.py+++ b/products/web_analytics/backend/tasks/test/test_heatmap_screenshot.py@@ -19,6 +19,7 @@ from products.web_analytics.backend.tasks.heatmap_screenshot import (BrowserlessError,BrowserlessPermanentError,BrowserlessTransientError,+ PageHttpStatusError,_browserless_screenshot,_build_browserless_screenshot_url,_classify_failure,@@ -87,6 +88,25 @@ class TestHeatmapScreenshotTask(APIBaseTest):block_consent_modals=block_consent_modals,)+ @override_settings(**BROWSERLESS_SETTINGS)+ @patch("products.web_analytics.backend.tasks.heatmap_screenshot.requests")+ def test_a_captured_error_page_fails_the_heatmap_instead_of_being_stored(self, mock_requests: MagicMock) -> None:+ # The render is a valid JPEG of the host's error page, so without the page status this looked+ # like a healthy heatmap and the user was shown a picture of a 429.+ resp = _make_response(_jpeg(b"err"))+ resp.headers = {"content-type": "image/png", "x-response-code": "429"}+ mock_requests.post.return_value = resp++ heatmap = self._make_heatmap()+ with self.assertRaises(PageHttpStatusError):+ generate_heatmap_screenshot(heatmap.id)++ heatmap.refresh_from_db()+ assert heatmap.status == SavedHeatmap.Status.FAILED+ assert "429" in (heatmap.exception or "")+ assert "example.com" in (heatmap.exception or "")+ assert not HeatmapSnapshot.objects.filter(heatmap=heatmap).exists()+@parameterized.expand([("blocking_on", True), ("blocking_off", False)])@override_settings(**BROWSERLESS_SETTINGS, HEATMAP_BROWSERLESS_BLOCK_ADS=False)@patch("products.web_analytics.backend.tasks.heatmap_screenshot.requests")@@ -246,6 +266,32 @@ class TestHeatmapScreenshotTask(APIBaseTest):# Pure-function tests for the Browserless REST helper — no DB, so they run on SimpleTestCase.class TestBrowserlessScreenshotRequest(SimpleTestCase):+ @parameterized.expand(+ [+ ("rate_limited", {"x-response-code": "429"}, 429),+ ("healthy", {"x-response-code": "200"}, 200),+ ("header_absent", {}, None),+ ("header_unparseable", {"x-response-code": "nope"}, None),+ ]+ )+ @override_settings(**BROWSERLESS_SETTINGS)+ @patch("products.web_analytics.backend.tasks.heatmap_screenshot.requests")+ def test_reports_the_pages_own_status_from_the_response_header(+ self, _name: str, headers: dict[str, str], expected: int | None, mock_requests: MagicMock+ ) -> None:+ # Browserless answers 200 with a valid JPEG even when the page it rendered returned 429, so+ # this header is the only thing that distinguishes a heatmap from a picture of an error page.+ resp = _make_response(_jpeg(b"img"))+ resp.headers = {"content-type": "image/png", **headers}+ mock_requests.post.return_value = resp++ content, page_status = _browserless_screenshot(+ "https://host/screenshot?token=t", "https://ex.com", 1024, block_consent_modals=False+ )++ assert content == _jpeg(b"img")+ assert page_status == expected+@parameterized.expand([("desktop", 1024, False), ("mobile", 320, True)])@override_settings(HEATMAP_BROWSERLESS_TIMEOUT_MS=180000,@@ -258,7 +304,7 @@ class TestBrowserlessScreenshotRequest(SimpleTestCase):) -> None:mock_requests.post.return_value = _make_response(_jpeg(b"img"))- content = _browserless_screenshot(+ content, _ = _browserless_screenshot("https://host/screenshot?token=t", "https://example.com", width, block_consent_modals=True)@@ -447,6 +493,7 @@ class TestClassifyFailure(SimpleTestCase):("http_429", BrowserlessTransientError("x", status_code=429, cause="http_status"), "browserless_4xx"),("http_404", BrowserlessPermanentError("x", status_code=404, cause="http_status"), "browserless_4xx"),("http_503", BrowserlessTransientError("x", status_code=503, cause="http_status"), "browserless_5xx"),+ ("page_http_status", PageHttpStatusError("x", cause="page_http_status"), "page_http_status"),("unknown", ValueError("x"), "unknown"),])diff --git a/products/web_analytics/backend/test/test_heatmap_access_control.py b/products/web_analytics/backend/test/test_heatmap_access_control.pyindex 7c4f9c8fd057..aa61427be149 100644--- a/products/web_analytics/backend/test/test_heatmap_access_control.py+++ b/products/web_analytics/backend/test/test_heatmap_access_control.py@@ -15,6 +15,7 @@ from posthog.models.organization import OrganizationMembershipfrom posthog.models.user import Userfrom posthog.rbac.user_access_control import ACCESS_CONTROL_RESOURCES, model_to_resource+from products.web_analytics.backend.heatmap_preflight import PreflightResultfrom products.web_analytics.backend.models import SavedHeatmapfrom products.web_analytics.backend.test.test_heatmaps_api import INSERT_SINGLE_HEATMAP_EVENT@@ -172,6 +173,32 @@ class TestHeatmapAccessControl(ClickhouseTestMixin, APIBaseTest):else:mock_task.assert_called_once()+ @parameterized.expand(+ [+ ("object_viewer", True, status.HTTP_403_FORBIDDEN),+ ("resource_viewer", False, status.HTTP_200_OK),+ ]+ )+ @patch("products.web_analytics.backend.api.heatmaps_api.preflight_page")+ def test_preflight_requires_resource_viewer_access(+ self, _name: str, object_grant: bool, expected_status: int, mock_preflight: MagicMock+ ) -> None:+ mock_preflight.return_value = PreflightResult("allowed", None, 200, None)+ self._create_project_default(access_level="none")+ self._create_access_control(+ self.viewer_user,+ resource_id=str(self.heatmap.id) if object_grant else None,+ access_level="viewer",+ )+ self.client.force_login(self.viewer_user)++ response = self.client.post(+ self._list_url() + "preflight/", data={"url": "https://example.com/probed"}, format="json"+ )++ self.assertEqual(response.status_code, expected_status, response.json())+ self.assertEqual(mock_preflight.called, not object_grant)+def test_creator_list_filters_out_object_blocked_heatmap(self):# Creator sees their own heatmap; an object-level "none" on another user's heatmap excludes it.other_user = User.objects.create_and_join(self.organization, "[email protected]", "testtest")diff --git a/products/web_analytics/backend/test/test_heatmap_preflight.py b/products/web_analytics/backend/test/test_heatmap_preflight.pynew file mode 100644index 000000000000..2f03a9b79abb--- /dev/null+++ b/products/web_analytics/backend/test/test_heatmap_preflight.py@@ -0,0 +1,251 @@+from io import BytesIO++from unittest.mock import patch++from django.test import SimpleTestCase, override_settings++import requests+from parameterized import parameterized++from posthog.security.pinned_requests import SSRFBlockedError++from products.web_analytics.backend.heatmap_preflight import (+ PREFLIGHT_MAX_REDIRECTS,+ PreflightResult,+ analyze_framing_headers,+ preflight_page,+)++APP_ORIGIN = "https://us.posthog.com"+++@override_settings(SITE_URL=APP_ORIGIN)+class TestFramingHeaderAnalysis(SimpleTestCase):+ @parameterized.expand(+ [+ # Some sites send frame-ancestors 'none' alongside X-Frame-Options: DENY. The CSP is the+ # operative one; reporting this as allowed is the false negative that makes the failure+ # look like ours.+ (+ "csp_frame_ancestors_none_wins_over_xfo",+ {+ "x-frame-options": "DENY",+ "content-security-policy": "block-all-mixed-content; frame-ancestors 'none'; upgrade-insecure-requests;",+ },+ "blocked",+ "frame_ancestors",+ ),+ # A host that names the app in frame-ancestors. XFO is still DENY here, but browsers ignore XFO+ # when frame-ancestors is present, so treating XFO as decisive would wrongly warn on a working setup.+ (+ "csp_allowing_app_wins_over_xfo_deny",+ {"x-frame-options": "DENY", "content-security-policy": "frame-ancestors 'self' *.posthog.com"},+ "allowed",+ None,+ ),+ ("xfo_deny", {"x-frame-options": "DENY"}, "blocked", "x_frame_options"),+ ("xfo_sameorigin_is_not_us", {"x-frame-options": "SAMEORIGIN"}, "blocked", "x_frame_options"),+ # No browser we support implements ALLOW-FROM, and browsers ignore values they don't+ # recognize, so an unrecognized value must not produce a warning.+ ("xfo_unrecognized_value_is_ignored", {"x-frame-options": "ALLOWALL"}, "allowed", None),+ ("no_framing_headers", {}, "allowed", None),+ ("csp_wildcard", {"content-security-policy": "frame-ancestors *"}, "allowed", None),+ (+ "csp_exact_origin",+ {"content-security-policy": "frame-ancestors https://us.posthog.com"},+ "allowed",+ None,+ ),+ (+ "csp_scheme_mismatch",+ {"content-security-policy": "frame-ancestors http://us.posthog.com"},+ "blocked",+ "frame_ancestors",+ ),+ (+ "csp_only_other_site",+ {"content-security-policy": "frame-ancestors https://example.com"},+ "blocked",+ "frame_ancestors",+ ),+ (+ "csp_without_frame_ancestors_falls_back_to_xfo",+ {"content-security-policy": "default-src 'self'", "x-frame-options": "DENY"},+ "blocked",+ "x_frame_options",+ ),+ ("header_casing_is_ignored", {"X-Frame-Options": "deny"}, "blocked", "x_frame_options"),+ # Port is part of the origin the browser compares, so a source naming a different one+ # does not permit the app even though the host matches.+ (+ "csp_non_default_port_is_a_different_origin",+ {"content-security-policy": "frame-ancestors https://us.posthog.com:8443"},+ "blocked",+ "frame_ancestors",+ ),+ (+ "csp_spelled_out_default_port",+ {"content-security-policy": "frame-ancestors https://us.posthog.com:443"},+ "allowed",+ None,+ ),+ (+ "csp_wildcard_port",+ {"content-security-policy": "frame-ancestors https://us.posthog.com:*"},+ "allowed",+ None,+ ),+ # A scheme-source permits every origin on that scheme, so reading it as a hostname is+ # the false alarm that tells a customer their site blocks us when it doesn't.+ (+ "csp_scheme_source",+ {"content-security-policy": "frame-ancestors https:"},+ "allowed",+ None,+ ),+ # Several policies each apply on their own, so the strictest decides. requests joins+ # repeated headers with a comma exactly like a multi-policy header value.+ (+ "csp_strictest_of_several_policies_wins",+ {"content-security-policy": "frame-ancestors *, frame-ancestors 'none'"},+ "blocked",+ "frame_ancestors",+ ),+ ]+ )+ def test_framing_verdict(self, _name, headers, expected_framing, expected_blocked_by):+ assert analyze_framing_headers(headers) == (expected_framing, expected_blocked_by)+++@override_settings(SITE_URL=APP_ORIGIN)+class TestPreflightPage(SimpleTestCase):+ def setUp(self):+ super().setUp()+ cache_patch = patch("products.web_analytics.backend.heatmap_preflight.cache")+ self.mock_cache = cache_patch.start()+ self.mock_cache.get.return_value = None+ self.addCleanup(cache_patch.stop)++ @staticmethod+ def _response(status_code: int, headers: dict[str, str], body: str = "") -> requests.Response:+ res = requests.Response()+ res.status_code = status_code+ res.headers.update(headers)+ # The body is streamed, so it has to come off `raw` rather than the cached `_content`.+ res.raw = BytesIO(body.encode())+ return res++ @patch("products.web_analytics.backend.heatmap_preflight.pinned_session")+ def test_non_2xx_reports_status_not_a_framing_verdict(self, mock_session):+ # The 429 body a customer's edge actually returned. Its headers describe the rate limiter, not+ # the page, so claiming "embedding allowed" here would send the user hunting the wrong problem.+ mock_session.return_value.__enter__.return_value.request.return_value = self._response(+ 429, {}, "local_rate_limited"+ )++ result = preflight_page("https://example.com/page")++ assert result.framing == "unknown"+ assert result.http_status == 429+ assert result.body_excerpt == "local_rate_limited"+ self.mock_cache.set.assert_not_called()++ @parameterized.expand(+ [+ ("absolute_location", "https://www.example.com/final", "https://www.example.com/final"),+ ("relative_location", "/final", "https://example.com/final"),+ ]+ )+ @patch("products.web_analytics.backend.heatmap_preflight.pinned_session")+ def test_the_verdict_comes_from_the_page_at_the_end_of_the_chain(self, _name, location, expected_hop, mock_session):+ # http->https, apex->www and trailing-slash redirects are how a healthy public page+ # normally answers. An iframe follows them, so stopping at the 3xx and reporting it would+ # accuse the customer's host of failing when nothing is wrong.+ request = mock_session.return_value.__enter__.return_value.request+ request.side_effect = [+ self._response(301, {"location": location}),+ self._response(200, {"x-frame-options": "DENY"}),+ ]++ result = preflight_page("https://example.com/page")++ assert result == PreflightResult("blocked", "x_frame_options", 200, None)+ # Every hop re-enters pinned_session, which is what validates and pins each target.+ assert [call.args[0] for call in mock_session.call_args_list] == ["https://example.com/page", expected_hop]++ @patch("products.web_analytics.backend.heatmap_preflight.pinned_session")+ def test_a_chain_that_never_settles_reports_no_status(self, mock_session):+ request = mock_session.return_value.__enter__.return_value.request+ request.side_effect = lambda *args, **kwargs: self._response(302, {"location": "https://example.com/again"})++ result = preflight_page("https://example.com/page")++ # No status, because the UI reads one as the host's answer about the page and a loop never+ # produced a page.+ assert result == PreflightResult("unknown", None, None, None)+ assert request.call_count == PREFLIGHT_MAX_REDIRECTS + 1++ @patch("products.web_analytics.backend.heatmap_preflight.pinned_session")+ def test_a_redirect_into_a_blocked_address_is_not_followed(self, mock_session):+ # The first hop is a public URL that passes validation; the second points inside. Validating+ # per hop is the only thing standing between a caller-supplied URL and an internal address.+ mock_session.return_value.__enter__.return_value.request.return_value = self._response(+ 302, {"location": "http://169.254.169.254/latest/meta-data/"}+ )+ mock_session.side_effect = [mock_session.return_value, SSRFBlockedError("Private IP")]++ result = preflight_page("https://example.com/page")++ assert result == PreflightResult("unknown", None, None, None)++ @patch("products.web_analytics.backend.heatmap_preflight.pinned_session")+ def test_unreachable_host_is_a_verdict_not_an_exception(self, mock_session):+ mock_session.return_value.__enter__.return_value.request.side_effect = requests.ConnectionError("boom")++ result = preflight_page("https://example.com/page")++ assert result.framing == "unknown"+ assert result.http_status is None++ @patch("products.web_analytics.backend.heatmap_preflight.pinned_session")+ def test_a_body_that_never_ends_is_capped(self, mock_session):+ # requests' read timeout bounds the gap between chunks, not the total transfer, so an+ # endless trickle would otherwise grow a web worker without bound.+ def endless_chunks(chunk_size: int = 4096):+ while True:+ yield b"x" * chunk_size++ res = requests.Response()+ res.status_code = 503+ mock_session.return_value.__enter__.return_value.request.return_value = res+ with patch.object(requests.Response, "iter_content", side_effect=endless_chunks):+ result = preflight_page("https://example.com/page")++ assert result.http_status == 503+ assert result.body_excerpt is not None+ assert len(result.body_excerpt) <= 200++ @patch("products.web_analytics.backend.heatmap_preflight.pinned_session")+ def test_a_settled_verdict_is_cached_and_not_refetched(self, mock_session):+ request = mock_session.return_value.__enter__.return_value.request+ request.return_value = self._response(200, {"content-security-policy": "frame-ancestors 'none'"})++ first = preflight_page("https://example.com/page")+ assert first.framing == "blocked"+ assert first.blocked_by == "frame_ancestors"++ self.mock_cache.get.return_value = first+ assert preflight_page("https://example.com/page") == first+ request.assert_called_once()++ @patch("products.web_analytics.backend.heatmap_preflight.pinned_session")+ def test_credentials_never_reach_the_outbound_request(self, mock_session):+ # A customer-supplied URL can carry a signed token or basic-auth pair; it must not reach+ # the outbound request or any log line.+ request = mock_session.return_value.__enter__.return_value.request+ request.return_value = self._response(200, {})++ preflight_page("https://user:[email protected]:8443/page")++ mock_session.assert_called_once_with("https://example.com:8443/page")+ assert request.call_args.args[1] == "https://example.com:8443/page"diff --git a/products/web_analytics/backend/test/test_heatmap_screenshots.py b/products/web_analytics/backend/test/test_heatmap_screenshots.pyindex 810dfcc07e77..65f88ba56442 100644--- a/products/web_analytics/backend/test/test_heatmap_screenshots.py+++ b/products/web_analytics/backend/test/test_heatmap_screenshots.py@@ -11,7 +11,11 @@ from rest_framework.test import APIClientfrom posthog.jwt import PosthogJwtAudience, encode_jwtfrom posthog.models import Team+from posthog.models.personal_api_key import PersonalAPIKey+from posthog.models.utils import generate_random_token_personal, hash_key_value+from posthog.rate_limit import HeatmapPreflightBurstRateThrottle+from products.web_analytics.backend.heatmap_preflight import PreflightResultfrom products.web_analytics.backend.models import HeatmapSnapshot, SavedHeatmap@@ -57,6 +61,62 @@ class TestHeatmapsAPI(APIBaseTest):saved = SavedHeatmap.objects.get(id=resp.data["id"])self.assertTrue(saved.block_consent_modals)+ @patch("products.web_analytics.backend.api.heatmaps_api.preflight_page")+ def test_preflight_returns_the_verdict_for_the_requested_url(self, mock_preflight):+ mock_preflight.return_value = PreflightResult(+ framing="blocked",+ blocked_by="frame_ancestors",+ http_status=200,+ body_excerpt=None,+ )++ resp = self.client.post(+ f"/api/environments/{self.team.id}/saved/preflight/",+ {"url": "https://example.com/page"},+ )++ self.assertEqual(resp.status_code, 200)+ self.assertEqual(resp.data["framing"], "blocked")+ self.assertEqual(resp.data["blocked_by"], "frame_ancestors")+ mock_preflight.assert_called_once_with("https://example.com/page")++ def test_preflight_rejects_a_wildcard_url(self):+ resp = self.client.post(+ f"/api/environments/{self.team.id}/saved/preflight/",+ {"url": "https://example.com/*"},+ )++ self.assertEqual(resp.status_code, 400)++ @patch("products.web_analytics.backend.api.heatmaps_api.preflight_page")+ @patch("posthog.rate_limit.is_rate_limit_enabled", return_value=True)+ def test_preflight_budget_is_shared_across_personal_api_keys(self, _enabled, mock_preflight):+ # Each probe holds a web worker for as long as the target takes to answer. The default+ # cache key idents personal-API-key requests by key hash, so a user could mint keys to+ # multiply that occupancy; the budget has to be one project-wide bucket.+ mock_preflight.return_value = PreflightResult(+ framing="allowed", blocked_by=None, http_status=200, body_excerpt=None+ )+ self.client.logout()++ def post_with_a_fresh_key():+ token = generate_random_token_personal()+ PersonalAPIKey.objects.create(+ user=self.user, label="t", secure_value=hash_key_value(token), scopes=["heatmap:read"]+ )+ return self.client.post(+ f"/api/projects/{self.team.id}/saved/preflight/",+ {"url": "https://example.com/page"},+ headers={"authorization": f"Bearer {token}"},+ )++ with patch.object(HeatmapPreflightBurstRateThrottle, "rate", "2/minute"):+ self.assertEqual(post_with_a_fresh_key().status_code, 200)+ self.assertEqual(post_with_a_fresh_key().status_code, 200)+ throttled = post_with_a_fresh_key()++ self.assertEqual(throttled.status_code, 429)+@patch("products.web_analytics.backend.tasks.heatmap_screenshot.generate_heatmap_screenshot.delay")def test_prewarm_starts_single_width_render_hidden_from_list(self, mock_delay):resp = self.client.post(diff --git a/products/web_analytics/frontend/generated/api.schemas.ts b/products/web_analytics/frontend/generated/api.schemas.tsindex a78b6a910748..1cb1aa91e131 100644--- a/products/web_analytics/frontend/generated/api.schemas.ts+++ b/products/web_analytics/frontend/generated/api.schemas.ts@@ -283,6 +283,59 @@ export interface PatchedSavedHeatmapRequestApi {block_consent_modals?: boolean}+export interface HeatmapPreflightRequestApi {+ /** Exact page URL to probe. Wildcards are not allowed. This is the URL that would be loaded in the live preview iframe, not the data URL used to look up heatmap events. */+ url: string+}++/**+ * * `allowed` - allowed+ * * `blocked` - blocked+ * * `unknown` - unknown+ */+export type FramingEnumApi = (typeof FramingEnumApi)[keyof typeof FramingEnumApi]++export const FramingEnumApi = {+ Allowed: 'allowed',+ Blocked: 'blocked',+ Unknown: 'unknown',+} as const++/**+ * * `x_frame_options` - x_frame_options+ * * `frame_ancestors` - frame_ancestors+ */+export type BlockedByEnumApi = (typeof BlockedByEnumApi)[keyof typeof BlockedByEnumApi]++export const BlockedByEnumApi = {+ XFrameOptions: 'x_frame_options',+ FrameAncestors: 'frame_ancestors',+} as const++export interface HeatmapPreflightResponseApi {+ /** Whether the page can be embedded in the live preview iframe. 'blocked' means the site's own headers forbid it, so only a screenshot or session recording background can work. 'unknown' means we could not tell, for example because the page was unreachable or redirected.+ *+ * * `allowed` - allowed+ * * `blocked` - blocked+ * * `unknown` - unknown */+ framing: FramingEnumApi+ /** Which response header forbids embedding, when framing is 'blocked'. Null otherwise.+ *+ * * `x_frame_options` - x_frame_options+ * * `frame_ancestors` - frame_ancestors */+ blocked_by: BlockedByEnumApi | null+ /**+ * HTTP status the page returned to us. A 4xx or 5xx here points at the customer's host or CDN rather than at PostHog. Null when the page could not be reached at all.+ * @nullable+ */+ http_status: number | null+ /**+ * Short whitespace-collapsed excerpt of the response body, only present for non-2xx responses, so the user can see what their host returned. Truncated.+ * @nullable+ */+ body_excerpt: string | null+}+export interface HeatmapPrewarmRequestApi {/** Exact page URL to speculatively render ahead of heatmap creation. Wildcards are not allowed. */url: stringdiff --git a/products/web_analytics/frontend/generated/api.ts b/products/web_analytics/frontend/generated/api.tsindex 915bf6bf926c..0508541dfe4d 100644--- a/products/web_analytics/frontend/generated/api.ts+++ b/products/web_analytics/frontend/generated/api.ts@@ -13,6 +13,8 @@ import type {AcknowledgeCelebrationRequestApi,AcknowledgeCelebrationResponseApi,HeatmapEventsResponseApi,+ HeatmapPreflightRequestApi,+ HeatmapPreflightResponseApi,HeatmapPrewarmRequestApi,HeatmapScreenshotResponseApi,HeatmapScreenshotsContentRetrieveParams,@@ -273,6 +275,27 @@ export const savedRegenerateCreate = async (})}+export const getSavedPreflightCreateUrl = (projectId: string) => {+ return `/api/projects/${projectId}/saved/preflight/`+}++/**+ * Fetch a page URL server-side and report whether it allows being embedded in the live preview iframe, plus the HTTP status it returned. The live preview loads the customer's site directly in their browser, so a site that sends X-Frame-Options or a restrictive frame-ancestors will never render, and a 4xx or 5xx from the site's own host or CDN leaves an empty frame with no explanation. This endpoint makes both cases explainable. The fetch comes from PostHog's own network rather than from the screenshot renderer, so a host that varies its response by IP or user agent can answer this differently than it answers a screenshot render. Settled verdicts are cached briefly, so repeat checks for the same URL do not refetch it.+ * @summary Check whether a page can back a heatmap+ */+export const savedPreflightCreate = async (+ projectId: string,+ heatmapPreflightRequestApi: HeatmapPreflightRequestApi,+ options?: RequestInit+): Promise<HeatmapPreflightResponseApi> => {+ return apiMutator<HeatmapPreflightResponseApi>(getSavedPreflightCreateUrl(projectId), {+ ...options,+ method: 'POST',+ headers: { 'Content-Type': 'application/json', ...options?.headers },+ body: JSON.stringify(heatmapPreflightRequestApi),+ })+}+export const getSavedPrewarmCreateUrl = (projectId: string) => {return `/api/projects/${projectId}/saved/prewarm/`}diff --git a/products/web_analytics/frontend/generated/api.zod.ts b/products/web_analytics/frontend/generated/api.zod.tsindex 3cba53d271eb..6aae6852f00e 100644--- a/products/web_analytics/frontend/generated/api.zod.ts+++ b/products/web_analytics/frontend/generated/api.zod.ts@@ -114,6 +114,18 @@ export const SavedPartialUpdateBody = /* @__PURE__ */ zod.object({),})+/**+ * Fetch a page URL server-side and report whether it allows being embedded in the live preview iframe, plus the HTTP status it returned. The live preview loads the customer's site directly in their browser, so a site that sends X-Frame-Options or a restrictive frame-ancestors will never render, and a 4xx or 5xx from the site's own host or CDN leaves an empty frame with no explanation. This endpoint makes both cases explainable. The fetch comes from PostHog's own network rather than from the screenshot renderer, so a host that varies its response by IP or user agent can answer this differently than it answers a screenshot render. Settled verdicts are cached briefly, so repeat checks for the same URL do not refetch it.+ * @summary Check whether a page can back a heatmap+ */+export const SavedPreflightCreateBody = /* @__PURE__ */ zod.object({+ url: zod+ .string()+ .describe(+ 'Exact page URL to probe. Wildcards are not allowed. This is the URL that would be loaded in the live preview iframe, not the data URL used to look up heatmap events.'+ ),+})+/*** Speculatively render a screenshot for a page URL ahead of heatmap creation, so it's ready (or closer to ready) by the time the user reaches the generation screen. Renders a single preview width. Idempotent within a short window: returns the existing in-flight or completed prewarm render for the same URL and consent setting if one exists (200), otherwise starts a new one (201). The result is reused when a heatmap is later created for the same URL.*/diff --git a/products/web_analytics/mcp/tools.yaml b/products/web_analytics/mcp/tools.yamlindex d8911f70feb2..a8f58242b452 100644--- a/products/web_analytics/mcp/tools.yaml+++ b/products/web_analytics/mcp/tools.yaml@@ -141,6 +141,9 @@ tools:saved-destroy:operation: saved_destroyenabled: false+ saved-preflight-create:+ operation: saved_preflight_create+ enabled: falsesaved-prewarm-create:operation: saved_prewarm_createenabled: falsediff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex aba7032fbc30..347cf0cfa844 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -12201,6 +12201,18 @@ export namespace Schemas {dedupe_key?: DedupeKeyEnum | null;}+ /**+ * * `x_frame_options` - x_frame_options+ * * `frame_ancestors` - frame_ancestors+ */+ export type BlockedByEnum = typeof BlockedByEnum[keyof typeof BlockedByEnum];+++ export const BlockedByEnum = {+ XFrameOptions: 'x_frame_options',+ FrameAncestors: 'frame_ancestors',+ } as const;+export interface BooleanScoreDefinitionConfig {/** Optional label for a true value. */true_label?: string;@@ -32882,6 +32894,20 @@ export namespace Schemas {deleted: boolean;}+ /**+ * * `allowed` - allowed+ * * `blocked` - blocked+ * * `unknown` - unknown+ */+ export type FramingEnum = typeof FramingEnum[keyof typeof FramingEnum];+++ export const FramingEnum = {+ Allowed: 'allowed',+ Blocked: 'blocked',+ Unknown: 'unknown',+ } as const;+export interface FreshdeskTicketSignalExtra {status: string | null;priority: string | null;@@ -33836,6 +33862,35 @@ export namespace Schemas {median_viewport_height: number | null;}+ export interface HeatmapPreflightRequest {+ /** Exact page URL to probe. Wildcards are not allowed. This is the URL that would be loaded in the live preview iframe, not the data URL used to look up heatmap events. */+ url: string;+ }++ export interface HeatmapPreflightResponse {+ /** Whether the page can be embedded in the live preview iframe. 'blocked' means the site's own headers forbid it, so only a screenshot or session recording background can work. 'unknown' means we could not tell, for example because the page was unreachable or redirected.+ *+ * * `allowed` - allowed+ * * `blocked` - blocked+ * * `unknown` - unknown */+ framing: FramingEnum;+ /** Which response header forbids embedding, when framing is 'blocked'. Null otherwise.+ *+ * * `x_frame_options` - x_frame_options+ * * `frame_ancestors` - frame_ancestors */+ blocked_by: BlockedByEnum | null;+ /**+ * HTTP status the page returned to us. A 4xx or 5xx here points at the customer's host or CDN rather than at PostHog. Null when the page could not be reached at all.+ * @nullable+ */+ http_status: number | null;+ /**+ * Short whitespace-collapsed excerpt of the response body, only present for non-2xx responses, so the user can see what their host returned. Truncated.+ * @nullable+ */+ body_excerpt: string | null;+ }+export interface HeatmapPrewarmRequest {/** Exact page URL to speculatively render ahead of heatmap creation. Wildcards are not allowed. */url: string;