: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
fix(replay): decompress encoded stylesheets in the recording rasterizer (#114120)
HaynesPostHog4167780b3bc0
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.tsindex 8a5a45214641..c9fa69180efd 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@@ -1,3 +1,4 @@+import { brotliCompressSync, deflateSync, gzipSync } from 'node:zlib'import { Frame, HTTPRequest, Page } from 'puppeteer'import { BlockProxy } from '~/session-replay/recording-rasterizer/capture/block-proxy'@@ -6,9 +7,29 @@ import { RequestInterceptor } from '~/session-replay/recording-rasterizer/capturconst mockFetch = jest.fn()jest.mock('~/common/utils/request', () => ({- fetch: (...args: any[]) => mockFetch(...args),+ fetchStreamed: (...args: any[]) => mockFetch(...args),}))+function streamedResponse({+ status = 200,+ headers = { 'content-type': 'text/css' },+ body = '',+ overLimit = false,+}: {+ status?: number+ headers?: Record<string, string>+ body?: string | Buffer+ overLimit?: boolean+} = {}): object {+ return {+ status,+ headers,+ headerLines: Object.entries(headers).map(([name, value]) => ({ name, value })),+ read: jest.fn().mockResolvedValue({ bytes: Buffer.from(body), overLimit }),+ discard: jest.fn(),+ }+}+type PageEventHandler = (req: HTTPRequest) => voidconst mainFrame = { name: 'mainFrame' } as unknown as Frame@@ -62,6 +83,15 @@ function mockRequest(type: string, frame: Frame = subFrame, url = 'https://examp} as unknown as HTTPRequest}+function respondedWith(req: HTTPRequest): Promise<unknown> {+ return new Promise((resolve) =>+ (req.respond as jest.Mock).mockImplementation((response) => {+ resolve(response)+ return Promise.resolve()+ })+ )+}+const mockLog = {info: jest.fn(),warn: jest.fn(),@@ -200,11 +230,7 @@ describe('RequestInterceptor', () => {})it('proxies sub-frame stylesheet requests through Node.js', async () => {- mockFetch.mockResolvedValue({- status: 200,- headers: { 'content-type': 'text/css' },- text: jest.fn().mockResolvedValue('body { color: red }'),- })+ mockFetch.mockResolvedValue(streamedResponse({ body: 'body { color: red }' }))const { page } = await createInterceptor()const handler = getRequestHandler(page.page)@@ -221,7 +247,7 @@ describe('RequestInterceptor', () => {status: 200,contentType: 'text/css',headers: { 'access-control-allow-origin': '*' },- body: 'body { color: red }',+ body: Buffer.from('body { color: red }'),})})@@ -267,11 +293,7 @@ describe('RequestInterceptor', () => {describe('stylesheet proxy', () => {it('strips hop-by-hop headers from the proxied request', async () => {- mockFetch.mockResolvedValue({- status: 200,- headers: { 'content-type': 'text/css' },- text: jest.fn().mockResolvedValue(''),- })+ mockFetch.mockResolvedValue(streamedResponse())const { page } = await createInterceptor()const handler = getRequestHandler(page.page)@@ -288,11 +310,7 @@ describe('RequestInterceptor', () => {})it('defaults content-type to text/css when upstream omits it', async () => {- mockFetch.mockResolvedValue({- status: 200,- headers: {},- text: jest.fn().mockResolvedValue('h1 {}'),- })+ mockFetch.mockResolvedValue(streamedResponse({ headers: {}, body: 'h1 {}' }))const { page } = await createInterceptor()const handler = getRequestHandler(page.page)@@ -304,6 +322,70 @@ describe('RequestInterceptor', () => {expect(req.respond).toHaveBeenCalledWith(expect.objectContaining({ contentType: 'text/css' }))})+ it.each([+ { encoding: 'gzip', encode: gzipSync },+ { encoding: 'deflate', encode: deflateSync },+ { encoding: 'br', encode: brotliCompressSync },+ { encoding: 'gzip, br', encode: (css: string) => brotliCompressSync(gzipSync(css)) },+ ])('decodes a $encoding body before Chromium parses it', async ({ encoding, encode }) => {+ const css = 'body { background: rebeccapurple }'+ mockFetch.mockResolvedValue(+ streamedResponse({+ headers: { 'content-type': 'text/css', 'content-encoding': encoding },+ body: encode(css),+ })+ )++ const { page } = await createInterceptor()+ const handler = getRequestHandler(page.page)+ const req = mockRequest('stylesheet')++ handler(req)++ expect(await respondedWith(req)).toEqual({+ status: 200,+ contentType: 'text/css',+ headers: { 'access-control-allow-origin': '*' },+ body: Buffer.from(css),+ })+ })++ it.each([+ { name: 'the body is over the size limit', response: { overLimit: true } },+ {+ name: 'the body decompresses past the size limit',+ response: {+ headers: { 'content-encoding': 'gzip' },+ body: gzipSync(Buffer.alloc(10 * 1024 * 1024 + 1)),+ },+ },+ {+ name: 'the content encoding is not supported',+ response: { headers: { 'content-encoding': 'compress' }, body: 'x' },+ },+ {+ name: 'the body has more content encodings than allowed',+ response: {+ headers: { 'content-encoding': 'gzip, gzip, gzip' },+ body: gzipSync(gzipSync(gzipSync('h1 {}'))),+ },+ },+ ])('responds with empty CSS when $name', async ({ response }) => {+ mockFetch.mockResolvedValue(streamedResponse(response))++ const { page } = await createInterceptor()+ const handler = getRequestHandler(page.page)+ const req = mockRequest('stylesheet')++ handler(req)++ expect(await respondedWith(req)).toEqual({ status: 200, contentType: 'text/css', body: '' })+ expect(mockLog.warn).toHaveBeenCalledWith(+ expect.objectContaining({ url: 'https://example.com/style.css' }),+ 'stylesheet proxy failed, responding empty'+ )+ })+it('responds with empty CSS on fetch failure', async () => {mockFetch.mockRejectedValue(new Error('ETIMEDOUT'))@@ -354,10 +436,7 @@ describe('RequestInterceptor', () => {it('waits for tracked stylesheet requests to complete', async () => {mockFetch.mockImplementation(- () =>- new Promise((resolve) =>- setTimeout(() => resolve({ status: 200, headers: {}, text: () => Promise.resolve('') }), 50)- )+ () => new Promise((resolve) => setTimeout(() => resolve(streamedResponse({ headers: {} })), 50)))const mp = mockPage()@@ -384,11 +463,7 @@ describe('RequestInterceptor', () => {})it('resolves when the last of multiple stylesheet requests finishes', async () => {- mockFetch.mockResolvedValue({- status: 200,- headers: {},- text: jest.fn().mockResolvedValue(''),- })+ mockFetch.mockResolvedValue(streamedResponse({ headers: {} }))const mp = mockPage()const bp = mockBlockProxy()@@ -418,11 +493,7 @@ describe('RequestInterceptor', () => {})it('resolves when a tracked request fails', async () => {- mockFetch.mockResolvedValue({- status: 200,- headers: {},- text: jest.fn().mockResolvedValue(''),- })+ mockFetch.mockResolvedValue(streamedResponse({ headers: {} }))const mp = mockPage()const bp = mockBlockProxy()diff --git a/nodejs/src/session-replay/recording-rasterizer/capture/request-interceptor.ts b/nodejs/src/session-replay/recording-rasterizer/capture/request-interceptor.tsindex cfa6583affca..4a6b1693260d 100644--- a/nodejs/src/session-replay/recording-rasterizer/capture/request-interceptor.ts+++ b/nodejs/src/session-replay/recording-rasterizer/capture/request-interceptor.ts@@ -1,7 +1,9 @@import { randomBytes } from 'node:crypto'+import { promisify } from 'node:util'+import { brotliDecompress, gunzip, inflate } from 'node:zlib'import { Frame, HTTPRequest } from 'puppeteer'-import { fetch } from '~/common/utils/request'+import { fetchStreamed } from '~/common/utils/request'import { config } from '~/session-replay/recording-rasterizer/config'import { type Logger, createLogger } from '~/session-replay/recording-rasterizer/logger'@@ -9,6 +11,16 @@ import { BLOCK_REQUEST_PREFIX, BlockSource } from './block-proxy'import { CapturePage } from './capture-page'const PROXY_TIMEOUT_MS = 10_000+const MAX_STYLESHEET_BYTES = 10 * 1024 * 1024+const MAX_CONTENT_ENCODING_LAYERS = 2++type Decoder = (input: Buffer, options: { maxOutputLength: number }) => Promise<Buffer>+const DECODERS = new Map<string, Decoder>([+ ['gzip', promisify(gunzip)],+ ['x-gzip', promisify(gunzip)],+ ['deflate', promisify(inflate)],+ ['br', promisify(brotliDecompress)],+])// 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@@ -164,8 +176,12 @@ export class RequestInterceptor {headers[name] = browserHeaders[name]}}- const resp = await fetch(url, { headers, timeoutMs: PROXY_TIMEOUT_MS })- const body = await resp.text()+ const resp = await fetchStreamed(url, { headers, timeoutMs: PROXY_TIMEOUT_MS })+ const { bytes, overLimit } = await resp.read(MAX_STYLESHEET_BYTES, false)+ if (overLimit) {+ throw new Error(`stylesheet is larger than ${MAX_STYLESHEET_BYTES} bytes`)+ }+ const body = await decodeContentEncoding(bytes, resp.headerLines)await request.respond({status: resp.status,contentType: resp.headers['content-type'] || 'text/css',@@ -184,3 +200,32 @@ export class RequestInterceptor {}}}++// A host such as S3 sends an object stored with `Content-Encoding: gzip` encoded even when the request+// has no `accept-encoding`. Chromium gets the body without that header, so it cannot parse it undecoded.+async function decodeContentEncoding(+ body: Buffer,+ headerLines: Array<{ name: string; value: string }>+): Promise<Buffer> {+ const codings = headerLines+ .filter((line) => line.name === 'content-encoding')+ .flatMap((line) => line.value.split(','))+ .map((coding) => coding.trim().toLowerCase())+ .filter((coding) => coding !== '' && coding !== 'identity')+ if (codings.length === 0 || body.length === 0) {+ return body+ }+ if (codings.length > MAX_CONTENT_ENCODING_LAYERS) {+ throw new Error(`too many content encodings: ${codings.join(', ')}`)+ }+ let decoded = body+ // The header lists codings in the order the sender applied them, so decode in reverse.+ for (const coding of codings.reverse()) {+ const decode = DECODERS.get(coding)+ if (!decode) {+ throw new Error(`unsupported content encoding: ${coding}`)+ }+ decoded = await decode(decoded, { maxOutputLength: MAX_STYLESHEET_BYTES })+ }+ return decoded+}