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): send the replay proxy token from the player (#111579)

Paul D'Ambraf9357f935cba
diff --git a/common/replay-shared/src/index.ts b/common/replay-shared/src/index.ts
index 1e5ab0c8fedd..8db94b6067e8 100644
--- a/common/replay-shared/src/index.ts
+++ b/common/replay-shared/src/index.ts
@@ -54,6 +54,7 @@ export { CanvasReplayerPlugin } from './canvas/canvas-plugin'
export {
AudioMuteReplayerPlugin,
CorsPlugin,
+ createCorsPlugin,
COMMON_REPLAYER_CONFIG,
speedDependentStyleRules,
HLSPlayerPlugin,
diff --git a/common/replay-shared/src/rrweb-plugins/index.ts b/common/replay-shared/src/rrweb-plugins/index.ts
index 06c95b7e9521..88568896a751 100644
--- a/common/replay-shared/src/rrweb-plugins/index.ts
+++ b/common/replay-shared/src/rrweb-plugins/index.ts
@@ -4,65 +4,83 @@ import { PLACEHOLDER_SVG_DATA_IMAGE_URL } from '../mobile/transformer/shared'
const PROXY_URL = 'https://replay.ph-proxy.com' as const
-export const CorsPlugin: ReplayPlugin & {
+type CorsReplayPlugin = ReplayPlugin & {
_replaceFontCssUrls: (value: string | null) => string | null
_replaceFontUrl: (value: string) => string
_replaceJSUrl: (value: string) => string
-} = {
- _replaceFontCssUrls: (value: string | null): string | null => {
- return (
- value?.replace(
- /url\("(https:\/\/[^\s"?#]+\.(?:eot|woff2|ttf|woff)(?:[?#][^\s"]*)?)"\)/gi,
- `url("${PROXY_URL}/proxy?url=$1")`
- ) || null
- )
- },
-
- _replaceFontUrl: (value: string): string => {
- return value.replace(
- /^(https:\/\/[^\s"?#]+\.(?:eot|woff2|ttf|woff)(?:[?#][^\s"]*)?)$/i,
- `${PROXY_URL}/proxy?url=$1`
- )
- },
-
- _replaceJSUrl: (value: string): string => {
- return value.replace(/^(https:\/\/[^\s"?#]+\.js(?:[?#][^\s"]*)?)$/i, `${PROXY_URL}/proxy?url=$1`)
- },
-
- onBuild: (node) => {
- if (node.nodeName === 'STYLE') {
- const styleElement = node as HTMLStyleElement
- const childNodes = styleElement.childNodes
- for (let i = 0; i < childNodes.length; i++) {
- if (childNodes[i].nodeType == 3) {
- const updatedContent = CorsPlugin._replaceFontCssUrls(childNodes[i].textContent)
- if (updatedContent !== childNodes[i].textContent) {
- childNodes[i].textContent = updatedContent
+}
+
+// The token goes before `url`, because a font url can end in a `#` fragment, and the browser
+// does not send anything after a `#` to the proxy.
+function proxyUrl(targetUrl: string, token: string | null | undefined): string {
+ return token
+ ? `${PROXY_URL}/proxy?token=${encodeURIComponent(token)}&url=${targetUrl}`
+ : `${PROXY_URL}/proxy?url=${targetUrl}`
+}
+
+// getProxyToken runs for every url, so a token that the player refreshes reaches nodes it builds later.
+export function createCorsPlugin(getProxyToken: () => string | null | undefined): CorsReplayPlugin {
+ const plugin: CorsReplayPlugin = {
+ _replaceFontCssUrls: (value: string | null): string | null => {
+ return (
+ value?.replace(
+ /url\("(https:\/\/[^\s"?#]+\.(?:eot|woff2|ttf|woff)(?:[?#][^\s"]*)?)"\)/gi,
+ (_, targetUrl: string) => `url("${proxyUrl(targetUrl, getProxyToken())}")`
+ ) || null
+ )
+ },
+
+ _replaceFontUrl: (value: string): string => {
+ return value.replace(/^(https:\/\/[^\s"?#]+\.(?:eot|woff2|ttf|woff)(?:[?#][^\s"]*)?)$/i, (targetUrl) =>
+ proxyUrl(targetUrl, getProxyToken())
+ )
+ },
+
+ _replaceJSUrl: (value: string): string => {
+ return value.replace(/^(https:\/\/[^\s"?#]+\.js(?:[?#][^\s"]*)?)$/i, (targetUrl) =>
+ proxyUrl(targetUrl, getProxyToken())
+ )
+ },
+
+ onBuild: (node) => {
+ if (node.nodeName === 'STYLE') {
+ const styleElement = node as HTMLStyleElement
+ const childNodes = styleElement.childNodes
+ for (let i = 0; i < childNodes.length; i++) {
+ if (childNodes[i].nodeType == 3) {
+ const updatedContent = plugin._replaceFontCssUrls(childNodes[i].textContent)
+ if (updatedContent !== childNodes[i].textContent) {
+ childNodes[i].textContent = updatedContent
+ }
}
}
}
- }
- if (node.nodeName === 'LINK') {
- const linkElement = node as HTMLLinkElement
- const href = linkElement.href
- if (!href) {
- return
- }
- if (linkElement.getAttribute('rel') == 'modulepreload') {
- linkElement.href = CorsPlugin._replaceJSUrl(href)
- } else {
- linkElement.href = CorsPlugin._replaceFontUrl(href)
+ if (node.nodeName === 'LINK') {
+ const linkElement = node as HTMLLinkElement
+ const href = linkElement.href
+ if (!href) {
+ return
+ }
+ if (linkElement.getAttribute('rel') == 'modulepreload') {
+ linkElement.href = plugin._replaceJSUrl(href)
+ } else {
+ linkElement.href = plugin._replaceFontUrl(href)
+ }
}
- }
- if (node.nodeName === 'SCRIPT') {
- const scriptElement = node as HTMLScriptElement
- scriptElement.src = CorsPlugin._replaceJSUrl(scriptElement.src)
- }
- },
+ if (node.nodeName === 'SCRIPT') {
+ const scriptElement = node as HTMLScriptElement
+ scriptElement.src = plugin._replaceJSUrl(scriptElement.src)
+ }
+ },
+ }
+ return plugin
}
+// The headless renderer has no proxy token, so it calls the proxy without one.
+export const CorsPlugin = createCorsPlugin(() => null)
+
const defaultStyleRules = `.ph-no-capture { background-image: ${PLACEHOLDER_SVG_DATA_IMAGE_URL}; }`
const shopifyShorthandCSSFix =
'@media (prefers-reduced-motion: no-preference) { .scroll-trigger:not(.scroll-trigger--offscreen).animate--slide-in { animation: var(--animation-slide-in) } }'
diff --git a/common/replay-shared/src/rrweb-plugins/rrweb-plugins.test.ts b/common/replay-shared/src/rrweb-plugins/rrweb-plugins.test.ts
index 4b35df68a492..caefecef430c 100644
--- a/common/replay-shared/src/rrweb-plugins/rrweb-plugins.test.ts
+++ b/common/replay-shared/src/rrweb-plugins/rrweb-plugins.test.ts
@@ -1,7 +1,7 @@
/**
* @jest-environment jsdom
*/
-import { CorsPlugin, createHLSPlayerPlugin, WindowTitlePlugin } from './index'
+import { CorsPlugin, createCorsPlugin, createHLSPlayerPlugin, WindowTitlePlugin } from './index'
describe('CorsPlugin', () => {
it.each(['https://some-external.js'])('should replace JS urls', (jsUrl) => {
@@ -37,6 +37,28 @@ describe('CorsPlugin', () => {
CorsPlugin.onBuild?.(el, { id: 1, replayer: null as unknown as any })
expect(el.href).toEqual(`https://replay.ph-proxy.com/proxy?url=https://app.posthog.com/my-image.js`)
})
+
+ it.each([
+ [null, 'https://replay.ph-proxy.com/proxy?url=https://app.posthog.com/fonts/my-font.woff2#iefix'],
+ [
+ 'header.payload.signature',
+ 'https://replay.ph-proxy.com/proxy?token=header.payload.signature&url=https://app.posthog.com/fonts/my-font.woff2#iefix',
+ ],
+ ])('sends proxy token %s before the url', (token, expected) => {
+ const plugin = createCorsPlugin(() => token)
+
+ expect(plugin._replaceFontUrl('https://app.posthog.com/fonts/my-font.woff2#iefix')).toEqual(expected)
+ })
+
+ it('reads the latest proxy token for each url', () => {
+ let token = 'first'
+ const plugin = createCorsPlugin(() => token)
+ token = 'second'
+
+ expect(plugin._replaceJSUrl('https://some-external.js')).toEqual(
+ 'https://replay.ph-proxy.com/proxy?token=second&url=https://some-external.js'
+ )
+ })
})
const mockHlsInstance = {
diff --git a/frontend/src/scenes/session-recordings/player/__mocks__/test-setup.ts b/frontend/src/scenes/session-recordings/player/__mocks__/test-setup.ts
index 989b8c61bef2..bc7e3584665f 100644
--- a/frontend/src/scenes/session-recordings/player/__mocks__/test-setup.ts
+++ b/frontend/src/scenes/session-recordings/player/__mocks__/test-setup.ts
@@ -23,7 +23,10 @@ export const EMPTY_PAGINATED_RESPONSE = {
results: [],
}
-function createSnapshotMockHandler(sources: SessionRecordingSnapshotSource[]): MockSignature {
+function createSnapshotMockHandler(
+ sources: SessionRecordingSnapshotSource[],
+ replayProxyToken?: string | null
+): MockSignature {
return ({ request }) => {
const sourceParam = new URL(request.url).searchParams.get('source')
@@ -35,6 +38,7 @@ function createSnapshotMockHandler(sources: SessionRecordingSnapshotSource[]): M
200,
{
sources,
+ ...(replayProxyToken !== undefined ? { replay_proxy_token: replayProxyToken } : {}),
},
]
}
@@ -47,12 +51,14 @@ export interface SessionRecordingTestSetupOptions {
patchMocks?: Record<string, MockSignature>
deleteMocks?: Record<string, MockSignature>
snapshotSources?: SessionRecordingSnapshotSource[]
+ replayProxyToken?: string | null
customQueryHandler?: MockSignature
}
function getDefaultMocks(
snapshotSources: SessionRecordingSnapshotSource[],
- customQueryHandler?: MockSignature
+ customQueryHandler?: MockSignature,
+ replayProxyToken?: string | null
): {
get: Record<string, MockSignature>
post: Record<string, MockSignature>
@@ -61,7 +67,10 @@ function getDefaultMocks(
} {
return {
get: {
- '/api/environments/:team_id/session_recordings/:id/snapshots': createSnapshotMockHandler(snapshotSources),
+ '/api/environments/:team_id/session_recordings/:id/snapshots': createSnapshotMockHandler(
+ snapshotSources,
+ replayProxyToken
+ ),
'/api/environments/:team_id/session_recordings/:id': recordingMetaJson,
'/api/projects/:team_id/comments': EMPTY_PAGINATED_RESPONSE,
'/api/projects/:team/notebooks/recording_comments': EMPTY_PAGINATED_RESPONSE,
@@ -87,12 +96,13 @@ export function setupSessionRecordingTest(options: SessionRecordingTestSetupOpti
patchMocks = {},
deleteMocks = {},
snapshotSources = [BLOB_SOURCE_V2],
+ replayProxyToken,
customQueryHandler,
} = options
useAvailableFeatures(features)
- const defaults = getDefaultMocks(snapshotSources, customQueryHandler)
+ const defaults = getDefaultMocks(snapshotSources, customQueryHandler, replayProxyToken)
useMocks({
get: { ...defaults.get, ...getMocks },
@@ -111,10 +121,11 @@ export function overrideSessionRecordingMocks(options: Omit<SessionRecordingTest
patchMocks = {},
deleteMocks = {},
snapshotSources = [BLOB_SOURCE_V2],
+ replayProxyToken,
customQueryHandler,
} = options
- const defaults = getDefaultMocks(snapshotSources, customQueryHandler)
+ const defaults = getDefaultMocks(snapshotSources, customQueryHandler, replayProxyToken)
useMocks({
get: { ...defaults.get, ...getMocks },
diff --git a/frontend/src/scenes/session-recordings/player/sessionRecordingPlayerLogic.ts b/frontend/src/scenes/session-recordings/player/sessionRecordingPlayerLogic.ts
index da83fb75a541..a603a42dda90 100644
--- a/frontend/src/scenes/session-recordings/player/sessionRecordingPlayerLogic.ts
+++ b/frontend/src/scenes/session-recordings/player/sessionRecordingPlayerLogic.ts
@@ -28,7 +28,7 @@ import {
COMMON_REPLAYER_CONFIG,
speedDependentStyleRules,
CanvasReplayerPlugin,
- CorsPlugin,
+ createCorsPlugin,
SnapshotStore,
createHLSPlayerPlugin,
} from '@posthog/replay-shared'
@@ -772,6 +772,7 @@ export interface sessionRecordingPlayerLogicValues {
}[] // sessionRecordingDataCoordinatorLogic
allSourcesLoaded: boolean // snapshotDataLogic
isSnapshotUnauthorized: boolean // snapshotDataLogic
+ replayProxyToken: string | null // snapshotDataLogic
snapshotSources: SessionRecordingSnapshotSource[] | null // snapshotDataLogic
snapshotStore: SnapshotStore // snapshotDataLogic
snapshotsLoaded: boolean // snapshotDataLogic
@@ -1491,6 +1492,7 @@ export const sessionRecordingPlayerLogic = kea<sessionRecordingPlayerLogicType>(
values: [
snapshotDataLogic(props),
[
+ 'replayProxyToken',
'snapshotsLoaded',
'snapshotsLoading',
'snapshotSources',
@@ -2741,7 +2743,7 @@ export const sessionRecordingPlayerLogic = kea<sessionRecordingPlayerLogicType>(
// We don't want non-cloud products to talk to our proxy as it likely won't work, but we _do_ want local testing to work
if (values.preflight?.cloud || window.location.hostname === 'localhost') {
- plugins.push(CorsPlugin)
+ plugins.push(createCorsPlugin(() => values.replayProxyToken))
}
const canvasPlugin = CanvasReplayerPlugin(values.sessionPlayerData.snapshotsByWindowId[windowId], (error) =>
diff --git a/frontend/src/scenes/session-recordings/player/snapshotDataLogic.test.ts b/frontend/src/scenes/session-recordings/player/snapshotDataLogic.test.ts
index 880d82e60dab..2b73fc971a29 100644
--- a/frontend/src/scenes/session-recordings/player/snapshotDataLogic.test.ts
+++ b/frontend/src/scenes/session-recordings/player/snapshotDataLogic.test.ts
@@ -9,7 +9,7 @@ import { parseEncodedSnapshots } from 'scenes/session-recordings/player/snapshot
import { RecordingSnapshot, SessionRecordingSnapshotSource } from '~/types'
-import { setupSessionRecordingTest } from './__mocks__/test-setup'
+import { overrideSessionRecordingMocks, setupSessionRecordingTest } from './__mocks__/test-setup'
import { snapshotDataLogic } from './snapshotDataLogic'
const BLOB_SOURCE: SessionRecordingSnapshotSource = {
@@ -122,6 +122,22 @@ describe('snapshotDataLogic', () => {
})
})
+ describe('replay proxy token', () => {
+ it.each([
+ ['the token from the sources listing', 'header.payload.signature', 'header.payload.signature'],
+ ['null when the listing has a null token', null, null],
+ ['null when the listing has no token field', undefined, null],
+ ])('stores %s', async (_, replayProxyToken, expected) => {
+ overrideSessionRecordingMocks({ snapshotSources: [BLOB_SOURCE], replayProxyToken })
+
+ await expectLogic(logic, () => {
+ logic.actions.loadSnapshotSources()
+ })
+ .toDispatchActions(['loadSnapshotSourcesSuccess'])
+ .toMatchValues({ replayProxyToken: expected })
+ })
+ })
+
describe('isSnapshotUnauthorized', () => {
it('is false when no error', () => {
expect(logic.values.isSnapshotUnauthorized).toBe(false)
diff --git a/frontend/src/scenes/session-recordings/player/snapshotDataLogic.tsx b/frontend/src/scenes/session-recordings/player/snapshotDataLogic.tsx
index 07ebd54147f8..4036edddb0b7 100644
--- a/frontend/src/scenes/session-recordings/player/snapshotDataLogic.tsx
+++ b/frontend/src/scenes/session-recordings/player/snapshotDataLogic.tsx
@@ -60,6 +60,7 @@ export interface snapshotDataLogicValues {
pollingInterval: number
recordingDeletedAt: number | null
recordingDeletedBy: string | null
+ replayProxyToken: string | null
seekTarget: SeekTarget | null
snapshotLoadError: Error | null
snapshotSources: SessionRecordingSnapshotSource[] | null
@@ -161,6 +162,9 @@ export interface snapshotDataLogicActions {
setPollingInterval: (intervalMs: number) => {
intervalMs: number
}
+ setReplayProxyToken: (token: string | null) => {
+ token: string | null
+ }
setSnapshots: (snapshots: RecordingSnapshot[]) => {
snapshots: RecordingSnapshot[]
}
@@ -272,8 +276,15 @@ export const snapshotDataLogic = kea<snapshotDataLogicType>([
loadAllSources: true,
// dispatch after any mutation to cache.store — it lives outside Kea's reactivity and needs explicit invalidation
storeUpdated: true,
+ setReplayProxyToken: (token: string | null) => ({ token }),
}),
reducers(() => ({
+ replayProxyToken: [
+ null as string | null,
+ {
+ setReplayProxyToken: (_, { token }) => token,
+ },
+ ],
storeUpdateCount: [
0,
{
@@ -345,6 +356,8 @@ export const snapshotDataLogic = kea<snapshotDataLogicType>([
// returning [] here would silently dead-end with no error and no polling.
throw new Error('Malformed response listing snapshot sources')
}
+ // Each listing mints a new token, so polling the sources keeps the proxy token fresh.
+ actions.setReplayProxyToken(response.replay_proxy_token ?? null)
const anyBlobV2 = response.sources.some((s) => s.source === SnapshotSourceType.blob_v2)
if (anyBlobV2) {
diff --git a/frontend/src/types.ts b/frontend/src/types.ts
index 5fc3938f9963..031ae468a333 100644
--- a/frontend/src/types.ts
+++ b/frontend/src/types.ts
@@ -1506,6 +1506,7 @@ export type SessionRecordingSnapshotParams = {
export interface SessionRecordingSnapshotResponse {
sources?: SessionRecordingSnapshotSource[]
snapshots?: EncodedRecordingSnapshot[]
+ replay_proxy_token?: string | null
}
export interface SessionPlayerSnapshotData {