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.

feat(replay): give the player frame its own document behind a flag (#94400)

Tom Piccirellob42fc0f58f05
diff --git a/common/storybook/.storybook/main.ts b/common/storybook/.storybook/main.ts
index a6ade84ce4c2..6826ca9dc3f2 100644
--- a/common/storybook/.storybook/main.ts
+++ b/common/storybook/.storybook/main.ts
@@ -54,6 +54,10 @@ const config: StorybookConfig = {
// story whose play function is still running when it fires.
{ from: '../.workers', to: '/static' },
{ from: '../../../frontend/node_modules/@posthog/hedgehog-mode/assets', to: '/static/hedgehog-mode' },
+ // The replay player mounts rrweb into this document rather than the app's, so a recorded
+ // page is judged against its policy instead of ours. Django renders the same file; serving
+ // it here keeps stories on the real path rather than a Storybook-only stand-in.
+ { from: '../../../posthog/templates/replay_player_frame', to: '/replay_player_frame' },
],
framework: {
diff --git a/common/storybook/.storybook/test-runner.ts b/common/storybook/.storybook/test-runner.ts
index 8ab765649a65..9b054a3653df 100644
--- a/common/storybook/.storybook/test-runner.ts
+++ b/common/storybook/.storybook/test-runner.ts
@@ -106,6 +106,7 @@ declare module 'storybook/internal/types' {
}
const RETRY_TIMES = 2
+const FRAME_SELECTOR_SEPARATOR = ' >>> '
const LOADER_SELECTORS = [
'.Spinner',
'.quill-spinner', // Quill's <Spinner /> — rotates while present, so it must settle before we snapshot
@@ -485,10 +486,10 @@ async function expectStoryToMatchSnapshot(
}
if (typeof waitForSelector === 'string') {
- await page.waitForSelector(waitForSelector, { timeout: waitForSelectorTimeout })
+ await waitForPossiblyFramedSelector(page, waitForSelector, waitForSelectorTimeout)
} else if (Array.isArray(waitForSelector)) {
await Promise.all(
- waitForSelector.map((selector) => page.waitForSelector(selector, { timeout: waitForSelectorTimeout }))
+ waitForSelector.map((selector) => waitForPossiblyFramedSelector(page, selector, waitForSelectorTimeout))
)
}
@@ -501,6 +502,22 @@ async function expectStoryToMatchSnapshot(
}
}
+/**
+ * Wait for a selector that may live inside a same-origin iframe.
+ *
+ * `page.waitForSelector` does not cross a frame boundary, so a story whose content renders in one
+ * (the session replay player, which mounts rrweb into its own document) writes
+ * `'iframe.Outer >>> .inner'` and gets the frame's own wait instead.
+ */
+async function waitForPossiblyFramedSelector(page: Page, selector: string, timeout: number | undefined): Promise<void> {
+ const [frameSelector, innerSelector] = selector.split(FRAME_SELECTOR_SEPARATOR)
+ if (innerSelector === undefined) {
+ await page.waitForSelector(selector, { timeout })
+ return
+ }
+ await page.frameLocator(frameSelector.trim()).locator(innerSelector.trim()).first().waitFor({ timeout })
+}
+
async function takeSnapshotWithTheme(
page: Page,
context: TestContext,
diff --git a/frontend/src/lib/constants.tsx b/frontend/src/lib/constants.tsx
index b74556d2b0bf..c677d9c85d15 100644
--- a/frontend/src/lib/constants.tsx
+++ b/frontend/src/lib/constants.tsx
@@ -220,6 +220,7 @@ export const FEATURE_FLAGS = {
QUERY_RUNNING_TIME: 'query_running_time', // owner: #team-analytics-platform
REPLAY_HOGQL_FILTERS: 'replay-hogql-filters', // owner: @pauldambra #team-replay
REPLAY_OVERSIZED_RECORDING_GATE: 'replay-oversized-recording-gate', // owner: #team-replay
+ REPLAY_PLAYER_OWN_DOCUMENT: 'replay-player-own-document', // owner: #team-replay
REPLAY_PLAYER_PERSON_SESSIONS_TAB: 'replay-player-person-sessions-tab', // owner: @ksvat #team-replay
REPLAY_SETTINGS_HELP: 'replay-settings-help', // owner: @veryayskiy #team-replay
SCOUTS_MODEL_CONFIG: 'scouts-model-config', // owner: #team-self-driving, gates the per-scout model pin in the inbox scout settings (also checked server-side)
diff --git a/frontend/src/scenes/session-recordings/SessionsRecordings-player-success.stories.tsx b/frontend/src/scenes/session-recordings/SessionsRecordings-player-success.stories.tsx
index 86523dc1872b..9f4712738c0e 100644
--- a/frontend/src/scenes/session-recordings/SessionsRecordings-player-success.stories.tsx
+++ b/frontend/src/scenes/session-recordings/SessionsRecordings-player-success.stories.tsx
@@ -4,6 +4,7 @@ import { Meta, StoryObj } from '@storybook/react'
import { combineUrl, router } from 'kea-router'
import { HttpResponse } from 'msw'
+import { FEATURE_FLAGS } from 'lib/constants'
import { App } from 'scenes/App'
import recordingEventsJson from 'scenes/session-recordings/__mocks__/recording_events_query'
import { recordingMetaJson } from 'scenes/session-recordings/__mocks__/recording_meta'
@@ -96,7 +97,10 @@ const meta: Meta = {
layout: 'fullscreen',
viewMode: 'story',
mockDate: '2023-02-01',
- waitForSelector: '.PlayerFrame__content .replayer-wrapper iframe',
+ // This file covers the REPLAY_PLAYER_OWN_DOCUMENT path, where rrweb mounts inside the
+ // player's own document. The other replay story files stay on the default path.
+ featureFlags: [FEATURE_FLAGS.REPLAY_PLAYER_OWN_DOCUMENT],
+ waitForSelector: 'iframe.PlayerFrame__document >>> .PlayerFrame__content .replayer-wrapper iframe',
pageUrl: urls.replay(),
},
decorators: [
diff --git a/frontend/src/scenes/session-recordings/player/PlayerFrame.scss b/frontend/src/scenes/session-recordings/player/PlayerFrame.scss
index 8af8c7b0eb76..5fd26225cc94 100644
--- a/frontend/src/scenes/session-recordings/player/PlayerFrame.scss
+++ b/frontend/src/scenes/session-recordings/player/PlayerFrame.scss
@@ -14,6 +14,15 @@
touch-action: pan-x pan-y;
}
+ // Under REPLAY_PLAYER_OWN_DOCUMENT the wrapper renders inside this frame's document, which
+ // this stylesheet cannot reach. The rules below are duplicated in
+ // posthog/templates/replay_player_frame/index.html until the flag is removed and this copy goes.
+ .PlayerFrame__document {
+ width: 100%;
+ height: 100%;
+ border: 0;
+ }
+
.PlayerFrame__content--masking-window .replayer-wrapper::before {
position: absolute;
inset: 0; /* Cover the entire wrapper */
diff --git a/frontend/src/scenes/session-recordings/player/PlayerFrame.test.tsx b/frontend/src/scenes/session-recordings/player/PlayerFrame.test.tsx
new file mode 100644
index 000000000000..7efdedd7d5cb
--- /dev/null
+++ b/frontend/src/scenes/session-recordings/player/PlayerFrame.test.tsx
@@ -0,0 +1,70 @@
+import '@testing-library/jest-dom'
+
+import { fireEvent, render } from '@testing-library/react'
+import { BindLogic, Provider } from 'kea'
+import posthog from 'posthog-js'
+
+import { FEATURE_FLAGS } from 'lib/constants'
+import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
+
+import { setupSessionRecordingTest } from './__mocks__/test-setup'
+import { PlayerFrame } from './PlayerFrame'
+import { sessionRecordingPlayerLogic } from './sessionRecordingPlayerLogic'
+
+describe('PlayerFrame', () => {
+ const logicProps = { sessionRecordingId: '1', playerKey: 'player-frame-test' }
+
+ beforeEach(() => {
+ setupSessionRecordingTest()
+ featureFlagLogic.mount()
+ featureFlagLogic.actions.setFeatureFlags([FEATURE_FLAGS.REPLAY_PLAYER_OWN_DOCUMENT], {
+ [FEATURE_FLAGS.REPLAY_PLAYER_OWN_DOCUMENT]: true,
+ })
+ })
+
+ function renderPlayerFrame(): { container: HTMLElement; iframe: HTMLIFrameElement } {
+ const { container } = render(
+ <Provider>
+ <BindLogic logic={sessionRecordingPlayerLogic} props={logicProps}>
+ <PlayerFrame />
+ </BindLogic>
+ </Provider>
+ )
+ const iframe = container.querySelector('iframe.PlayerFrame__document')
+ if (!(iframe instanceof HTMLIFrameElement)) {
+ throw new Error('the flag-on player did not render its frame')
+ }
+ return { container, iframe }
+ }
+
+ it('mounts the player on the frame document once the frame loads', () => {
+ const { iframe } = renderPlayerFrame()
+ const frameDocument = iframe.contentDocument!
+ frameDocument.open()
+ frameDocument.write('<div id="player-frame-content"></div>')
+ frameDocument.close()
+
+ fireEvent.load(iframe)
+
+ expect(sessionRecordingPlayerLogic(logicProps).values.rootFrame).toBe(
+ frameDocument.getElementById('player-frame-content')
+ )
+ // The frame is same-origin, so any script permission added here runs as the app.
+ expect(iframe).toHaveAttribute('sandbox', 'allow-same-origin')
+ })
+
+ // A same-origin error page, a login redirect, or a browser network-error page all fire load
+ // with a document that has no mount node. The player must not stay blank with no report.
+ it('falls back to the app document and reports it when the frame loads without a mount node', () => {
+ const captureSpy = jest.spyOn(posthog, 'captureException')
+ const { container, iframe } = renderPlayerFrame()
+
+ fireEvent.load(iframe)
+
+ expect(container.querySelector('iframe')).toBeNull()
+ const fallback = container.querySelector('div.PlayerFrame__content')
+ expect(fallback).not.toBeNull()
+ expect(sessionRecordingPlayerLogic(logicProps).values.rootFrame).toBe(fallback)
+ expect(captureSpy).toHaveBeenCalledTimes(1)
+ })
+})
diff --git a/frontend/src/scenes/session-recordings/player/PlayerFrame.tsx b/frontend/src/scenes/session-recordings/player/PlayerFrame.tsx
index 16d6572831e0..5ee90a4e5c60 100644
--- a/frontend/src/scenes/session-recordings/player/PlayerFrame.tsx
+++ b/frontend/src/scenes/session-recordings/player/PlayerFrame.tsx
@@ -7,16 +7,33 @@ import { useActions, useValues } from 'kea'
import { Handler, viewportResizeDimension } from 'posthog-js/rrweb-types'
import { useCallback, useEffect, useRef } from 'react'
+import { FEATURE_FLAGS } from 'lib/constants'
+import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
import { getPlayerFrameScale, isIOS } from 'scenes/session-recordings/player/playerFrameScaling'
import { sessionRecordingPlayerLogic } from 'scenes/session-recordings/player/sessionRecordingPlayerLogic'
const BASE_CLICK_INDICATOR_DURATION_S = 1 / 3
+// rrweb builds its replay iframe on about:blank, and a frame on a local scheme inherits its
+// embedder's whole policy, report-uri included. Mounting rrweb inside a real document instead puts
+// that document in the inheritance chain, so a recorded page is judged against its policy rather
+// than the app's. CSPMiddleware supplies it.
+const PLAYER_FRAME_SRC = '/replay_player_frame/index.html'
+const PLAYER_FRAME_CONTENT_ID = 'player-frame-content'
+
export const PlayerFrame = (): JSX.Element => {
const replayDimensionRef = useRef<viewportResizeDimension>()
- const { player, sessionRecordingId, maskingWindow, speed, resolution } = useValues(sessionRecordingPlayerLogic)
- const { setScale, setRootFrame } = useActions(sessionRecordingPlayerLogic)
+ const { player, sessionRecordingId, maskingWindow, speed, resolution, playerFrameDocumentFailed } =
+ useValues(sessionRecordingPlayerLogic)
+ const { setScale, setRootFrame, playerFrameDocumentLoadFailed } = useActions(sessionRecordingPlayerLogic)
+ const { featureFlags } = useValues(featureFlagLogic)
+
+ // A frame that loaded without its mount node falls back to the container below, which is the
+ // flag-off path. That path still works, so the player renders rather than staying blank.
+ const ownDocument = !!featureFlags[FEATURE_FLAGS.REPLAY_PLAYER_OWN_DOCUMENT] && !playerFrameDocumentFailed
+ const iframeRef = useRef<HTMLIFrameElement | null>(null)
+ // rrweb's mount point. Under the flag it lives in the player frame's document, not this one.
const frameRef = useRef<HTMLDivElement | null>(null)
const containerRef = useRef<HTMLDivElement | null>(null)
const containerDimensions = useSize(containerRef)
@@ -35,6 +52,8 @@ export const PlayerFrame = (): JSX.Element => {
replayDimensionRef.current = dimensions
+ // rrweb scales its wrapper to fit the wrapper's parent, so measure that parent rather than
+ // this container. Under the flag the parent is the player frame's body.
const parentDimensions = frameRef.current.parentElement.getBoundingClientRect()
const { scale, transform } = getPlayerFrameScale(parentDimensions, dimensions)
@@ -55,12 +74,49 @@ export const PlayerFrame = (): JSX.Element => {
updatePlayerDimensions(replayDimensionRef.current)
}, [updatePlayerDimensions])
- // Need useEffect to populate replayer on component paint
+ // The app stylesheet cannot reach inside the player frame, so the click duration and the
+ // masking overlay are applied to that document rather than to the container below.
+ const applyFrameStyles = useCallback((): void => {
+ if (!ownDocument) {
+ return
+ }
+ iframeRef.current?.contentDocument?.documentElement?.style?.setProperty(
+ '--player-frame-click-duration',
+ `${BASE_CLICK_INDICATOR_DURATION_S / speed}s`
+ )
+ frameRef.current?.classList?.toggle('PlayerFrame__content--masking-window', !!maskingWindow)
+ }, [ownDocument, speed, maskingWindow])
+
+ const handleFrameLoad = useCallback((): void => {
+ const content = iframeRef.current?.contentDocument?.getElementById(PLAYER_FRAME_CONTENT_ID)
+ if (!content) {
+ // A same-origin error page, a login redirect, and a browser error page all fire load too,
+ // so a load event does not prove the shell document arrived.
+ playerFrameDocumentLoadFailed()
+ return
+ }
+ frameRef.current = content as HTMLDivElement
+ // The frame usually loads after speed and maskingWindow settle, so the effect below has
+ // already run against a document that did not exist yet.
+ applyFrameStyles()
+ setRootFrame(frameRef.current)
+ }, [setRootFrame, applyFrameStyles, playerFrameDocumentLoadFailed])
+
+ // Need useEffect to populate replayer on component paint. Under the flag the frame may still be
+ // loading, in which case handleFrameLoad does this instead.
+ // ownDocument is a dependency because flags resolve after the first paint. A user who holds a
+ // stale enabled flag paints the frame, then React swaps in the container below when the fresh
+ // value arrives, and the replayer must move with it. The fallback after a failed frame load
+ // swaps the same way.
useEffect(() => {
if (frameRef.current) {
setRootFrame(frameRef.current)
}
- }, [sessionRecordingId, setRootFrame])
+ }, [sessionRecordingId, ownDocument, setRootFrame])
+
+ useEffect(() => {
+ applyFrameStyles()
+ }, [applyFrameStyles])
// Recalculate the player size when the recording changes dimensions
useEffect(() => {
@@ -95,10 +151,22 @@ export const PlayerFrame = (): JSX.Element => {
} as React.CSSProperties
}
>
- <div
- className={clsx('PlayerFrame__content', maskingWindow && 'PlayerFrame__content--masking-window')}
- ref={frameRef}
- />
+ {ownDocument ? (
+ <iframe
+ ref={iframeRef}
+ className="PlayerFrame__document"
+ src={PLAYER_FRAME_SRC}
+ onLoad={handleFrameLoad}
+ title="Session replay player"
+ // Interaction belongs to the app's controls, not the recorded page.
+ sandbox="allow-same-origin"
+ />
+ ) : (
+ <div
+ className={clsx('PlayerFrame__content', maskingWindow && 'PlayerFrame__content--masking-window')}
+ ref={frameRef}
+ />
+ )}
</div>
)
}
diff --git a/frontend/src/scenes/session-recordings/player/sessionRecordingPlayerLogic.ts b/frontend/src/scenes/session-recordings/player/sessionRecordingPlayerLogic.ts
index 519b2adde139..65c52527046a 100644
--- a/frontend/src/scenes/session-recordings/player/sessionRecordingPlayerLogic.ts
+++ b/frontend/src/scenes/session-recordings/player/sessionRecordingPlayerLogic.ts
@@ -627,6 +627,7 @@ export interface sessionRecordingPlayerLogicValues {
playNextRecording: ((automatic: boolean) => void) | undefined
player: Player | null
playerError: string | null
+ playerFrameDocumentFailed: boolean
playerSpeed: number
playingState: SessionPlayerState.PLAY | SessionPlayerState.PAUSE
playingTimeTracking: PlayerTimeTracking
@@ -865,6 +866,9 @@ export interface sessionRecordingPlayerLogicActions {
playerErrorSeen: (error: any) => {
error: any
}
+ playerFrameDocumentLoadFailed: () => {
+ value: true
+ }
restartIframePlayback: () => {
value: true
}
@@ -1271,6 +1275,7 @@ export const sessionRecordingPlayerLogic = kea<sessionRecordingPlayerLogicType>(
incrementClickCount: true,
// the error is emitted from code we don't control in rrweb, so we can't guarantee it's really an Error
playerErrorSeen: (error: any) => ({ error }),
+ playerFrameDocumentLoadFailed: true,
fingerprintReported: (fingerprint: string) => ({ fingerprint }),
setDebugSnapshotTypes: (types: EventType[]) => ({ types }),
setDebugSnapshotIncrementalSources: (incrementalSources: IncrementalSource[]) => ({ incrementalSources }),
@@ -1457,6 +1462,8 @@ export const sessionRecordingPlayerLogic = kea<sessionRecordingPlayerLogicType>(
},
],
isBuffering: [true, { startBuffer: () => true, endBuffer: () => false }],
+ // The frame's src never changes, so a second load never arrives on its own, and nothing resets this.
+ playerFrameDocumentFailed: [false, { playerFrameDocumentLoadFailed: () => true }],
playerError: [
null as string | null,
{
@@ -2112,6 +2119,13 @@ export const sessionRecordingPlayerLogic = kea<sessionRecordingPlayerLogicType>(
actions.setPlay()
}
},
+ playerFrameDocumentLoadFailed: () => {
+ // The player still works from the app document, so the only sign of this is the report.
+ posthog.captureException(new Error('Replay player frame loaded without its mount node'), {
+ feature: 'session-recording-player-frame',
+ sessionRecordingId: props.sessionRecordingId,
+ })
+ },
playerErrorSeen: ({ error }) => {
const fingerprint = encodeURIComponent(error.message + error.filename + error.lineno + error.colno)
if (values.reportedReplayerErrors.has(fingerprint)) {
diff --git a/posthog/middleware.py b/posthog/middleware.py
index beac0d9d5171..937ce4ccb5e9 100644
--- a/posthog/middleware.py
+++ b/posthog/middleware.py
@@ -1157,6 +1157,11 @@ def csp_report_endpoint(**params: str) -> str:
return f"{endpoint}{separator}{urlencode(params)}"
+# The full path, matched exactly. Django sends every unmatched path to the app catch-all, so a
+# prefix match would also hand the app document this policy and stop it from starting.
+REPLAY_PLAYER_FRAME_PATH = "/replay_player_frame/index.html"
+
+
class CSPMiddleware:
def __init__(self, get_response):
self.get_response = get_response
@@ -1174,6 +1179,40 @@ class CSPMiddleware:
response.headers["Content-Security-Policy"] = "default-src 'none'"
return response
+ if request.path == REPLAY_PLAYER_FRAME_PATH:
+ # rrweb's own iframe is on about:blank, and a frame on a local scheme inherits its
+ # parent's policy wholesale. Mounting rrweb inside this document rather than the app's
+ # makes this policy the one a recorded page is judged against.
+ #
+ # Recorded pages load whatever they loaded when recorded, so the media directives are
+ # open on purpose. Scripts are the exception: rrweb sandboxes its frame without
+ # allow-scripts, so nothing recorded ever executes, and 'none' states that rather than
+ # leaving it to the sandbox attribute alone.
+ #
+ # No report-uri: violations here describe a customer's site, not ours.
+ #
+ # frame-ancestors stays open because shared and embedded recordings put the app itself
+ # in a customer's page, which makes this frame's ancestor chain cross-origin. The
+ # document holds no data and cannot be scripted into cross-origin, so framing it
+ # elsewhere yields a blank page.
+ response.headers["Content-Security-Policy"] = "; ".join(
+ [
+ "default-src 'none'",
+ "script-src 'none'",
+ "style-src * 'unsafe-inline' data: blob:",
+ "img-src * data: blob:",
+ "font-src * data: blob:",
+ "media-src * data: blob:",
+ "connect-src *",
+ "frame-src *",
+ "child-src *",
+ "form-action 'none'",
+ "base-uri 'none'",
+ "frame-ancestors *",
+ ]
+ )
+ return response
+
is_admin_view = request.path.startswith("/admin/")
if is_admin_view:
django_loginas_inline_script_hash = "sha256-2bSkJXtgXFhxZUhgXzWsEsKImxJEQsqjns0vi3KiSrI="
@@ -1238,8 +1277,9 @@ class CSPMiddleware:
f"img-src 'self' data: https: {resource_url} https://posthog.com https://www.gravatar.com https://res.cloudinary.com https://platform.slack-edge.com https://raw.githubusercontent.com",
"frame-ancestors https://posthog.com https://preview.posthog.com https://vercel.com",
f"connect-src 'self' https://www.posthogstatus.com {resource_url} {connect_debug_url} https://raw.githubusercontent.com https://api.github.com",
- # allow all sites for displaying heatmaps
- "frame-src https:",
+ # https: lets heatmaps frame a customer's site. 'self' is for the replay player
+ # frame, whose document is same-origin: an http origin does not match https:.
+ "frame-src 'self' https:",
"manifest-src 'self'",
"base-uri 'self'",
# form-action has no default-src fallback, so leaving it unset lets an injected
diff --git a/posthog/templates/replay_player_frame/index.html b/posthog/templates/replay_player_frame/index.html
new file mode 100644
index 000000000000..9e94353a3a6b
--- /dev/null
+++ b/posthog/templates/replay_player_frame/index.html
@@ -0,0 +1,177 @@
+<!DOCTYPE html>
+<html>
+ <head>
+ <meta charset="utf-8">
+ <title>Session replay player</title>
+ <style>
+ /*
+ Copied from PlayerFrame.scss and PlayerFrameLLMHighlight.scss. These rules style the
+ rrweb wrapper, which under REPLAY_PLAYER_OWN_DOCUMENT lives in this document rather than
+ the app's, so the app's stylesheet can no longer reach them. Both copies stay until the
+ flag is removed, at which point the app's copy goes and this one remains.
+ */
+ html, body {
+ width: 100%;
+ height: 100%;
+ margin: 0;
+ padding: 0;
+ overflow: hidden;
+ background: transparent;
+ }
+
+ .PlayerFrame__content {
+ position: absolute;
+
+ /* Center the frame so a letterboxed or not-yet-scaled recording sits in the
+ middle of the player rather than pinned to the top-left corner. */
+ top: 50%;
+ left: 50%;
+ transform: translate(-50%, -50%);
+ }
+
+ .PlayerFrame__content--masking-window .replayer-wrapper::before {
+ position: absolute;
+ inset: 0; /* Cover the entire wrapper */
+ z-index: 10; /* Ensure it's above the iframe */
+ pointer-events: auto; /* Block interactions */
+ content: '';
+ background-image: url('data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMTYiIGhlaWdodD0iMTYiIHZpZXdCb3g9IjAgMCAxNiAxNiIgZmlsbD0ibm9uZSIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj4KPHJlY3Qgd2lkdGg9IjE2IiBoZWlnaHQ9IjE2IiBmaWxsPSJibGFjayIvPgo8cGF0aCBkPSJNOCAwSDE2TDAgMTZWOEw4IDBaIiBmaWxsPSIjMkQyRDJEIi8+CjxwYXRoIGQ9Ik0xNiA4VjE2SDhMMTYgOFoiIGZpbGw9IiMyRDJEMkQiLz4KPC9zdmc+Cg==');
+ background-repeat: repeat;
+ background-size: 16px 16px;
+ }
+
+ .PlayerFrame__content iframe {
+ background-color: white;
+ border: 0;
+ }
+
+ /* Copied over from rrweb replay css */
+ .PlayerFrame__content .replayer-wrapper {
+ position: relative;
+ }
+
+ .PlayerFrame__content .replayer-mouse {
+ position: absolute;
+ width: 20px;
+ height: 20px;
+ background-image: url('data:image/svg+xml;base64,PHN2ZyBoZWlnaHQ9JzMwMHB4JyB3aWR0aD0nMzAwcHgnICBmaWxsPSIjMDAwMDAwIiB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIGRhdGEtbmFtZT0iTGF5ZXIgMSIgdmlld0JveD0iMCAwIDUwIDUwIiB4PSIwcHgiIHk9IjBweCI+PHRpdGxlPkRlc2lnbl90bnA8L3RpdGxlPjxwYXRoIGQ9Ik00OC43MSw0Mi45MUwzNC4wOCwyOC4yOSw0NC4zMywxOEExLDEsMCwwLDAsNDQsMTYuMzlMMi4zNSwxLjA2QTEsMSwwLDAsMCwxLjA2LDIuMzVMMTYuMzksNDRhMSwxLDAsMCwwLDEuNjUuMzZMMjguMjksMzQuMDgsNDIuOTEsNDguNzFhMSwxLDAsMCwwLDEuNDEsMGw0LjM4LTQuMzhBMSwxLDAsMCwwLDQ4LjcxLDQyLjkxWm0tNS4wOSwzLjY3TDI5LDMyYTEsMSwwLDAsMC0xLjQxLDBsLTkuODUsOS44NUwzLjY5LDMuNjlsMzguMTIsMTRMMzIsMjcuNThBMSwxLDAsMCwwLDMyLDI5TDQ2LjU5LDQzLjYyWiI+PC9wYXRoPjwvc3ZnPg==');
+ background-repeat: no-repeat;
+ background-position: center center;
+ background-size: contain;
+ border-color: transparent; /* otherwise we transition from black when .touch-device class is added */
+ transition:
+ left 0.05s linear,
+ top 0.05s linear;
+ }
+
+ .PlayerFrame__content .replayer-mouse::after {
+ display: inline-block;
+ width: 20px;
+ height: 20px;
+ content: '';
+ background: rgb(73 80 246);
+ border-radius: 100%;
+ opacity: 0.3;
+ transform: translate(-50%, -50%);
+ }
+
+ .PlayerFrame__content .replayer-mouse.touch-device {
+ width: 70px;
+ height: 70px;
+ margin-top: -37px;
+ margin-left: -37px;
+ background-image: none; /* there's no passive cursor on touch-only screens */
+ border-color: rgb(73 80 246 / 0%);
+ border-style: solid;
+ border-width: 4px;
+ border-radius: 100%;
+ transition:
+ left 0s linear,
+ top 0s linear,
+ border-color 0.2s ease-in-out;
+ }
+
+ .PlayerFrame__content .replayer-mouse.touch-device.touch-active {
+ border-color: rgb(73 80 246 / 100%);
+ transition:
+ left 0.25s linear,
+ top 0.25s linear,
+ border-color 0.2s ease-in-out;
+ }
+
+ .PlayerFrame__content .replayer-mouse.touch-device::after {
+ opacity: 0; /* there's no passive cursor on touch-only screens */
+ }
+
+ .PlayerFrame__content .replayer-mouse-tail {
+ position: absolute;
+ pointer-events: none;
+ }
+
+ /*
+ The click highlight was conditional on a `.PlayerFrame--llm-highlight` class on the app-side
+ container. The app sets that class unconditionally, so the rules apply unconditionally here.
+ */
+ .PlayerFrame__content .replayer-mouse.active::after {
+ /* Duration scales with playback speed; the app sets the property on this document. */
+ animation: PlayerFrame__click--llm-highlight var(--player-frame-click-duration, 0.333s) ease-in-out 1;
+ }
+
+ .PlayerFrame__content .replayer-mouse.touch-device.active::after {
+ animation: PlayerFrame__touch-click--llm-highlight var(--player-frame-click-duration, 0.333s) ease-in-out 1;
+ }
+
+ /* Desktop. Magenta stays visible against most UI. */
+ @keyframes PlayerFrame__click--llm-highlight {
+ 0% {
+ width: 60px;
+ height: 60px;
+ background: rgb(236 72 153);
+ opacity: 0.8;
+ }
+
+ /* Shrink unevenly to keep the highlight visible as long as possible */
+ 80% {
+ width: 40px;
+ height: 40px;
+ background: rgb(236 72 153);
+ opacity: 0.8;
+ }
+
+ 100% {
+ width: 20px;
+ height: 20px;
+ background: rgb(236 72 153);
+ opacity: 0.3;
+ }
+ }
+
+ /* Mobile. Touch devices have no passive cursor, so fade to invisible. */
+ @keyframes PlayerFrame__touch-click--llm-highlight {
+ 0% {
+ width: 60px;
+ height: 60px;
+ background: rgb(236 72 153);
+ opacity: 0.8;
+ }
+
+ 80% {
+ width: 40px;
+ height: 40px;
+ background: rgb(236 72 153);
+ opacity: 0.8;
+ }
+
+ 100% {
+ width: 40px;
+ height: 40px;
+ background: rgb(236 72 153);
+ opacity: 0;
+ }
+ }
+ </style>
+ </head>
+ <body>
+ <div class="PlayerFrame__content" id="player-frame-content"></div>
+ </body>
+</html>
diff --git a/posthog/test/test_middleware.py b/posthog/test/test_middleware.py
index 60c7eb244d46..d6fdb5d01a04 100644
--- a/posthog/test/test_middleware.py
+++ b/posthog/test/test_middleware.py
@@ -1890,14 +1890,51 @@ class TestActivityLoggingMiddleware(APIBaseTest):
class TestCSPMiddleware(APIBaseTest):
+ def test_replay_player_frame_carries_its_own_policy_and_reports_nothing(self):
+ # The frame exists so a recorded page stops being judged against the app policy. If the
+ # middleware branch goes, it silently inherits that policy again, along with its report-uri,
+ # and every replayed page resumes reporting a customer's site to our project.
+ response = self.client.get("/replay_player_frame/index.html")
+ assert response.status_code == 200
+ policy = response["Content-Security-Policy"]
+ assert "script-src 'none'" in policy
+ assert "img-src * data: blob:" in policy
+ assert "report-uri" not in policy
+ assert "Content-Security-Policy-Report-Only" not in response
+ assert "Reporting-Endpoints" not in response
+
+ def test_app_policy_allows_framing_the_replay_player_frame(self):
+ # The player frame is same-origin, and an http origin does not match the https: source
+ # that heatmaps need.
+ response = self.client.get("/")
+ assert "frame-src 'self' https:" in response["Content-Security-Policy-Report-Only"]
+
+ def test_replay_player_frame_serves_the_mount_node_without_a_session(self):
+ # Shared recordings render the player for logged-out viewers.
+ self.client.logout()
+ response = self.client.get("/replay_player_frame/index.html")
+ assert response.status_code == 200
+ # PlayerFrame.tsx looks the mount node up by this id. A rename here makes every player fall
+ # back to the app document.
+ assert 'id="player-frame-content"' in response.content.decode()
+
def test_non_html_response_gets_strict_csp(self):
response = self.client.get("/api/users/@me/")
assert response.status_code == 200
assert response["Content-Security-Policy"] == "default-src 'none'"
assert "Content-Security-Policy-Report-Only" not in response
- def test_html_response_gets_report_only_csp(self):
- response = self.client.get("/")
+ @parameterized.expand(
+ [
+ ("app_root", "/"),
+ # No route serves this path, so the app catch-all answers it. It must keep the app
+ # policy, because the frame policy is enforced and its script-src 'none' stops the app
+ # from starting.
+ ("path_under_the_replay_frame_prefix", "/replay_player_frame"),
+ ]
+ )
+ def test_html_response_gets_report_only_csp(self, _name, path):
+ response = self.client.get(path)
assert response.status_code == 200
assert "Content-Security-Policy-Report-Only" in response
assert "Content-Security-Policy" not in response
diff --git a/posthog/urls.py b/posthog/urls.py
index 5a85b290ab32..e02b68882b03 100644
--- a/posthog/urls.py
+++ b/posthog/urls.py
@@ -99,6 +99,7 @@ from .views import (
preferences_page,
preflight_check,
render_query,
+ replay_player_frame,
robots_txt,
security_txt,
stats,
@@ -513,6 +514,11 @@ urlpatterns = [
# NOTE: We have _health, livez, and _readyz. _health is deprecated and
# is only included for compatability with old installations. For new
# operations livez and readyz should be used.
+ # Same-origin shell the session replay player mounts rrweb into. Unauthenticated because
+ # shared recordings render the player too; it carries no data of its own. The path ends in
+ # index.html so Storybook's static server, which does no directory-index resolution, serves the
+ # same file at the same URL.
+ path("replay_player_frame/index.html", replay_player_frame),
opt_slash_path("_health", health),
opt_slash_path("_stats", stats),
opt_slash_path("_preflight", preflight_check),
diff --git a/posthog/views.py b/posthog/views.py
index 76b933f57478..a82034460072 100644
--- a/posthog/views.py
+++ b/posthog/views.py
@@ -788,3 +788,16 @@ def update_preferences(request: HttpRequest) -> JsonResponse:
except Exception as e:
capture_exception(e)
return JsonResponse({"error": "Failed to update preferences"}, status=400)
+
+
+@xframe_options_exempt
+@never_cache
+def replay_player_frame(request: HttpRequest) -> HttpResponse:
+ """Empty shell the replay player mounts rrweb into.
+
+ rrweb builds its own `about:blank` iframe, and a frame on a local scheme inherits its parent's
+ whole policy, report-uri included. Mounting rrweb here rather than in the app document puts a
+ real document in that inheritance chain, so a recorded page is judged against this frame's
+ policy instead of the app's. CSPMiddleware supplies that policy.
+ """
+ return render(request, "replay_player_frame/index.html")