Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

fix(replay): confine rasterizer player scripts with a nonce CSP (#68985)

Tom Piccirelloa7fc41ac065e
diff --git a/common/replay-headless/build.mjs b/common/replay-headless/build.mjs
index 03e806e09adb..36224812760f 100644
--- a/common/replay-headless/build.mjs
+++ b/common/replay-headless/build.mjs
@@ -24,8 +24,10 @@ const result = await build({
const js = result.outputFiles[0].text
const html = readFileSync(resolve(__dirname, 'src/index.html'), 'utf-8')
-// Use a replacer function to avoid $ replacement patterns in the JS being interpreted
-const outputHtml = html.replace('<!-- INLINE_JS -->', () => `<script>${js}</script>`)
+// The `__CSP_NONCE__` placeholder is swapped for a per-request nonce (or stripped) by the
+// rasterizer's CSP handling — see servePlayer in nodejs recording-rasterizer/request-interceptor.ts.
+// Use a replacer function to avoid $ replacement patterns in the JS being interpreted.
+const outputHtml = html.replace('<!-- INLINE_JS -->', () => `<script nonce="__CSP_NONCE__">${js}</script>`)
mkdirSync(resolve(__dirname, 'dist'), { recursive: true })
writeFileSync(resolve(__dirname, 'dist/player.html'), outputHtml)
diff --git a/nodejs/src/session-replay/recording-rasterizer/__tests__/request-interceptor.test.ts b/nodejs/src/session-replay/recording-rasterizer/__tests__/request-interceptor.test.ts
index 29b2e261552d..14a26e660023 100644
--- a/nodejs/src/session-replay/recording-rasterizer/__tests__/request-interceptor.test.ts
+++ b/nodejs/src/session-replay/recording-rasterizer/__tests__/request-interceptor.test.ts
@@ -15,7 +15,8 @@ const mainFrame = { name: 'mainFrame' } as unknown as Frame
const subFrame = { name: 'subFrame' } as unknown as Frame
const playerUrl = 'http://localhost:8000/player'
-const playerHtml = '<html>player</html>'
+const playerHtml =
+ '<html><head></head><body><div>player</div><script nonce="__CSP_NONCE__">window.__player=1</script></body></html>'
function mockPage(): {
page: Page
@@ -79,12 +80,13 @@ function mockBlockProxy(): BlockProxy {
async function createInterceptor(
page?: Page,
- blockProxy?: BlockProxy
+ blockProxy?: BlockProxy,
+ enablePlayerCsp = false
): Promise<{ interceptor: RequestInterceptor; page: ReturnType<typeof mockPage>; blockProxy: BlockProxy }> {
const mp = page ? { page, emitRequestFinished: () => {}, emitRequestFailed: () => {} } : mockPage()
const bp = blockProxy || mockBlockProxy()
const cp = mockCapturePage(mp.page)
- const interceptor = new RequestInterceptor(cp, bp, mockLog)
+ const interceptor = new RequestInterceptor(cp, bp, mockLog, enablePlayerCsp)
await interceptor.install()
return { interceptor, page: mp as ReturnType<typeof mockPage>, blockProxy: bp }
}
@@ -112,18 +114,65 @@ describe('RequestInterceptor', () => {
})
describe('request routing', () => {
- it('serves player HTML for the player URL', async () => {
+ it('serves the player HTML under a script-locking CSP with a matching nonce when enabled', async () => {
+ const { page } = await createInterceptor(undefined, undefined, true)
+ const handler = getRequestHandler(page.page)
+ const req = mockRequest('document', mainFrame, playerUrl)
+
+ handler(req)
+
+ const call = (req.respond as jest.Mock).mock.calls[0][0]
+ expect(call.status).toBe(200)
+ expect(call.contentType).toBe('text/html')
+
+ const csp: string = call.headers['Content-Security-Policy']
+ const nonce = csp.match(/script-src 'nonce-([^']+)'/)?.[1]
+ expect(nonce).toBeTruthy()
+ // recorded inline event handlers must not be executable in the player origin
+ expect(csp).not.toContain("'unsafe-inline'")
+ expect(csp).toContain("object-src 'none'")
+ // hls.js's transmux worker loads from a blob URL; dropping this would break HLS playback
+ expect(csp).toContain('worker-src blob:')
+ // the build's placeholder is swapped for the real nonce, leaving none behind
+ expect(call.body).toContain(`<script nonce="${nonce}">`)
+ expect(call.body).not.toContain('__CSP_NONCE__')
+ })
+
+ it('strips the nonce placeholder and sets no CSP when the flag is off', async () => {
const { page } = await createInterceptor()
const handler = getRequestHandler(page.page)
const req = mockRequest('document', mainFrame, playerUrl)
handler(req)
- expect(req.respond).toHaveBeenCalledWith({
- status: 200,
- contentType: 'text/html',
- body: playerHtml,
- })
+ const call = (req.respond as jest.Mock).mock.calls[0][0]
+ expect(call.status).toBe(200)
+ expect(call.headers?.['Content-Security-Policy']).toBeUndefined()
+ // placeholder gone, script tag restored to its pre-CSP form
+ expect(call.body).not.toContain('__CSP_NONCE__')
+ expect(call.body).toContain('<script>window.__player=1</script>')
+ })
+
+ it.each([
+ { name: 'the placeholder is missing', html: '<html><body><script>x=1</script></body></html>' },
+ {
+ name: 'more than one placeholder is present',
+ html: '<html><body><script nonce="__CSP_NONCE__">a</script><script nonce="__CSP_NONCE__">b</script></body></html>',
+ },
+ ])('serves a 500 with no CSP when $name', async ({ html }) => {
+ const mp = mockPage()
+ const cp = { page: mp.page, playerUrl, playerHtml: html } as unknown as CapturePage
+ const interceptor = new RequestInterceptor(cp, mockBlockProxy(), mockLog, true)
+ await interceptor.install()
+ const handler = getRequestHandler(mp.page)
+ const req = mockRequest('document', mainFrame, playerUrl)
+
+ handler(req)
+
+ const call = (req.respond as jest.Mock).mock.calls[0][0]
+ expect(call.status).toBe(500)
+ expect(call.headers?.['Content-Security-Policy']).toBeUndefined()
+ expect(mockLog.error).toHaveBeenCalled()
})
it('forwards block requests to BlockProxy', async () => {
diff --git a/nodejs/src/session-replay/recording-rasterizer/capture/request-interceptor.ts b/nodejs/src/session-replay/recording-rasterizer/capture/request-interceptor.ts
index 382417178498..170c293824d1 100644
--- a/nodejs/src/session-replay/recording-rasterizer/capture/request-interceptor.ts
+++ b/nodejs/src/session-replay/recording-rasterizer/capture/request-interceptor.ts
@@ -1,6 +1,8 @@
+import { randomBytes } from 'node:crypto'
import { Frame, HTTPRequest } from 'puppeteer'
import { fetch } from '~/common/utils/request'
+import { config } from '~/session-replay/recording-rasterizer/config'
import { type Logger, createLogger } from '~/session-replay/recording-rasterizer/logger'
import { BLOCK_REQUEST_PREFIX, BlockProxy } from './block-proxy'
@@ -8,6 +10,11 @@ import { CapturePage } from './capture-page'
const PROXY_TIMEOUT_MS = 10_000
+// The replay-headless build stamps this placeholder as the player script's nonce attribute
+// (see common/replay-headless/build.mjs). It is swapped for a per-request nonce when the CSP is on
+// and stripped when it is off. Keep in sync with the build.
+const NONCE_PLACEHOLDER = '__CSP_NONCE__'
+
/**
* Centralizes all Puppeteer request interception: serves the player HTML,
* forwards block requests to {@link BlockProxy}, proxies sub-frame
@@ -23,7 +30,8 @@ export class RequestInterceptor {
constructor(
private capturePage: CapturePage,
private blockProxy: BlockProxy,
- private log: Logger = createLogger()
+ private log: Logger = createLogger(),
+ private enablePlayerCsp: boolean = config.enablePlayerCsp
) {
this.mainFrame = capturePage.page.mainFrame()
}
@@ -50,7 +58,7 @@ export class RequestInterceptor {
const url = request.url()
if (url === this.capturePage.playerUrl) {
- void request.respond({ status: 200, contentType: 'text/html', body: this.capturePage.playerHtml })
+ this.servePlayer(request)
return
}
@@ -82,6 +90,60 @@ export class RequestInterceptor {
void request.continue()
}
+ /**
+ * Serve the player document. When {@link enablePlayerCsp} is set, it goes out under a
+ * Content-Security-Policy that confines script execution to our own bundle via a per-response
+ * nonce. Recordings are untrusted, so this stops a malicious snapshot from running an inline
+ * event handler (e.g. a copied `onerror`) in the player origin — defense in depth behind
+ * sanitizing the DOM itself.
+ *
+ * Only script execution is locked down. Resource directives (img/style/font/media/
+ * connect/frame) are intentionally left unset so recorded pages keep loading assets from
+ * arbitrary third-party hosts, which is the whole point of the replay. `worker-src blob:`
+ * keeps hls.js's transmux worker alive; the replay iframe is scriptless (`allow-same-origin`
+ * sandbox with no `allow-scripts`), so inheriting this policy costs it nothing.
+ *
+ * The CSP is opt-in (ENABLE_PLAYER_CSP) so it can be verified in dev before production; when
+ * off, the placeholder is stripped and the player is served as it was before this feature.
+ */
+ private servePlayer(request: HTTPRequest): void {
+ const playerHtml = this.capturePage.playerHtml
+
+ if (!this.enablePlayerCsp) {
+ void request.respond({
+ status: 200,
+ contentType: 'text/html',
+ body: playerHtml.replace(` nonce="${NONCE_PLACEHOLDER}"`, ''),
+ })
+ return
+ }
+
+ const nonce = randomBytes(16).toString('base64')
+ // Replace the single build-stamped placeholder (function replacer avoids $-pattern parsing).
+ const body = playerHtml.replace(NONCE_PLACEHOLDER, () => nonce)
+
+ // The build stamps exactly one placeholder. If it is gone (build changed) or a second one
+ // slipped through, our bundle would load without a valid nonce and the CSP would blank the
+ // page. Fail loudly instead of silently serving a broken player.
+ if (!body.includes(nonce) || body.includes(NONCE_PLACEHOLDER)) {
+ this.log.error(
+ { playerUrl: this.capturePage.playerUrl },
+ 'player HTML nonce placeholder missing or duplicated; refusing to serve without a working CSP nonce'
+ )
+ void request.respond({ status: 500, contentType: 'text/plain', body: 'player nonce injection failed' })
+ return
+ }
+
+ void request.respond({
+ status: 200,
+ contentType: 'text/html',
+ headers: {
+ 'Content-Security-Policy': `script-src 'nonce-${nonce}'; worker-src blob:; object-src 'none'`,
+ },
+ body,
+ })
+ }
+
private removeTracked(req: HTTPRequest): void {
if (this.tracked.delete(req) && this.tracked.size === 0 && this.onSettled) {
this.onSettled()
diff --git a/nodejs/src/session-replay/recording-rasterizer/config.ts b/nodejs/src/session-replay/recording-rasterizer/config.ts
index 5b76b24ee84c..883d08372d52 100644
--- a/nodejs/src/session-replay/recording-rasterizer/config.ts
+++ b/nodejs/src/session-replay/recording-rasterizer/config.ts
@@ -40,4 +40,7 @@ export const config = {
// Player
siteUrl: process.env.SITE_URL || 'http://localhost:8000',
playerHtmlPath: process.env.PLAYER_HTML_PATH || '/code/common/replay-headless/dist/player.html',
+ // Opt-in: serve the player under a script-locking CSP (nonce). Off by default so it can be
+ // rolled out and verified in dev before enabling in production.
+ enablePlayerCsp: process.env.ENABLE_PLAYER_CSP === '1',
}