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.

chore(replay): delete the TS scrubbers from the ml-mirror pipeline (#69220)

Robbie6e4f7831d413
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/anonymize-step.test.ts b/nodejs/src/ingestion/pipelines/sessionreplay/anonymize-step.test.ts
deleted file mode 100644
index e1765f46aeba..000000000000
--- a/nodejs/src/ingestion/pipelines/sessionreplay/anonymize-step.test.ts
+++ /dev/null
@@ -1,83 +0,0 @@
-import { PipelineResultType } from '~/ingestion/framework/results'
-
-import { createAnonymizeStep } from './anonymize-step'
-import { defaultAllowLists } from './anonymize/default-dict'
-import { ParsedMessageData } from './kafka/types'
-
-describe('anonymize-step', () => {
- const step = createAnonymizeStep({ scrubContext: { allow: defaultAllowLists() } })
- const team = { teamId: 1, consoleLogIngestionEnabled: true, aiTrainingOptedIn: true, firstPartyHosts: [] }
-
- const parsedMessageWith = (eventsByWindowId: Record<string, any[]>): ParsedMessageData =>
- ({ eventsByWindowId }) as unknown as ParsedMessageData
-
- it('scrubs events across all windows in place and returns OK', async () => {
- const parsedMessage = parsedMessageWith({
- win1: [{ type: 3, timestamp: 1, data: { source: 5, id: 1, text: 'Hello SecretName', isChecked: false } }],
- win2: [{ type: 4, timestamp: 2, data: { href: 'https://example.com/user/abc/edit', width: 1, height: 1 } }],
- })
-
- const result = await step({ parsedMessage, team })
-
- expect(result.type).toBe(PipelineResultType.OK)
- expect((parsedMessage.eventsByWindowId.win1[0] as any).data.text).toBe('Hello **********')
- expect((parsedMessage.eventsByWindowId.win2[0] as any).data.href).toBe(
- 'https://example.com/user/[redacted]/edit'
- )
- })
-
- it('blurs a data-image media source via the deferred job pass', async () => {
- // Small patterned PNG (portable across libvips/libpng builds; a solid color would blur to
- // identical bytes, so we use a checkerboard the blur visibly changes).
- const onePxPng =
- 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAIAAACQkWg2AAAACXBIWXMAAAPoAAAD6AG1e1JrAAAAJUlEQVQokWN4plEBRyInbOAIlzjDINRAjCJk8cGoYRAG60iMBwA8H08Qor0ygQAAAABJRU5ErkJggg=='
- const parsedMessage = parsedMessageWith({
- win1: [
- {
- type: 2,
- timestamp: 1,
- data: {
- node: {
- type: 0,
- id: 1,
- childNodes: [
- { type: 2, id: 2, tagName: 'img', attributes: { src: onePxPng }, childNodes: [] },
- ],
- },
- initialOffset: { top: 0, left: 0 },
- },
- },
- ],
- })
-
- await step({ parsedMessage, team })
-
- const src = (parsedMessage.eventsByWindowId.win1[0] as any).data.node.childNodes[0].attributes.src
- // Blurred into a fresh PNG, not left as the placeholder or the original.
- expect(src.startsWith('data:image/png;base64,')).toBe(true)
- expect(src).not.toBe(onePxPng)
- })
-
- it('passes through events with no scrubbable content', async () => {
- const parsedMessage = parsedMessageWith({
- win1: [{ type: 3, timestamp: 1, data: { source: 1, positions: [] } }],
- })
-
- const result = await step({ parsedMessage, team })
-
- expect(result.type).toBe(PipelineResultType.OK)
- expect((parsedMessage.eventsByWindowId.win1[0] as any).data.source).toBe(1)
- })
-
- it('fails closed: drops the message when an event cannot be anonymized', async () => {
- // A FullSnapshot whose data string is not valid latin-1 throws during scrubbing.
- const parsedMessage = parsedMessageWith({
- win1: [{ type: 2, timestamp: 1, cv: '2024-10', data: 'not-Ā-gzip' }],
- })
-
- const result = await step({ parsedMessage, team })
-
- expect(result.type).toBe(PipelineResultType.DROP)
- expect(result.type === PipelineResultType.DROP && result.reason).toBe('anonymize_failed')
- })
-})
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/anonymize-step.ts b/nodejs/src/ingestion/pipelines/sessionreplay/anonymize-step.ts
deleted file mode 100644
index 90a5fcfb22b6..000000000000
--- a/nodejs/src/ingestion/pipelines/sessionreplay/anonymize-step.ts
+++ /dev/null
@@ -1,37 +0,0 @@
-import { drop, ok } from '~/ingestion/framework/results'
-import { ProcessingStep } from '~/ingestion/framework/steps'
-
-import { anonymizeParsedMessage } from './anonymize/anonymize-event'
-import { ScrubContext } from './anonymize/config'
-import { ParsedMessageData } from './kafka/types'
-import { TeamForReplay } from './shared/teams/types'
-
-export interface AnonymizeStepInput {
- parsedMessage: ParsedMessageData
- team: TeamForReplay
-}
-
-export interface AnonymizeStepConfig {
- /** Shared, immutable scrub context (allow lists + tunables). */
- scrubContext: ScrubContext
-}
-
-/**
- * Anonymizes the parsed events in place before recording. Drops the message if any
- * event can't be anonymized — fail-closed, since blocks are written unencrypted.
- */
-export function createAnonymizeStep<T extends AnonymizeStepInput>(config: AnonymizeStepConfig): ProcessingStep<T, T> {
- const { scrubContext } = config
-
- return async function anonymizeStep(input) {
- const teamContext: ScrubContext = {
- ...scrubContext,
- firstPartyHosts: input.team.firstPartyHosts,
- }
- const { failed } = await anonymizeParsedMessage(teamContext, input.parsedMessage)
- if (failed) {
- return drop('anonymize_failed')
- }
- return ok(input)
- }
-}
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/anonymize/anonymize-event.test.ts b/nodejs/src/ingestion/pipelines/sessionreplay/anonymize/anonymize-event.test.ts
deleted file mode 100644
index e17d1dc972c9..000000000000
--- a/nodejs/src/ingestion/pipelines/sessionreplay/anonymize/anonymize-event.test.ts
+++ /dev/null
@@ -1,156 +0,0 @@
-import { anonymizeEvent } from './anonymize-event'
-import { defaultAllowLists } from './default-dict'
-
-describe('anonymize/event router', () => {
- const ctx = { allow: defaultAllowLists() }
-
- it('scrubs Input text', () => {
- const event: any = {
- type: 3,
- timestamp: 1,
- data: { source: 5, id: 1, text: 'Hello SecretName', isChecked: false },
- }
- expect(anonymizeEvent(ctx, event)).toBe(true)
- expect(event.data.text).toBe('Hello **********')
- })
-
- it('URL-scrubs Meta href and leaves width/height untouched', () => {
- const event: any = {
- type: 4,
- timestamp: 1,
- data: { href: 'https://example.com/api/v1/users/abc', width: 1280, height: 720 },
- }
- expect(anonymizeEvent(ctx, event)).toBe(true)
- expect(event.data.href).toBe('https://example.com/api/v1/users/[redacted]')
- expect(event.data.width).toBe(1280)
- expect(event.data.height).toBe(720)
- })
-
- it('passes through a FullSnapshot with nothing to scrub', () => {
- const event: any = {
- type: 2,
- timestamp: 1,
- data: { node: { type: 0, id: 1, childNodes: [] }, initialOffset: { top: 0, left: 0 } },
- }
- expect(anonymizeEvent(ctx, event)).toBe(false)
- })
-
- it('passes through mouse-move incremental events', () => {
- const event: any = {
- type: 3,
- timestamp: 1,
- data: { source: 1, positions: [{ x: 1, y: 2, id: 3, timeOffset: 0 }] },
- }
- expect(anonymizeEvent(ctx, event)).toBe(false)
- })
-
- it('passes through Load events', () => {
- const event: any = { type: 1, timestamp: 1, data: {} }
- expect(anonymizeEvent(ctx, event)).toBe(false)
- })
-
- const onePxPng =
- 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAIAAACQkWg2AAAACXBIWXMAAAPoAAAD6AG1e1JrAAAAJUlEQVQokWN4plEBRyInbOAIlzjDINRAjCJk8cGoYRAG60iMBwA8H08Qor0ygQAAAABJRU5ErkJggg=='
- test.each([
- [
- 'StyleSheetRule adds/replace/replaceSync',
- {
- source: 8,
- id: 1,
- adds: [{ rule: `.a{background:url(${onePxPng})}` }],
- replace: `.b{background:url(${onePxPng})}`,
- replaceSync: `.c{background:url(${onePxPng})}`,
- },
- ],
- [
- 'StyleDeclaration set value',
- { source: 13, id: 1, index: [0], set: { property: 'background', value: `url(${onePxPng})` } },
- ],
- [
- 'AdoptedStyleSheet rules',
- {
- source: 15,
- id: 1,
- styleIds: [1],
- styles: [{ styleId: 1, rules: [{ rule: `.a{background:url(${onePxPng})}` }] }],
- },
- ],
- ])('scrubs css data images in incremental stylesheet events: %s', (_name, data) => {
- const event: any = { type: 3, timestamp: 1, data }
- expect(anonymizeEvent(ctx, event)).toBe(true)
- expect(JSON.stringify(event)).not.toContain(onePxPng)
- })
-
- it('scrubs console plugin payload strings', () => {
- const event: any = {
- type: 6,
- timestamp: 1,
- data: { plugin: 'rrweb/console@1', payload: { level: 'info', payload: ['Hello SecretName'], trace: [] } },
- }
- expect(anonymizeEvent(ctx, event)).toBe(true)
- expect(event.data.payload.payload[0]).toBe('Hello **********')
- })
-
- it('scrubs network plugin request name and body', () => {
- const event: any = {
- type: 6,
- timestamp: 1,
- data: {
- plugin: 'rrweb/network@1',
- payload: { requests: [{ name: 'https://example.com/user/abc/edit', requestBody: 'Hello SecretName' }] },
- },
- }
- expect(anonymizeEvent(ctx, event)).toBe(true)
- expect(event.data.payload.requests[0].name).toBe('https://example.com/user/[redacted]/edit')
- expect(event.data.payload.requests[0].requestBody).toBe('Hello **********')
- })
-
- it('scrubs an arbitrary Custom payload generically', () => {
- const event: any = { type: 5, timestamp: 1, data: { tag: 'x', payload: { note: 'Hello SecretName' } } }
- expect(anonymizeEvent(ctx, event)).toBe(true)
- expect(event.data.payload.note).toBe('Hello **********')
- })
-
- it('scrubs an unknown plugin payload generically', () => {
- const event: any = {
- type: 6,
- timestamp: 1,
- data: { plugin: 'some/other-plugin@1', payload: { note: 'Hello SecretName' } },
- }
- expect(anonymizeEvent(ctx, event)).toBe(true)
- expect(event.data.payload.note).toBe('Hello **********')
- })
-
- it.each([
- ['IncrementalSnapshot', 3],
- ['Meta', 4],
- ['Custom', 5],
- ['Plugin', 6],
- ])('passes through %s events whose data is not an object', (_name, type) => {
- const event: any = { type, timestamp: 1, data: null }
- expect(anonymizeEvent(ctx, event)).toBe(false)
- })
-
- it('passes through incremental events with an unhandled source', () => {
- const event: any = { type: 3, timestamp: 1, data: { source: 99, foo: 'bar' } }
- expect(anonymizeEvent(ctx, event)).toBe(false)
- })
-
- it('passes through (no change) a malformed event with non-object data', () => {
- const event: any = { type: 2, timestamp: 1, data: null }
- expect(anonymizeEvent(ctx, event)).toBe(false)
- })
-
- it('throws when a scrubber errors, so the caller can fail closed', () => {
- // A throwing getter on `data` forces an exception inside routing. The
- // error must propagate (not be swallowed as "nothing to scrub").
- const event: any = {
- type: 2,
- timestamp: 1,
- get data() {
- throw new Error('boom')
- },
- }
- expect(() => anonymizeEvent(ctx, event)).toThrow('boom')
- })
-})
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/anonymize/anonymize-event.ts b/nodejs/src/ingestion/pipelines/sessionreplay/anonymize/anonymize-event.ts
deleted file mode 100644
index 687dda534f02..000000000000
--- a/nodejs/src/ingestion/pipelines/sessionreplay/anonymize/anonymize-event.ts
+++ /dev/null
@@ -1,187 +0,0 @@
-/** Routes each parsed rrweb event to the right scrubber by type/source. */
-import { logger } from '~/common/utils/logger'
-import { ParsedMessageData } from '~/ingestion/pipelines/sessionreplay/kafka/types'
-import { SessionRecordingIngesterMetrics } from '~/ingestion/pipelines/sessionreplay/metrics'
-import { RRWebEventSource, RRWebEventType } from '~/ingestion/pipelines/sessionreplay/rrweb-types'
-
-import { runBlurJobs } from './blur'
-import { scrubCanvasMutation } from './canvas'
-import { BlurCache, BlurJob, ScrubContext, ScrubTiming, isObject } from './config'
-import { scrubAdoptedStyleSheet, scrubStyleDeclaration, scrubStyleSheetRule } from './css'
-import { scrubCompressedFullSnapshot, scrubCompressedMutation } from './cv'
-import { scrubFullSnapshot, scrubMutation } from './dom'
-import { scrubText } from './text'
-import { scrubUrl } from './url'
-import { scrubConsolePlugin, scrubGenericField, scrubNetworkPlugin } from './value'
-
-const NETWORK_PLUGIN = 'rrweb/network@1'
-const CONSOLE_PLUGIN = 'rrweb/console@1'
-
-const yieldToEventLoop = (): Promise<void> => new Promise((resolve) => setImmediate(resolve))
-
-// Diagnostic: log the per-message time breakdown when a message takes longer than this to anonymize.
-const ANON_SLOW_LOG_THRESHOLD_MS = 5000
-
-/**
- * Anonymizes every event in a parsed message in place, then awaits its blur jobs.
- * Fails closed: returns `failed: true` if any event errors, so the caller can drop
- * the message rather than write un-anonymized data to the unencrypted ML bucket.
- */
-export async function anonymizeParsedMessage(
- scrubContext: ScrubContext,
- parsedMessage: ParsedMessageData
-): Promise<{ failed: boolean }> {
- const blurJobs: BlurJob[] = []
- // One memo per Kafka message: identical images across its rrweb events share a single sharp call.
- const blurCache: BlurCache = new Map()
- const timing: ScrubTiming = { decompressMs: 0, recompressMs: 0 }
- const ctx: ScrubContext = { ...scrubContext, blurJobs, blurCache, timing }
-
- const scrubStart = performance.now()
- let eventCount = 0
- for (const events of Object.values(parsedMessage.eventsByWindowId)) {
- for (const event of events) {
- try {
- anonymizeEvent(ctx, event)
- } catch (error) {
- logger.warn('🙈', 'anonymize_event_failed', {
- error: String(error),
- type: isObject(event) ? event.type : undefined,
- })
- SessionRecordingIngesterMetrics.incrementMlAnonymizeFailed('ts')
- return { failed: true }
- }
- eventCount++
- }
- }
- // scrubMs is synchronous (on the event loop); blurMs is the off-thread sharp work we await.
- const scrubMs = performance.now() - scrubStart
-
- const blurStart = performance.now()
- await runBlurJobs(blurJobs)
- const blurMs = performance.now() - blurStart
-
- SessionRecordingIngesterMetrics.observeMlAnonymizeDuration('ts', scrubMs + blurMs)
-
- if (scrubMs + blurMs > ANON_SLOW_LOG_THRESHOLD_MS) {
- logger.warn('🕒', 'anonymize_slow_breakdown', {
- totalMs: Math.round(scrubMs + blurMs),
- scrubMs: Math.round(scrubMs),
- blurMs: Math.round(blurMs),
- decompressMs: Math.round(timing.decompressMs),
- recompressMs: Math.round(timing.recompressMs),
- walkMs: Math.round(scrubMs - timing.decompressMs - timing.recompressMs),
- events: eventCount,
- blurJobs: blurJobs.length,
- sessionId: parsedMessage.session_id,
- topic: parsedMessage.metadata.topic,
- partition: parsedMessage.metadata.partition,
- offset: parsedMessage.metadata.offset,
- kafkaTimestamp: parsedMessage.metadata.timestamp,
- rawSize: parsedMessage.metadata.rawSize,
- })
- }
-
- // Macrotask break so a batch of messages doesn't scrub fully synchronously and starve the loop.
- await yieldToEventLoop()
- return { failed: false }
-}
-
-/**
- * Scrubs a single event in place, returning whether it changed. Throws if a
- * scrubber errors — callers must treat a throw as "could not anonymize", never
- * as "nothing to scrub".
- */
-export function anonymizeEvent(ctx: ScrubContext, event: unknown): boolean {
- if (!isObject(event)) {
- return false
- }
- return routeEvent(ctx, event)
-}
-
-function routeEvent(ctx: ScrubContext, event: Record<string, unknown>): boolean {
- const compressed = event.cv != null
- const data = event.data
-
- switch (event.type) {
- case RRWebEventType.FullSnapshot:
- return compressed ? scrubCompressedFullSnapshot(ctx, event) : scrubFullSnapshot(ctx, data)
-
- case RRWebEventType.IncrementalSnapshot: {
- if (!isObject(data)) {
- return false
- }
- if (data.source === RRWebEventSource.Mutation) {
- return compressed ? scrubCompressedMutation(ctx, event) : scrubMutation(ctx, data)
- }
- if (data.source === RRWebEventSource.Input) {
- return scrubStringField(ctx, data, 'text', 'text')
- }
- if (data.source === RRWebEventSource.CanvasMutation) {
- return scrubCanvasMutation(ctx, data)
- }
- if (data.source === RRWebEventSource.StyleSheetRule) {
- return scrubStyleSheetRule(ctx, data)
- }
- if (data.source === RRWebEventSource.StyleDeclaration) {
- return scrubStyleDeclaration(ctx, data)
- }
- if (data.source === RRWebEventSource.AdoptedStyleSheet) {
- return scrubAdoptedStyleSheet(ctx, data)
- }
- return false
- }
-
- case RRWebEventType.Meta: {
- // Meta `href` is the page URL — also strip the authority and rewrite the host to
- // example.com (Meta only for now).
- if (!isObject(data) || typeof data.href !== 'string') {
- return false
- }
- const r = scrubUrl(ctx, data.href, { collapseHost: true })
- if (r.changed) {
- data.href = r.value
- return true
- }
- return false
- }
-
- case RRWebEventType.Custom:
- return isObject(data) ? scrubGenericField(ctx, data, 'payload') : false
-
- case RRWebEventType.Plugin: {
- if (!isObject(data)) {
- return false
- }
- if (data.plugin === NETWORK_PLUGIN) {
- return scrubNetworkPlugin(ctx, data, 'payload')
- }
- if (data.plugin === CONSOLE_PLUGIN) {
- return scrubConsolePlugin(ctx, data, 'payload')
- }
- return scrubGenericField(ctx, data, 'payload')
- }
-
- default:
- // DomContentLoaded, Load, unknown types: pass-through.
- return false
- }
-}
-
-function scrubStringField(
- ctx: ScrubContext,
- owner: Record<string, unknown>,
- key: string,
- kind: 'text' | 'url'
-): boolean {
- const value = owner[key]
- if (typeof value !== 'string') {
- return false
- }
- const result = kind === 'url' ? scrubUrl(ctx, value) : scrubText(ctx, value)
- if (result.changed) {
- owner[key] = result.value
- return true
- }
- return false
-}
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/anonymize/assets.test.ts b/nodejs/src/ingestion/pipelines/sessionreplay/anonymize/assets.test.ts
deleted file mode 100644
index ac61bbd42f80..000000000000
--- a/nodejs/src/ingestion/pipelines/sessionreplay/anonymize/assets.test.ts
+++ /dev/null
@@ -1,35 +0,0 @@
-import { PLACEHOLDER_SRC, applyBlur, isMediaTag } from './assets'
-import { defaultAllowLists } from './default-dict'
-
-describe('anonymize/assets', () => {
- const ctx = { allow: defaultAllowLists() }
-
- it('classifies media tags', () => {
- for (const tag of ['img', 'IMG', 'image', 'video', 'audio', 'source', 'track']) {
- expect(isMediaTag(tag)).toBe(true)
- }
- for (const tag of ['iframe', 'div', 'a']) {
- expect(isMediaTag(tag)).toBe(false)
- }
- })
-
- it('replaces a remote src with the placeholder and stashes a host+path-scrubbed original', () => {
- const attrs: Record<string, unknown> = { src: 'https://cdn.acme.io/users/42/avatar.png?t=secret' }
- applyBlur(ctx, attrs)
- expect(attrs.src).toBe(PLACEHOLDER_SRC)
- const stash = attrs['data-anon-original-src'] as string
- expect(typeof stash).toBe('string')
- expect(stash).toContain('example.com') // host rewritten
- expect(stash).not.toContain('acme') // original host gone
- expect(stash).not.toContain('42') // path identifier redacted
- expect(stash).not.toContain('secret') // query dropped
- })
-
- it('replaces a data-image src with the placeholder', () => {
- const attrs: Record<string, unknown> = { src: 'data:image/png;base64,AAAA' }
- applyBlur(ctx, attrs)
- expect(attrs.src).toBe(PLACEHOLDER_SRC)
- // data-image has no URL to preserve, so no stash is added.
- expect('data-anon-original-src' in attrs).toBe(false)
- })
-})
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/anonymize/assets.ts b/nodejs/src/ingestion/pipelines/sessionreplay/anonymize/assets.ts
deleted file mode 100644
index 1c95bc6eb4bb..000000000000
--- a/nodejs/src/ingestion/pipelines/sessionreplay/anonymize/assets.ts
+++ /dev/null
@@ -1,82 +0,0 @@
-/** Media detection + placeholder/blur dispatch. */
-import { BLANK_IMAGE_DATA_URI, blurImageDataUri, isImageDataUri, memoizedBlur } from './blur'
-import { ScrubContext } from './config'
-import { scrubUrl } from './url'
-
-// rrweb inlines rendered pixels (a `toDataURL()` snapshot) into this attribute — for `<canvas>`
-// in a FullSnapshot/adds, and for `<img>` when image inlining is on. It holds raw drawn content.
-export const INLINE_IMAGE_ATTR = 'rr_dataURL'
-
-export const PLACEHOLDER_SRC =
- "data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 80 80'><rect width='80' height='80' fill='%23f3f4f6'/><rect x='6' y='6' width='68' height='68' fill='none' stroke='%23d1d5db' stroke-width='2' rx='6'/><circle cx='26' cy='26' r='6' fill='%239ca3af'/><path d='M14 60 L34 40 L48 50 L66 32 L66 66 L14 66 Z' fill='%239ca3af'/></svg>"
-
-export const MEDIA_SRC_ATTRS = ['src', 'rr_src', 'srcset', 'href', 'xlink:href', 'poster']
-
-export function isMediaTag(tag: string): boolean {
- switch (tag.toLowerCase()) {
- case 'img':
- case 'image':
- case 'video':
- case 'audio':
- case 'source':
- case 'track':
- case 'picture':
- return true
- default:
- return false
- }
-}
-
-export function isMediaSrcAttr(name: string): boolean {
- return MEDIA_SRC_ATTRS.includes(name)
-}
-
-/** True if an attribute map contains any media-source attribute. */
-export function hasMediaSrcAttr(attrs: Record<string, unknown>): boolean {
- return MEDIA_SRC_ATTRS.some((name) => Object.prototype.hasOwnProperty.call(attrs, name))
-}
-
-/**
- * Blur an inlined-image data URI held in an attribute (a `<canvas>`/`<img>` `rr_dataURL`).
- * Blanks it synchronously (fail-safe) and defers the real blur. Returns whether it acted.
- */
-export function blurInlineImageAttr(ctx: ScrubContext, attrs: Record<string, unknown>, name: string): boolean {
- const value = attrs[name]
- if (typeof value !== 'string' || !isImageDataUri(value)) {
- return false
- }
- const original = value
- attrs[name] = BLANK_IMAGE_DATA_URI
- ctx.blurJobs?.push(async () => {
- const blurred = await memoizedBlur(ctx.blurCache, original, () => blurImageDataUri(original))
- if (blurred !== null) {
- attrs[name] = blurred
- }
- })
- return true
-}
-
-/** Replace a media element's source attrs with the placeholder (queuing a blur job for data-images). */
-export function applyBlur(ctx: ScrubContext, attrs: Record<string, unknown>): void {
- for (const key of MEDIA_SRC_ATTRS) {
- const existing = attrs[key]
- if (typeof existing !== 'string') {
- continue
- }
- if (isImageDataUri(existing)) {
- attrs[key] = PLACEHOLDER_SRC
- ctx.blurJobs?.push(async () => {
- const blurred = await memoizedBlur(ctx.blurCache, existing, () => blurImageDataUri(existing))
- if (blurred !== null) {
- attrs[key] = blurred
- }
- })
- } else {
- // Stash the scrubbed original under a namespaced attr (won't collide with app
- // `data-original-*`), host-scrubbed too so the CDN host can't leak.
- const scrubbed = scrubUrl(ctx, existing, { collapseHost: true })
- attrs[key] = PLACEHOLDER_SRC
- attrs[`data-anon-original-${key}`] = scrubbed.changed ? scrubbed.value : existing
- }
- }
-}
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/anonymize/blur.test.ts b/nodejs/src/ingestion/pipelines/sessionreplay/anonymize/blur.test.ts
deleted file mode 100644
index 1c0b984f1a72..000000000000
--- a/nodejs/src/ingestion/pipelines/sessionreplay/anonymize/blur.test.ts
+++ /dev/null
@@ -1,107 +0,0 @@
-import sharp from 'sharp'
-
-import { blurImageDataUri, isImageDataUri, memoizedBlur, runBlurJobs } from './blur'
-import { BlurCache } from './config'
-
-// A small patterned PNG (portable across libvips/libpng builds; a bare 1x1 is rejected by some,
-// and a solid color blurs to identical bytes, so we use a checkerboard the blur visibly changes).
-const ONE_PX_PNG =
- 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAIAAACQkWg2AAAACXBIWXMAAAPoAAAD6AG1e1JrAAAAJUlEQVQokWN4plEBRyInbOAIlzjDINRAjCJk8cGoYRAG60iMBwA8H08Qor0ygQAAAABJRU5ErkJggg=='
-
-describe('anonymize/blur', () => {
- it('detects image data URIs', () => {
- expect(isImageDataUri('data:image/png;base64,AAAA')).toBe(true)
- expect(isImageDataUri('https://example.com/x.png')).toBe(false)
- expect(isImageDataUri('data:text/plain,hi')).toBe(false)
- })
-
- it('gaussian-blurs a base64 image into a PNG data URI', async () => {
- const out = await blurImageDataUri(ONE_PX_PNG)
- expect(out).not.toBeNull()
- expect(out!.startsWith('data:image/png;base64,')).toBe(true)
- // It is a real, different encoding, not the original bytes echoed back.
- expect(out).not.toBe(ONE_PX_PNG)
- })
-
- it('falls back to a downsample when the gaussian blur throws', async () => {
- // Force the Gaussian path to fail; the resize-only fallback should still produce an image.
- const proto = Object.getPrototypeOf(sharp(Buffer.from([0])))
- const spy = jest.spyOn(proto, 'blur').mockImplementation(() => {
- throw new Error('blur boom')
- })
- try {
- const out = await blurImageDataUri(ONE_PX_PNG)
- expect(out).not.toBeNull()
- expect(out!.startsWith('data:image/png;base64,')).toBe(true)
- } finally {
- spy.mockRestore()
- }
- })
-
- it('returns null for non-image and remote sources', async () => {
- expect(await blurImageDataUri('https://example.com/x.png')).toBeNull()
- expect(await blurImageDataUri('data:text/plain;base64,aGk=')).toBeNull()
- expect(await blurImageDataUri('data:image/png,notbase64')).toBeNull()
- // No comma → not a data URI we can parse.
- expect(await blurImageDataUri('data:image/png')).toBeNull()
- })
-
- it('runBlurJobs is a no-op for an empty or absent job list', async () => {
- await expect(runBlurJobs([])).resolves.toBeUndefined()
- await expect(runBlurJobs(undefined)).resolves.toBeUndefined()
- })
-
- it('runBlurJobs runs every job', async () => {
- let ran = 0
- const bump = () => {
- ran++
- return Promise.resolve()
- }
- await runBlurJobs([bump, bump])
- expect(ran).toBe(2)
- })
-
- it('memoizedBlur runs compute once per key and shares the result (the in-batch dedup)', async () => {
- const cache: BlurCache = new Map()
- let calls = 0
- const compute = () => {
- calls++
- return Promise.resolve('blurred')
- }
- // The regression this guards: without dedup, one image repeated N times in a message
- // blurs N times. Same key must collapse to a single compute.
- const [a, b] = await Promise.all([memoizedBlur(cache, 'img', compute), memoizedBlur(cache, 'img', compute)])
- expect(calls).toBe(1)
- expect(a).toBe('blurred')
- expect(b).toBe('blurred')
-
- // A distinct key is a distinct image — it recomputes.
- await memoizedBlur(cache, 'other', compute)
- expect(calls).toBe(2)
- })
-
- it('memoizedBlur without a cache always computes (dedup is opt-in via the cache)', async () => {
- let calls = 0
- const compute = () => {
- calls++
- return Promise.resolve('blurred')
- }
- await memoizedBlur(undefined, 'img', compute)
- await memoizedBlur(undefined, 'img', compute)
- expect(calls).toBe(2)
- })
-
- it('runBlurJobs swallows a job that throws (already-blanked image is left as-is)', async () => {
- let ran = 0
- await expect(
- runBlurJobs([
- () => Promise.reject(new Error('boom')),
- () => {
- ran++
- return Promise.resolve()
- },
- ])
- ).resolves.toBeUndefined()
- expect(ran).toBe(1)
- })
-})
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/anonymize/blur.ts b/nodejs/src/ingestion/pipelines/sessionreplay/anonymize/blur.ts
deleted file mode 100644
index 8bd20d1ce420..000000000000
--- a/nodejs/src/ingestion/pipelines/sessionreplay/anonymize/blur.ts
+++ /dev/null
@@ -1,132 +0,0 @@
-/** Downsample + blur media/canvas images — scene stays legible, faces/text don't. Run deferred. */
-import sharp from 'sharp'
-
-import { BlurCache, BlurJob } from './config'
-
-// The ml-mirror scrub sidecar duplicates these (it's outside the workspace); keep the two in sync.
-const DOWNSAMPLE_RATIO = 0.12
-const BLUR_SIGMA = 2.34
-const MAX_LONG_SIDE = 96
-
-/** A 1×1 transparent PNG: the fail-safe stand-in dropped in before (and if) the real blur lands. */
-export const BLANK_PNG_BASE64 =
- 'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNk+M9QDwADhgGAWjR9awAAAABJRU5ErkJggg=='
-export const BLANK_IMAGE_DATA_URI = `data:image/png;base64,${BLANK_PNG_BASE64}`
-
-export function isImageDataUri(s: string): boolean {
- return s.startsWith('data:image/')
-}
-
-/** Scale to DOWNSAMPLE_RATIO, but never leave the long side above MAX_LONG_SIDE; floored at 1px. */
-function targetDims(width: unknown, height: unknown): [number, number] {
- const w = typeof width === 'number' && width > 0 ? width : 1
- const h = typeof height === 'number' && height > 0 ? height : 1
- const scale = Math.min(DOWNSAMPLE_RATIO, MAX_LONG_SIDE / Math.max(w, h))
- return [Math.max(1, Math.round(w * scale)), Math.max(1, Math.round(h * scale))]
-}
-
-/** Downsample a base64 image data URI to a fraction of its size + a blur, as a PNG; null if it can't. */
-export async function blurImageDataUri(s: string): Promise<string | null> {
- if (!s.startsWith('data:')) {
- return null
- }
- const comma = s.indexOf(',')
- if (comma === -1) {
- return null
- }
- const meta = s.slice('data:'.length, comma)
- if (!meta.includes('base64') || !meta.startsWith('image/')) {
- return null
- }
- const bytes = Buffer.from(s.slice(comma + 1), 'base64')
-
- let tw: number, th: number
- try {
- const info = await sharp(bytes).metadata()
- ;[tw, th] = targetDims(info.width, info.height)
- } catch {
- return null // can't even read the header
- }
- // Primary: downsample + Gaussian blur.
- try {
- const out = await sharp(bytes).resize(tw, th, { fit: 'fill' }).blur(BLUR_SIGMA).png().toBuffer()
- return `data:image/png;base64,${out.toString('base64')}`
- } catch {
- // Blur failed on an odd input — fall through to a plain downsample (still de-identifies).
- }
- try {
- const out = await sharp(bytes).resize(tw, th, { fit: 'fill' }).png().toBuffer()
- return `data:image/png;base64,${out.toString('base64')}`
- } catch {
- return null
- }
-}
-
-/**
- * De-identify raw RGBA pixels: downsample to DOWNSAMPLE_RATIO + a blur, then scale back up to the
- * original W×H, preserving byte length (`4·W·H`) so it slots back into a `putImageData` ImageData.
- */
-export async function pixelateRawRgba(base64: string, width: number, height: number): Promise<string | null> {
- try {
- const buf = Buffer.from(base64, 'base64')
- if (buf.length !== width * height * 4) {
- return null
- }
- const [sw, sh] = targetDims(width, height)
- const small = await sharp(buf, { raw: { width, height, channels: 4 } })
- .resize(sw, sh, { fit: 'fill' })
- .blur(BLUR_SIGMA)
- .ensureAlpha()
- .raw()
- .toBuffer()
- const out = await sharp(small, { raw: { width: sw, height: sh, channels: 4 } })
- .resize(width, height, { fit: 'fill' })
- .ensureAlpha()
- .raw()
- .toBuffer()
- return out.length === width * height * 4 ? out.toString('base64') : null
- } catch {
- return null
- }
-}
-
-/**
- * In-batch blur memo: within one Kafka message the same image often recurs thousands of times across
- * its rrweb events (a canvas redrawing one sprite, a repeated background), and both blur functions are
- * pure in their input. Sharing one settled Promise per distinct input collapses that fan-out to a
- * single sharp call. Neither producer rejects (both catch and return null), so a cached entry never
- * poisons its consumers. Scope is one Kafka message — the map is discarded when its blur jobs finish.
- */
-export function memoizedBlur(
- cache: BlurCache | undefined,
- key: string,
- compute: () => Promise<string | null>
-): Promise<string | null> {
- if (!cache) {
- return compute()
- }
- const existing = cache.get(key)
- if (existing !== undefined) {
- return existing
- }
- const pending = compute()
- cache.set(key, pending)
- return pending
-}
-
-/** Run deferred blur jobs concurrently. A job that throws is swallowed — the image was already
- * blanked synchronously, so a failed enhancement degrades to the blank rather than leaking. */
-export async function runBlurJobs(jobs: BlurJob[] | undefined): Promise<void> {
- if (!jobs || jobs.length === 0) {
- return
- }
- await Promise.all(
- jobs.map(async (job) => {
- try {
- await job()
- } catch {
- // image already neutralized synchronously; skip the enhancement
- }
- })
- )
-}
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/anonymize/canvas.test.ts b/nodejs/src/ingestion/pipelines/sessionreplay/anonymize/canvas.test.ts
deleted file mode 100644
index ab4046e61e41..000000000000
--- a/nodejs/src/ingestion/pipelines/sessionreplay/anonymize/canvas.test.ts
+++ /dev/null
@@ -1,190 +0,0 @@
-import { runBlurJobs } from './blur'
-import { scrubCanvasMutation } from './canvas'
-import { BlurJob, ScrubContext } from './config'
-import { defaultAllowLists } from './default-dict'
-
-// A small patterned PNG (portable across libvips/libpng builds; solid colors blur to identical
-// bytes, so we use a checkerboard the blur visibly changes).
-const ONE_PX_PNG_BASE64 =
- 'iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAIAAACQkWg2AAAACXBIWXMAAAPoAAAD6AG1e1JrAAAAJUlEQVQokWN4plEBRyInbOAIlzjDINRAjCJk8cGoYRAG60iMBwA8H08Qor0ygQAAAABJRU5ErkJggg=='
-// Must match BLANK_PNG_BASE64 in blur.ts (the fail-safe placeholder; never re-decoded).
-const BLANK_PNG_BASE64 =
- 'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNk+M9QDwADhgGAWjR9awAAAABJRU5ErkJggg=='
-
-function makeCtx(): ScrubContext & { blurJobs: BlurJob[] } {
- return { allow: defaultAllowLists(), blurJobs: [] }
-}
-
-describe('anonymize/canvas', () => {
- it('redacts text drawn via fillText/strokeText (batched commands)', () => {
- const ctx = makeCtx()
- const data = {
- source: 9,
- id: 1,
- type: 0,
- commands: [
- { property: 'fillText', args: ['SecretCustomerName', 10, 20] },
- { property: 'strokeText', args: ['AnotherSecret', 0, 0] },
- ],
- }
- expect(scrubCanvasMutation(ctx, data)).toBe(true)
- expect(data.commands[0].args[0]).not.toContain('Secret')
- expect(data.commands[0].args[0]).toMatch(/^\*+$/)
- expect(data.commands[1].args[0]).toMatch(/^\*+$/)
- // Numeric coordinates are untouched.
- expect(data.commands[0].args[1]).toBe(10)
- })
-
- it('redacts text in the flattened single-command form', () => {
- const ctx = makeCtx()
- const data = { source: 9, id: 1, type: 0, property: 'fillText', args: ['HelloSecret', 1, 2] }
- expect(scrubCanvasMutation(ctx, data)).toBe(true)
- expect(data.args[0]).toMatch(/^\*+$/)
- })
-
- it('blanks a data:image arg synchronously and queues a blur job', () => {
- const ctx = makeCtx()
- const data = {
- source: 9,
- id: 1,
- type: 0,
- commands: [{ property: 'drawImage', args: [`data:image/png;base64,${ONE_PX_PNG_BASE64}`, 0, 0] }],
- }
- expect(scrubCanvasMutation(ctx, data)).toBe(true)
- // Raw image gone immediately (fail-safe), blur deferred.
- expect(data.commands[0].args[0]).not.toContain(ONE_PX_PNG_BASE64)
- expect(data.commands[0].args[0]).toMatch(/^data:image\/png;base64,/)
- expect(ctx.blurJobs).toHaveLength(1)
- })
-
- it('blanks an encoded image Blob snapshot and queues a blur job (ImageBitmap → Blob → ArrayBuffer)', () => {
- const ctx = makeCtx()
- const ab = { rr_type: 'ArrayBuffer', base64: ONE_PX_PNG_BASE64 }
- const data = {
- source: 9,
- id: 1,
- type: 0,
- commands: [
- {
- property: 'drawImage',
- args: [
- { rr_type: 'ImageBitmap', args: [{ rr_type: 'Blob', type: 'image/png', data: [ab] }] },
- 0,
- 0,
- ],
- },
- ],
- }
- expect(scrubCanvasMutation(ctx, data)).toBe(true)
- expect(ab.base64).toBe(BLANK_PNG_BASE64)
- expect(ctx.blurJobs).toHaveLength(1)
- })
-
- it('blanks a data:image src and URL-scrubs a remote src', () => {
- const ctx = makeCtx()
- const data = {
- source: 9,
- id: 1,
- type: 0,
- commands: [
- {
- property: 'drawImage',
- args: [{ rr_type: 'HTMLImageElement', src: `data:image/png;base64,${ONE_PX_PNG_BASE64}` }],
- },
- {
- property: 'drawImage',
- args: [{ rr_type: 'HTMLImageElement', src: 'https://cdn.example.com/users/SecretUser/a.png' }],
- },
- ],
- }
- expect(scrubCanvasMutation(ctx, data)).toBe(true)
- expect((data.commands[0].args[0] as any).src).toMatch(/^data:image\/png;base64,/)
- expect((data.commands[0].args[0] as any).src).not.toContain(ONE_PX_PNG_BASE64)
- expect((data.commands[1].args[0] as any).src).not.toContain('SecretUser')
- expect((data.commands[1].args[0] as any).src).toContain('https://cdn.example.com')
- expect(ctx.blurJobs).toHaveLength(1)
- })
-
- it('leaves non-image args (numbers, non-image ArrayBuffers) untouched', () => {
- const ctx = makeCtx()
- const buf = { rr_type: 'ArrayBuffer', base64: 'V0VCR0xCVUZGRVI=' } // not inside an image Blob
- const data = {
- source: 9,
- id: 1,
- type: 1,
- commands: [
- { property: 'setTransform', args: [1, 0, 0, 1, 0, 0] },
- { property: 'bufferData', args: [34962, buf, 35044] },
- ],
- }
- expect(scrubCanvasMutation(ctx, data)).toBe(false)
- expect(buf.base64).toBe('V0VCR0xCVUZGRVI=')
- expect(ctx.blurJobs).toHaveLength(0)
- })
-
- it('runs queued blur jobs end to end, swapping the blank for a real blurred image', async () => {
- const ctx = makeCtx()
- const ab = { rr_type: 'ArrayBuffer', base64: ONE_PX_PNG_BASE64 }
- const data = {
- source: 9,
- id: 1,
- type: 0,
- commands: [{ property: 'drawImage', args: [{ rr_type: 'Blob', type: 'image/png', data: [ab] }, 0, 0] }],
- }
- scrubCanvasMutation(ctx, data)
- await runBlurJobs(ctx.blurJobs)
- // After blurring: not the blank placeholder and not the original.
- expect(ab.base64).not.toBe(BLANK_PNG_BASE64)
- expect(ab.base64).not.toBe(ONE_PX_PNG_BASE64)
- })
-
- // Build a putImageData command holding a W×H RGBA buffer with a non-uniform pattern.
- const W = 32
- const H = 32
- function rawImageDataCommand(): { ab: { rr_type: string; base64: string }; data: Record<string, unknown> } {
- const rgba = Buffer.alloc(W * H * 4)
- for (let i = 0; i < W * H; i++) {
- rgba[i * 4] = (i * 7) & 255
- rgba[i * 4 + 1] = (i * 3) & 255
- rgba[i * 4 + 2] = 200
- rgba[i * 4 + 3] = 255
- }
- const ab = { rr_type: 'ArrayBuffer', base64: rgba.toString('base64') }
- const data = {
- source: 9,
- id: 1,
- type: 0,
- property: 'putImageData',
- args: [
- { rr_type: 'ImageData', args: [{ rr_type: 'Uint8ClampedArray', args: [ab, 0, W * H * 4] }, W, H] },
- 0,
- 0,
- ],
- }
- return { ab, data }
- }
-
- it('blanks raw ImageData pixels synchronously and queues a pixelate job', () => {
- const ctx = makeCtx()
- const { ab, data } = rawImageDataCommand()
- const original = ab.base64
- expect(scrubCanvasMutation(ctx, data)).toBe(true)
- const blanked = Buffer.from(ab.base64, 'base64')
- expect(blanked.length).toBe(W * H * 4)
- expect(blanked.every((b) => b === 0)).toBe(true) // raw pixels gone immediately
- expect(ab.base64).not.toBe(original)
- expect(ctx.blurJobs).toHaveLength(1)
- })
-
- it('runs the ImageData pixelate job: same byte length, restored content, not the original', async () => {
- const ctx = makeCtx()
- const { ab, data } = rawImageDataCommand()
- const original = ab.base64
- scrubCanvasMutation(ctx, data)
- await runBlurJobs(ctx.blurJobs)
- const out = Buffer.from(ab.base64, 'base64')
- expect(out.length).toBe(W * H * 4) // dimensions preserved for putImageData
- expect(out.every((b) => b === 0)).toBe(false) // pixelated content restored
- expect(ab.base64).not.toBe(original) // but not the original detail
- })
-})
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/anonymize/canvas.ts b/nodejs/src/ingestion/pipelines/sessionreplay/anonymize/canvas.ts
deleted file mode 100644
index 4de15bb17d0c..000000000000
--- a/nodejs/src/ingestion/pipelines/sessionreplay/anonymize/canvas.ts
+++ /dev/null
@@ -1,276 +0,0 @@
-/**
- * Scrubs rrweb CanvasMutation events: redacts text drawn via fill/strokeText and
- * Gaussian-blurs drawn images and canvas snapshots.
- *
- * Canvas data is either batched (`{ commands: [{property, args, setter?}] }`) or a
- * single flattened command (`{ property, args, setter? }`). Each `args` entry is a
- * recursive `CanvasArg`: primitives, arrays, or serialized objects —
- * { rr_type: 'ArrayBuffer', base64 }
- * { rr_type: 'Blob', data: CanvasArg[], type? } // encoded image snapshot
- * { rr_type, src } // HTMLImageElement etc.
- * { rr_type, args: CanvasArg[] } // ImageBitmap etc.
- * { rr_type: 'ImageData', args: [pixels, w, h] } // putImageData raw RGBA
- * Images are neutralized synchronously (fail-safe) and the real downsampled/blurred
- * result is swapped in by the deferred blur job on success.
- */
-import {
- BLANK_IMAGE_DATA_URI,
- BLANK_PNG_BASE64,
- blurImageDataUri,
- isImageDataUri,
- memoizedBlur,
- pixelateRawRgba,
-} from './blur'
-import { ScrubContext, isObject } from './config'
-import { scrubText } from './text'
-import { scrubUrl } from './url'
-
-// Canvas API calls whose leading string arguments are user-visible text.
-const TEXT_COMMANDS = new Set(['fillText', 'strokeText'])
-
-/** Scrub a CanvasMutation `data` object in place. Returns whether anything changed. */
-export function scrubCanvasMutation(ctx: ScrubContext, data: Record<string, unknown>): boolean {
- let changed = false
- if (Array.isArray(data.commands)) {
- for (const cmd of data.commands) {
- if (isObject(cmd)) {
- changed = scrubCommand(ctx, cmd) || changed
- }
- }
- } else if (typeof data.property === 'string') {
- // Flattened single-command form: `data` itself is the command.
- changed = scrubCommand(ctx, data) || changed
- }
- return changed
-}
-
-function scrubCommand(ctx: ScrubContext, cmd: Record<string, unknown>): boolean {
- if (!Array.isArray(cmd.args)) {
- return false
- }
- const args = cmd.args
- let changed = false
-
- // Text drawn onto the canvas: fillText/strokeText take the text as leading string args.
- if (typeof cmd.property === 'string' && TEXT_COMMANDS.has(cmd.property)) {
- for (let i = 0; i < args.length; i++) {
- if (typeof args[i] === 'string') {
- const result = scrubText(ctx, args[i])
- if (result.changed) {
- args[i] = result.value
- changed = true
- }
- }
- }
- }
-
- // Images/snapshots can appear anywhere in the (recursive) arg tree.
- for (let i = 0; i < args.length; i++) {
- changed = blurCanvasArg(ctx, args, i) || changed
- }
- return changed
-}
-
-/** Recursively neutralize+blur image data inside a canvas arg, mutating in place. */
-function blurCanvasArg(ctx: ScrubContext, container: any, key: string | number): boolean {
- const value = container[key]
-
- if (typeof value === 'string') {
- if (isImageDataUri(value)) {
- queueImageBlur(ctx, value, (blurred) => (container[key] = blurred))
- container[key] = BLANK_IMAGE_DATA_URI
- return true
- }
- return false
- }
-
- if (Array.isArray(value)) {
- let changed = false
- for (let i = 0; i < value.length; i++) {
- changed = blurCanvasArg(ctx, value, i) || changed
- }
- return changed
- }
-
- if (!isObject(value)) {
- return false
- }
-
- // Serialized image element: { rr_type, src }. Data-URI src is an embedded image; a
- // remote src is a URL that may itself carry PII.
- if (typeof value.src === 'string') {
- if (isImageDataUri(value.src)) {
- const original = value.src
- value.src = BLANK_IMAGE_DATA_URI
- queueImageBlur(ctx, original, (blurred) => (value.src = blurred))
- return true
- }
- const result = scrubUrl(ctx, value.src)
- if (result.changed) {
- value.src = result.value
- return true
- }
- return false
- }
-
- // Encoded image snapshot: { rr_type: 'Blob', type: 'image/...', data: [ {rr_type:'ArrayBuffer', base64} ] }.
- if (value.rr_type === 'Blob' && typeof value.type === 'string' && value.type.startsWith('image/')) {
- return blurBlobImage(ctx, value)
- }
-
- // Raw pixels: { rr_type: 'ImageData', args: [pixels, width, height] } (putImageData).
- if (value.rr_type === 'ImageData') {
- return blurImageData(ctx, value)
- }
-
- // Otherwise recurse into nested arg/data arrays (ImageBitmap → Blob, etc.).
- let changed = false
- if (Array.isArray(value.args)) {
- for (let i = 0; i < value.args.length; i++) {
- changed = blurCanvasArg(ctx, value.args, i) || changed
- }
- }
- if (Array.isArray(value.data)) {
- for (let i = 0; i < value.data.length; i++) {
- changed = blurCanvasArg(ctx, value.data, i) || changed
- }
- }
- return changed
-}
-
-/** Blur the encoded image bytes inside an image Blob, neutralizing them first (fail-safe). */
-function blurBlobImage(ctx: ScrubContext, blob: Record<string, unknown>): boolean {
- const data = blob.data
- if (!Array.isArray(data)) {
- return false
- }
- const ab = data.find(
- (d): d is Record<string, unknown> => isObject(d) && d.rr_type === 'ArrayBuffer' && typeof d.base64 === 'string'
- )
- if (!ab) {
- return false
- }
- const mime = typeof blob.type === 'string' ? blob.type : 'image/png'
- const original = `data:${mime};base64,${ab.base64 as string}`
- // Fail-safe: drop the raw snapshot to a blank pixel now; the job swaps in the blur on success.
- ab.base64 = BLANK_PNG_BASE64
- blob.type = 'image/png'
- queueImageBlur(ctx, original, (blurred) => {
- const parts = splitDataUri(blurred)
- if (parts) {
- ab.base64 = parts.base64
- blob.type = parts.mime
- }
- })
- return true
-}
-
-function queueImageBlur(ctx: ScrubContext, dataUri: string, apply: (blurred: string) => void): void {
- ctx.blurJobs?.push(async () => {
- const blurred = await memoizedBlur(ctx.blurCache, dataUri, () => blurImageDataUri(dataUri))
- if (blurred !== null) {
- apply(blurred)
- }
- })
-}
-
-interface RawLoc {
- ab: Record<string, unknown>
- start: number
- length: number
-}
-
-/** Locate the RGBA ArrayBuffer behind an ImageData's pixel descriptor (direct or typed-array-wrapped). */
-function findRawBuffer(desc: unknown): RawLoc | null {
- if (!isObject(desc)) {
- return null
- }
- if (desc.rr_type === 'ArrayBuffer' && typeof desc.base64 === 'string') {
- return { ab: desc, start: 0, length: Buffer.from(desc.base64, 'base64').length }
- }
- // Typed-array wrapper: { rr_type: 'Uint8ClampedArray', args: [ {ArrayBuffer}, byteOffset?, length? ] }.
- if (Array.isArray(desc.args) && isObject(desc.args[0]) && desc.args[0].rr_type === 'ArrayBuffer') {
- const ab = desc.args[0] as Record<string, unknown>
- if (typeof ab.base64 !== 'string') {
- return null
- }
- const full = Buffer.from(ab.base64, 'base64').length
- const start = typeof desc.args[1] === 'number' ? desc.args[1] : 0
- const length = typeof desc.args[2] === 'number' ? desc.args[2] : full - start
- return { ab, start, length }
- }
- return null
-}
-
-/** Pixelate raw ImageData pixels in place (fail-safe blanked now, downsampled-and-restored by the job). */
-function blurImageData(ctx: ScrubContext, imageData: Record<string, unknown>): boolean {
- const args = imageData.args
- if (Array.isArray(args)) {
- const width = args[1]
- const height = args[2]
- const loc =
- typeof width === 'number' && typeof height === 'number' && width > 0 && height > 0
- ? findRawBuffer(args[0])
- : null
- if (loc && loc.length === width * height * 4) {
- const full = Buffer.from(loc.ab.base64 as string, 'base64')
- if (loc.start >= 0 && loc.start + loc.length <= full.length) {
- const rgba = full.subarray(loc.start, loc.start + loc.length).toString('base64')
- const blanked = Buffer.from(full)
- blanked.fill(0, loc.start, loc.start + loc.length)
- loc.ab.base64 = blanked.toString('base64')
- // Key on dims too: pixelateRawRgba's output depends on width/height, and the `raw:`
- // prefix keeps it from colliding with the `data:`-prefixed data-URI blur keys.
- const cacheKey = `raw:${width}x${height}:${rgba}`
- ctx.blurJobs?.push(async () => {
- const out = await memoizedBlur(ctx.blurCache, cacheKey, () => pixelateRawRgba(rgba, width, height))
- if (out === null) {
- return
- }
- const outBuf = Buffer.from(out, 'base64')
- if (outBuf.length !== loc.length) {
- return
- }
- const merged = Buffer.from(blanked)
- outBuf.copy(merged, loc.start)
- loc.ab.base64 = merged.toString('base64')
- })
- return true
- }
- }
- }
- // Unexpected shape — guarantee no raw-pixel leak by blanking every nested ArrayBuffer.
- return blankArrayBuffers(imageData)
-}
-
-/** Zero out every nested `{rr_type:'ArrayBuffer', base64}` (same byte length). Last-resort fail-safe. */
-function blankArrayBuffers(node: unknown): boolean {
- if (Array.isArray(node)) {
- let changed = false
- for (const item of node) {
- changed = blankArrayBuffers(item) || changed
- }
- return changed
- }
- if (!isObject(node)) {
- return false
- }
- if (node.rr_type === 'ArrayBuffer' && typeof node.base64 === 'string') {
- node.base64 = Buffer.alloc(Buffer.from(node.base64, 'base64').length).toString('base64')
- return true
- }
- let changed = false
- for (const key of Object.keys(node)) {
- changed = blankArrayBuffers((node as Record<string, unknown>)[key]) || changed
- }
- return changed
-}
-
-function splitDataUri(uri: string): { mime: string; base64: string } | null {
- const comma = uri.indexOf(',')
- if (!uri.startsWith('data:') || comma === -1) {
- return null
- }
- const mime = uri.slice('data:'.length, comma).split(';')[0] || 'image/png'
- return { mime, base64: uri.slice(comma + 1) }
-}
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/anonymize/config.ts b/nodejs/src/ingestion/pipelines/sessionreplay/anonymize/config.ts
deleted file mode 100644
index 233d99a05b45..000000000000
--- a/nodejs/src/ingestion/pipelines/sessionreplay/anonymize/config.ts
+++ /dev/null
@@ -1,36 +0,0 @@
-import { AllowLists } from './allow-lists'
-
-/** Replacement char for redacted (non-allow-listed) word characters. */
-export const REDACT_CHAR = '*'
-/** Replacement char for numeric tokens. */
-export const NUMBER_CHAR = '#'
-
-/** A deferred image-blur job: an async closure that blurs its image and writes the result back in place. */
-export type BlurJob = () => Promise<void>
-
-/** In-batch blur memo (input → settled blur): one per Kafka message, so an image recurring across its rrweb events blurs once. */
-export type BlurCache = Map<string, Promise<string | null>>
-
-/** Diagnostic accumulator (ms) for the cv gzip de/recompression sub-steps. */
-export interface ScrubTiming {
- decompressMs: number
- recompressMs: number
-}
-
-/** Per-scrub context: the active allow lists plus tunables read by the scrubbers. */
-export interface ScrubContext {
- allow: AllowLists
- firstPartyHosts?: string[]
- /** Optional collector for deferred image-blur jobs (see {@link BlurJob}). */
- blurJobs?: BlurJob[]
- /** Optional per-Kafka-message memo shared across those jobs so identical images blur once (see {@link BlurCache}). */
- blurCache?: BlurCache
- /** Optional diagnostic timing accumulator (see {@link ScrubTiming}). */
- timing?: ScrubTiming
- useRustAnonymizer?: boolean
-}
-
-/** Shared non-null-object type guard used across the scrubbers. */
-export function isObject(v: unknown): v is Record<string, any> {
- return typeof v === 'object' && v !== null
-}
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/anonymize/css.test.ts b/nodejs/src/ingestion/pipelines/sessionreplay/anonymize/css.test.ts
deleted file mode 100644
index 323265378a80..000000000000
--- a/nodejs/src/ingestion/pipelines/sessionreplay/anonymize/css.test.ts
+++ /dev/null
@@ -1,45 +0,0 @@
-import { runBlurJobs } from './blur'
-import { scrubCssImages } from './css'
-import { defaultAllowLists } from './default-dict'
-
-// A small patterned PNG.
-const ONE_PX =
- 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAIAAACQkWg2AAAACXBIWXMAAAPoAAAD6AG1e1JrAAAAJUlEQVQokWN4plEBRyInbOAIlzjDINRAjCJk8cGoYRAG60iMBwA8H08Qor0ygQAAAABJRU5ErkJggg=='
-
-function ctx(): { allow: ReturnType<typeof defaultAllowLists>; blurJobs: any[] } {
- return { allow: defaultAllowLists(), blurJobs: [] }
-}
-
-describe('anonymize/css', () => {
- it('blurs url(data:image) backgrounds, leaving sprite/remote/non-data url() untouched', () => {
- const c = ctx()
- const node: Record<string, unknown> = {
- textContent: `.a{background:url(${ONE_PX})} .b{background:url(/assets/sprite.svg#icon)} .c{mask:url("https://cdn.example.com/m.png")}`,
- }
- expect(scrubCssImages(c, node, 'textContent')).toBe(true)
- const css = node.textContent as string
- expect(css).not.toContain(ONE_PX) // raw image gone synchronously
- expect(css).toContain('/assets/sprite.svg#icon') // sprite fragment untouched
- expect(css).toContain('https://cdn.example.com/m.png') // remote url untouched
- expect(c.blurJobs).toHaveLength(1)
- })
-
- it('leaves CSS with no inline data-image unchanged', () => {
- const c = ctx()
- const node = { textContent: '.a{background:url(/img/x.png)}' }
- expect(scrubCssImages(c, node, 'textContent')).toBe(false)
- expect(node.textContent).toBe('.a{background:url(/img/x.png)}')
- expect(c.blurJobs).toHaveLength(0)
- })
-
- it('resolves the placeholder to a blurred png after the deferred job runs', async () => {
- const c = ctx()
- const node: Record<string, unknown> = { textContent: `.a{background:url(${ONE_PX})}` }
- scrubCssImages(c, node, 'textContent')
- await runBlurJobs(c.blurJobs)
- const css = node.textContent as string
- expect(css).toMatch(/url\(data:image\/png;base64,[A-Za-z0-9+/=]+\)/)
- expect(css).not.toContain('#a0') // unique placeholder fragment resolved
- expect(css).not.toContain(ONE_PX) // not the original
- })
-})
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/anonymize/css.ts b/nodejs/src/ingestion/pipelines/sessionreplay/anonymize/css.ts
deleted file mode 100644
index 66ba68eba90b..000000000000
--- a/nodejs/src/ingestion/pipelines/sessionreplay/anonymize/css.ts
+++ /dev/null
@@ -1,79 +0,0 @@
-/** Blur inline `url(data:image/...;base64,...)` backgrounds in CSS */
-import { BLANK_IMAGE_DATA_URI, blurImageDataUri, memoizedBlur } from './blur'
-import { ScrubContext, isObject } from './config'
-
-// rrweb inlines a same-origin/CORS-readable `<link rel="stylesheet">` into this attribute
-// at snapshot time, so it holds full stylesheet text and needs the same CSS treatment as `style`.
-export const INLINED_STYLESHEET_ATTR = '_cssText'
-
-const URL_DATA_IMAGE_RE = /url\(\s*(['"]?)(data:image\/[a-z0-9.+-]+;base64,[A-Za-z0-9+/=]+)\1\s*\)/gi
-
-/**
- * Replace each inline data-image background in `container[key]` with a blank placeholder synchronously
- * (fail-safe), and queue a deferred blur that splices the blurred image back in. Returns whether it acted.
- */
-export function scrubCssImages(ctx: ScrubContext, container: Record<string, unknown>, key: string): boolean {
- const css = container[key]
- if (typeof css !== 'string') {
- return false
- }
- let changed = false
- let n = 0
- const value = css.replace(URL_DATA_IMAGE_RE, (_match, quote: string, original: string) => {
- changed = true
- // A unique, valid stand-in (blank image + ignored fragment) so each deferred blur can splice
- // its own image back independently; on blur failure it just stays the blank.
- const placeholder = `${BLANK_IMAGE_DATA_URI}#a${n++}`
- ctx.blurJobs?.push(async () => {
- const blurred = await memoizedBlur(ctx.blurCache, original, () => blurImageDataUri(original))
- const cur = container[key]
- if (typeof cur === 'string') {
- container[key] = cur.replace(placeholder, () => blurred ?? BLANK_IMAGE_DATA_URI)
- }
- })
- return `url(${quote}${placeholder}${quote})`
- })
- if (changed) {
- container[key] = value
- }
- return changed
-}
-
-/** rrweb StyleSheetRule (source 8): CSS lives in `adds[].rule` and whole-sheet `replace`/`replaceSync`. */
-export function scrubStyleSheetRule(ctx: ScrubContext, data: Record<string, unknown>): boolean {
- let changed = scrubCssImages(ctx, data, 'replace')
- changed = scrubCssImages(ctx, data, 'replaceSync') || changed
- return scrubRuleList(ctx, data.adds) || changed
-}
-
-/** rrweb StyleDeclaration (source 13): CSS value lives in `set.value`. */
-export function scrubStyleDeclaration(ctx: ScrubContext, data: Record<string, unknown>): boolean {
- return isObject(data.set) ? scrubCssImages(ctx, data.set, 'value') : false
-}
-
-/** rrweb AdoptedStyleSheet (source 15): CSS lives in `styles[].rules[].rule`. */
-export function scrubAdoptedStyleSheet(ctx: ScrubContext, data: Record<string, unknown>): boolean {
- if (!Array.isArray(data.styles)) {
- return false
- }
- let changed = false
- for (const style of data.styles) {
- if (isObject(style)) {
- changed = scrubRuleList(ctx, style.rules) || changed
- }
- }
- return changed
-}
-
-function scrubRuleList(ctx: ScrubContext, rules: unknown): boolean {
- if (!Array.isArray(rules)) {
- return false
- }
- let changed = false
- for (const rule of rules) {
- if (isObject(rule)) {
- changed = scrubCssImages(ctx, rule, 'rule') || changed
- }
- }
- return changed
-}
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/anonymize/cv.test.ts b/nodejs/src/ingestion/pipelines/sessionreplay/anonymize/cv.test.ts
deleted file mode 100644
index a1f73e75c546..000000000000
--- a/nodejs/src/ingestion/pipelines/sessionreplay/anonymize/cv.test.ts
+++ /dev/null
@@ -1,142 +0,0 @@
-import { gunzipSync, gzipSync } from 'zlib'
-
-import { parseJSON } from '~/common/utils/json-parse'
-
-import { anonymizeEvent } from './anonymize-event'
-import { defaultAllowLists } from './default-dict'
-
-const compress = (v: unknown): string => gzipSync(Buffer.from(JSON.stringify(v))).toString('latin1')
-const decompress = (s: string): any => parseJSON(gunzipSync(Buffer.from(s, 'latin1')).toString('utf8'))
-
-describe('anonymize/cv', () => {
- const ctx = { allow: defaultAllowLists() }
-
- it('round-trips a cv-compressed FullSnapshot and scrubs the DOM text', () => {
- const payload = {
- node: {
- type: 0,
- id: 1,
- childNodes: [
- {
- type: 2,
- id: 2,
- tagName: 'div',
- attributes: {},
- childNodes: [{ type: 3, id: 3, textContent: 'Hello SecretName' }],
- },
- ],
- },
- initialOffset: { top: 0, left: 0 },
- }
- const event: any = { type: 2, timestamp: 1, cv: 'v2', data: compress(payload) }
-
- expect(anonymizeEvent(ctx, event)).toBe(true)
- const out = decompress(event.data)
- expect(out.node.childNodes[0].childNodes[0].textContent).toBe('Hello **********')
- })
-
- it('round-trips a cv-compressed Mutation and scrubs the text sub-field', () => {
- const event: any = {
- type: 3,
- timestamp: 1,
- cv: 'v2',
- data: {
- source: 0,
- texts: compress([{ id: 7, value: 'Hello SecretName' }]),
- attributes: compress([]),
- removes: compress([]),
- adds: compress([]),
- },
- }
-
- expect(anonymizeEvent(ctx, event)).toBe(true)
- const outTexts = decompress(event.data.texts)
- expect(outTexts[0].value).toBe('Hello **********')
- })
-
- it('round-trips a cv-compressed Mutation and media-scrubs an rr_src attribute sub-field', () => {
- const leakUrl =
- 'https://widget.example-vendor.co/v2/app/?widgetToken=eyJ0eXAiOiJKV1QifQ.eyJzdWIiOiJ1c2VyX2Zha2UxMjMifQ.fakesignature&refreshToken=FakeRefreshTok3nValue000&user=%7B%22email%22%3A%22john.fakename%40example.com%22%7D'
- const event: any = {
- type: 3,
- timestamp: 1,
- cv: 'v2',
- data: { source: 0, attributes: compress([{ id: 7, attributes: { rr_src: leakUrl } }]) },
- }
- expect(anonymizeEvent(ctx, event)).toBe(true)
- const outAttrs = decompress(event.data.attributes)[0].attributes
- expect(outAttrs.rr_src).toMatch(/^data:image\/svg\+xml/)
- for (const secret of ['fakesignature', 'FakeRefreshTok3nValue000', 'john.fakename']) {
- expect(JSON.stringify(outAttrs)).not.toContain(secret)
- }
- })
-
- it('scrubs a cv Mutation whose sub-fields are already decompressed arrays', () => {
- // Some producers/exporters emit cv events with plain-array sub-fields.
- // These must still be scrubbed (in place), not skipped as "absent".
- const event: any = {
- type: 3,
- timestamp: 1,
- cv: '2024-10',
- data: {
- source: 0,
- texts: [{ id: 7, value: 'Hello SecretName' }],
- attributes: [],
- removes: [],
- adds: [],
- },
- }
- expect(anonymizeEvent(ctx, event)).toBe(true)
- // Stays an array (not re-compressed to a string) and is scrubbed in place.
- expect(Array.isArray(event.data.texts)).toBe(true)
- expect(event.data.texts[0].value).toBe('Hello **********')
- })
-
- it('scrubs a cv FullSnapshot whose data is already a decompressed object', () => {
- const event: any = {
- type: 2,
- timestamp: 1,
- cv: '2024-10',
- data: {
- node: {
- type: 0,
- id: 1,
- childNodes: [{ type: 3, id: 2, textContent: 'Hello SecretName' }],
- },
- initialOffset: { top: 0, left: 0 },
- },
- }
- expect(anonymizeEvent(ctx, event)).toBe(true)
- expect(event.data.node.childNodes[0].textContent).toBe('Hello **********')
- })
-
- it('throws on a cv FullSnapshot whose data string is not valid latin-1', () => {
- // A codepoint > 0xFF cannot be a latin-1 gzip byte; decoding must throw
- // so the caller fails closed rather than writing the raw blob.
- const event: any = { type: 2, timestamp: 1, cv: '2024-10', data: 'not-Ā-gzip' }
- expect(() => anonymizeEvent(ctx, event)).toThrow()
- })
-
- it('does not gunzip an absent/empty sub-field', () => {
- // texts present, attributes/removes/adds absent — must still scrub texts.
- const event: any = {
- type: 3,
- timestamp: 1,
- cv: 'v2',
- data: { source: 0, texts: compress([{ id: 1, value: 'Hello SecretName' }]) },
- }
- expect(anonymizeEvent(ctx, event)).toBe(true)
- expect(decompress(event.data.texts)[0].value).toBe('Hello **********')
- })
-
- it('fails closed when a compressed sub-field does not decode to an array', () => {
- // A decodable-but-non-array sub-field is malformed; must throw (→ message dropped) rather than zero it.
- const event: any = {
- type: 3,
- timestamp: 1,
- cv: 'v2',
- data: { source: 0, texts: compress({ not: 'an array' }) },
- }
- expect(() => anonymizeEvent(ctx, event)).toThrow()
- })
-})
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/anonymize/cv.ts b/nodejs/src/ingestion/pipelines/sessionreplay/anonymize/cv.ts
deleted file mode 100644
index 39f884a58211..000000000000
--- a/nodejs/src/ingestion/pipelines/sessionreplay/anonymize/cv.ts
+++ /dev/null
@@ -1,112 +0,0 @@
-/** Decode/scrub/re-encode per-event `cv` compression (gzip stored as latin-1 codepoints). */
-import { gunzipSync, gzipSync } from 'zlib'
-
-import { parseJSON } from '~/common/utils/json-parse'
-
-import { ScrubContext, ScrubTiming, isObject } from './config'
-import { scrubFullSnapshot, scrubMutation } from './dom'
-
-function latin1ToBytes(s: string): Buffer {
- const buf = Buffer.allocUnsafe(s.length)
- for (let i = 0; i < s.length; i++) {
- const cp = s.charCodeAt(i)
- if (cp > 0xff) {
- throw new Error(`codepoint U+${cp.toString(16)} > 0xFF in latin-1 gzip stream`)
- }
- buf[i] = cp
- }
- return buf
-}
-
-function decompressString(s: string, timing?: ScrubTiming): unknown {
- const start = performance.now()
- const json = gunzipSync(latin1ToBytes(s)).toString('utf8')
- const value = parseJSON(json)
- if (timing) {
- timing.decompressMs += performance.now() - start
- }
- return value
-}
-
-function compressToString(value: unknown, timing?: ScrubTiming): string {
- const start = performance.now()
- // latin1 is the inverse of latin1ToBytes; JSON.stringify escapes it on serialization.
- const out = gzipSync(Buffer.from(JSON.stringify(value), 'utf8')).toString('latin1')
- if (timing) {
- timing.recompressMs += performance.now() - start
- }
- return out
-}
-
-/** Scrub a `cv`-compressed FullSnapshot event in place. Returns whether it changed. */
-export function scrubCompressedFullSnapshot(ctx: ScrubContext, event: Record<string, unknown>): boolean {
- const data = event.data
- if (typeof data !== 'string') {
- // Not actually whole-blob compressed — scrub as a plain object.
- return scrubFullSnapshot(ctx, data)
- }
- const payload = decompressString(data, ctx.timing)
- if (!scrubFullSnapshot(ctx, payload)) {
- return false
- }
- event.data = compressToString(payload, ctx.timing)
- return true
-}
-
-/** Scrub a `cv`-compressed Mutation event in place. Returns whether it changed. */
-export function scrubCompressedMutation(ctx: ScrubContext, event: Record<string, unknown>): boolean {
- const data = event.data
- if (!isObject(data)) {
- return false
- }
-
- // Sub-fields are gzipped strings on the wire but may arrive as plain arrays; handle both.
- const texts = readSubfield(data.texts, ctx.timing)
- const attributes = readSubfield(data.attributes, ctx.timing)
- const adds = readSubfield(data.adds, ctx.timing)
-
- const synthetic: Record<string, unknown> = {
- source: data.source,
- texts: texts.array,
- attributes: attributes.array,
- adds: adds.array,
- // `removes` is ids-only and untouched — left as-is.
- }
-
- if (!scrubMutation(ctx, synthetic)) {
- return false
- }
-
- // Array sub-fields were mutated in place; only re-encode the ones that arrived gzipped.
- if (texts.wasCompressed) {
- data.texts = compressToString(synthetic.texts, ctx.timing)
- }
- if (attributes.wasCompressed) {
- data.attributes = compressToString(synthetic.attributes, ctx.timing)
- }
- if (adds.wasCompressed) {
- data.adds = compressToString(synthetic.adds, ctx.timing)
- }
- return true
-}
-
-function readSubfield(field: unknown, timing?: ScrubTiming): { array: unknown[]; wasCompressed: boolean } {
- if (field === undefined || field === null) {
- return { array: [], wasCompressed: false }
- }
- if (typeof field === 'string') {
- if (field.length === 0) {
- return { array: [], wasCompressed: false }
- }
- const payload = decompressString(field, timing)
- if (!Array.isArray(payload)) {
- // Fail closed: a decodable-but-non-array sub-field is malformed; dropping beats shipping a zeroed block.
- throw new Error('cv mutation sub-field did not decode to an array')
- }
- return { array: payload, wasCompressed: true }
- }
- if (Array.isArray(field)) {
- return { array: field, wasCompressed: false }
- }
- throw new Error('cv mutation sub-field is neither a gzipped string nor an array')
-}
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/anonymize/dom.test.ts b/nodejs/src/ingestion/pipelines/sessionreplay/anonymize/dom.test.ts
deleted file mode 100644
index 9b336668a147..000000000000
--- a/nodejs/src/ingestion/pipelines/sessionreplay/anonymize/dom.test.ts
+++ /dev/null
@@ -1,270 +0,0 @@
-import { defaultAllowLists } from './default-dict'
-import { scrubFullSnapshot, scrubMutation } from './dom'
-
-describe('anonymize/dom', () => {
- const ctx = { allow: defaultAllowLists() }
-
- it('scrubs text nodes but leaves script source untouched', () => {
- const event = {
- type: 2,
- timestamp: 1,
- data: {
- node: {
- type: 0,
- id: 1,
- childNodes: [
- {
- type: 2,
- id: 2,
- tagName: 'div',
- attributes: {},
- childNodes: [{ type: 3, id: 3, textContent: 'Hello SecretName' }],
- },
- {
- type: 2,
- id: 4,
- tagName: 'script',
- attributes: {},
- childNodes: [{ type: 3, id: 5, textContent: 'var x = 1;' }],
- },
- ],
- },
- initialOffset: { top: 0, left: 0 },
- },
- }
- const changed = scrubFullSnapshot(ctx, event.data)
- expect(changed).toBe(true)
-
- const root = event.data.node
- const div = root.childNodes[0]
- const txt = div.childNodes[0]
- // "Hello" is allow-listed; "SecretName" is 10 chars → ten *s.
- expect(txt.textContent).toBe('Hello **********')
-
- const script = root.childNodes[1]
- const scriptTxt = script.childNodes[0]
- expect(scriptTxt.textContent).toBe('var x = 1;')
- })
-
- it('URL-scrubs url attributes and leaves class untouched', () => {
- const event = {
- type: 2,
- timestamp: 1,
- data: {
- node: {
- type: 0,
- id: 1,
- childNodes: [
- {
- type: 2,
- id: 2,
- tagName: 'a',
- attributes: { href: 'https://example.com/user/abc/edit', class: 'link primary' },
- childNodes: [],
- },
- ],
- },
- initialOffset: { top: 0, left: 0 },
- },
- }
- scrubFullSnapshot(ctx, event.data)
- const a = event.data.node.childNodes[0]
- expect(a.attributes.href).toBe('https://example.com/user/[redacted]/edit')
- expect(a.attributes.class).toBe('link primary')
- })
-
- it('preserves non-string attribute values and scrubs only string url/text attrs', () => {
- const event = {
- type: 2,
- timestamp: 1,
- data: {
- node: {
- type: 0,
- id: 1,
- childNodes: [
- {
- type: 2,
- id: 2,
- tagName: 'body',
- attributes: {
- href: 'https://example.com/user/abc/edit',
- title: 'Smithson lives nearby',
- class: 'x',
- 'data-n': 3,
- disabled: true,
- removed: null,
- },
- childNodes: [],
- },
- ],
- },
- initialOffset: { top: 0, left: 0 },
- },
- }
- scrubFullSnapshot(ctx, event.data)
- const attrs = event.data.node.childNodes[0].attributes
- // String url/user-text attrs scrubbed:
- expect(attrs.href).toBe('https://example.com/user/[redacted]/edit')
- expect(attrs.title).toBe('******** ***** ******')
- // Non-url/text string left as-is; non-string values untouched:
- expect(attrs.class).toBe('x')
- expect(attrs['data-n']).toBe(3)
- expect(attrs.disabled).toBe(true)
- expect(attrs.removed).toBeNull()
- })
-
- it('scrubs an inline (uncompressed) mutation', () => {
- const data: any = {
- source: 0,
- texts: [{ id: 5, value: 'Hello SecretName' }],
- attributes: [{ id: 4, attributes: { title: 'Smithson lives nearby', class: 'y' } }],
- removes: [{ parentId: 3, id: 7 }],
- adds: [{ parentId: 4, nextId: null, node: { type: 3, id: 8, textContent: 'Hello Smithson' } }],
- }
- const changed = scrubMutation(ctx, data)
- expect(changed).toBe(true)
- expect(data.texts[0].value).toBe('Hello **********')
- expect(data.attributes[0].attributes.title).toBe('******** ***** ******')
- expect(data.attributes[0].attributes.class).toBe('y')
- expect(data.adds[0].node.textContent).toBe('Hello ********')
- // removes is ids-only and untouched.
- expect(data.removes[0].id).toBe(7)
- })
-
- it('scrubs Comment and CDATA text content', () => {
- const event = {
- type: 2,
- timestamp: 1,
- data: {
- node: {
- type: 0,
- id: 1,
- childNodes: [
- { type: 5, id: 2, textContent: 'Hello SecretName' },
- { type: 4, id: 3, textContent: 'Hello SecretName' },
- // DocumentType (type 1) carries no text and is left alone.
- { type: 1, id: 4, name: 'html' },
- ],
- },
- initialOffset: { top: 0, left: 0 },
- },
- }
- const changed = scrubFullSnapshot(ctx, event.data)
- expect(changed).toBe(true)
- expect(event.data.node.childNodes[0].textContent).toBe('Hello **********')
- expect(event.data.node.childNodes[1].textContent).toBe('Hello **********')
- })
-
- it('replaces a remote image src with the placeholder and preserves the URL', () => {
- const event = {
- type: 2,
- timestamp: 1,
- data: {
- node: {
- type: 0,
- id: 1,
- childNodes: [
- {
- type: 2,
- id: 2,
- tagName: 'img',
- attributes: { src: 'https://example.com/u/abc.png', alt: 'profile photo of user' },
- childNodes: [],
- },
- ],
- },
- initialOffset: { top: 0, left: 0 },
- },
- }
- scrubFullSnapshot(ctx, event.data)
- const img = event.data.node.childNodes[0]
- expect(typeof img.attributes.src).toBe('string')
- expect((img.attributes.src as string).startsWith('data:image/svg+xml')).toBe(true)
- expect('data-anon-original-src' in img.attributes).toBe(true)
- })
-
- it('keeps state-token data-* (so styling survives) but redacts PII-looking values and emails', () => {
- const attrs: Record<string, unknown> = {
- 'data-state': 'active', // enum/state token → kept (CSS selectors depend on it)
- 'data-scheme': 'primary', // ditto
- 'data-tooltip': 'Logged in as Smithson', // free text (whitespace) → redacted
- 'data-contact': '[email protected]', // email → redacted regardless
- 'data-anon-original-src': 'https://example.com/[redacted]/[redacted]', // our stash → left intact
- }
- scrubMutation(ctx, { source: 0, attributes: [{ id: 2, attributes: attrs }] })
- expect(attrs['data-state']).toBe('active')
- expect(attrs['data-scheme']).toBe('primary')
- expect(attrs['data-tooltip']).not.toContain('Smithson')
- expect(attrs['data-contact']).not.toContain('jane')
- expect(attrs['data-contact']).not.toContain('example.com')
- expect(attrs['data-anon-original-src']).toBe('https://example.com/[redacted]/[redacted]')
- })
-
- it('leaves CSS untouched: the inline style attribute and <style> text pass through verbatim', () => {
- // CSS is author stylesheet content, not user PII; scrubbing url() targets broke far
- // more (SVG sprite fragments, CDN asset paths) than it ever saved, so we no longer touch it.
- const attrs: Record<string, unknown> = { style: 'background: url(/users/SecretUser/bg.png)' }
- expect(scrubMutation(ctx, { source: 0, attributes: [{ id: 2, attributes: attrs }] })).toBe(false)
- expect(attrs.style).toBe('background: url(/users/SecretUser/bg.png)')
-
- const cssText = '.a { background: url(/users/SecretUser/x.png) }'
- const event = {
- type: 2,
- timestamp: 1,
- data: {
- node: {
- type: 0,
- id: 1,
- childNodes: [
- {
- type: 2,
- id: 2,
- tagName: 'style',
- attributes: {},
- childNodes: [{ type: 3, id: 3, textContent: cssText }],
- },
- ],
- },
- initialOffset: { top: 0, left: 0 },
- },
- }
- expect(scrubFullSnapshot(ctx, event.data)).toBe(false)
- expect(event.data.node.childNodes[0].childNodes[0].textContent).toBe(cssText)
- })
-
- it('neutralizes data-image backgrounds in an inlined stylesheet (_cssText)', () => {
- const onePxPng =
- 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAIAAACQkWg2AAAACXBIWXMAAAPoAAAD6AG1e1JrAAAAJUlEQVQokWN4plEBRyInbOAIlzjDINRAjCJk8cGoYRAG60iMBwA8H08Qor0ygQAAAABJRU5ErkJggg=='
- const attrs: Record<string, unknown> = {
- rel: 'stylesheet',
- _cssText: `.a{background:url(${onePxPng})}`,
- }
- expect(scrubMutation(ctx, { source: 0, attributes: [{ id: 2, attributes: attrs }] })).toBe(true)
- expect(attrs._cssText).not.toContain(onePxPng)
- })
-
- it('blurs canvas pixels inlined as rr_dataURL in a FullSnapshot', () => {
- const blurCtx = { allow: defaultAllowLists(), blurJobs: [] as any[] }
- const onePxPng =
- 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAIAAACQkWg2AAAACXBIWXMAAAPoAAAD6AG1e1JrAAAAJUlEQVQokWN4plEBRyInbOAIlzjDINRAjCJk8cGoYRAG60iMBwA8H08Qor0ygQAAAABJRU5ErkJggg=='
- const canvasAttrs: Record<string, unknown> = { rr_dataURL: onePxPng, width: '300', height: '150' }
- const event = {
- type: 2,
- timestamp: 1,
- data: {
- node: {
- type: 0,
- id: 1,
- childNodes: [{ type: 2, id: 2, tagName: 'canvas', attributes: canvasAttrs, childNodes: [] }],
- },
- initialOffset: { top: 0, left: 0 },
- },
- }
- expect(scrubFullSnapshot(blurCtx, event.data)).toBe(true)
- // Raw pixels gone immediately (fail-safe), blur deferred; dimensions untouched.
- expect(canvasAttrs.rr_dataURL).not.toBe(onePxPng)
- expect(canvasAttrs.rr_dataURL).toMatch(/^data:image\/png;base64,/)
- expect(canvasAttrs.width).toBe('300')
- expect(blurCtx.blurJobs).toHaveLength(1)
- })
-})
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/anonymize/dom.ts b/nodejs/src/ingestion/pipelines/sessionreplay/anonymize/dom.ts
deleted file mode 100644
index 77d40fca95ca..000000000000
--- a/nodejs/src/ingestion/pipelines/sessionreplay/anonymize/dom.ts
+++ /dev/null
@@ -1,242 +0,0 @@
-/** Walks parsed rrweb serialized nodes, scrubbing text content and attributes in place. */
-import {
- INLINE_IMAGE_ATTR,
- applyBlur,
- blurInlineImageAttr,
- hasMediaSrcAttr,
- isMediaSrcAttr,
- isMediaTag,
-} from './assets'
-import { ScrubContext, isObject } from './config'
-import { INLINED_STYLESHEET_ATTR, scrubCssImages } from './css'
-import { redactEmails, scrubText } from './text'
-import { scrubUrl } from './url'
-
-export enum NodeType {
- Document = 0,
- DocumentType = 1,
- Element = 2,
- Text = 3,
- Cdata = 4,
- Comment = 5,
-}
-
-type ParentKind = 'script' | 'style' | 'other'
-type TagKind = 'script' | 'style' | 'media' | 'other'
-
-type AnyNode = Record<string, unknown>
-
-export function scrubFullSnapshot(ctx: ScrubContext, data: unknown): boolean {
- if (!isObject(data) || !isObject(data.node)) {
- return false
- }
- return walkNode(ctx, data.node, 'other')
-}
-
-export function scrubMutation(ctx: ScrubContext, data: unknown): boolean {
- if (!isObject(data)) {
- return false
- }
- let changed = false
-
- if (Array.isArray(data.texts)) {
- for (const t of data.texts) {
- if (isObject(t) && typeof t.value === 'string') {
- const result = scrubText(ctx, t.value)
- if (result.changed) {
- t.value = result.value
- changed = true
- }
- }
- }
- }
-
- if (Array.isArray(data.attributes)) {
- for (const a of data.attributes) {
- if (isObject(a) && isObject(a.attributes)) {
- const kind: TagKind = hasMediaSrcAttr(a.attributes) ? 'media' : 'other'
- changed = scrubAttrs(ctx, a.attributes, kind) || changed
- }
- }
- }
-
- if (Array.isArray(data.adds)) {
- for (const added of data.adds) {
- if (isObject(added) && isObject(added.node)) {
- changed = walkNode(ctx, added.node, 'other') || changed
- }
- }
- }
-
- return changed
-}
-
-function walkNode(ctx: ScrubContext, node: AnyNode, parent: ParentKind): boolean {
- let changed = false
-
- switch (node.type) {
- case NodeType.Element: {
- const kind = classifyTag(typeof node.tagName === 'string' ? node.tagName : '')
- if (isObject(node.attributes)) {
- changed = scrubAttrs(ctx, node.attributes, kind) || changed
- }
- const childParent: ParentKind = kind === 'media' ? 'other' : kind
- if (Array.isArray(node.childNodes)) {
- for (const child of node.childNodes) {
- if (isObject(child)) {
- changed = walkNode(ctx, child, childParent) || changed
- }
- }
- }
- break
- }
- case NodeType.Document: {
- if (Array.isArray(node.childNodes)) {
- for (const child of node.childNodes) {
- if (isObject(child)) {
- changed = walkNode(ctx, child, 'other') || changed
- }
- }
- }
- break
- }
- case NodeType.Text: {
- // Script is code — never touch it.
- if (parent === 'script') {
- return false
- }
- if (parent === 'style' || node.isStyle === true) {
- return scrubCssImages(ctx, node, 'textContent')
- }
- changed = scrubTextContent(ctx, node) || changed
- break
- }
- case NodeType.Comment:
- case NodeType.Cdata: {
- changed = scrubTextContent(ctx, node) || changed
- break
- }
- // DocumentType: nothing.
- }
-
- return changed
-}
-
-function scrubTextContent(ctx: ScrubContext, node: AnyNode): boolean {
- if (typeof node.textContent !== 'string') {
- return false
- }
- const result = scrubText(ctx, node.textContent)
- if (result.changed) {
- node.textContent = result.value
- return true
- }
- return false
-}
-
-function classifyTag(tag: string): TagKind {
- const lower = tag.toLowerCase()
- if (lower === 'script') {
- return 'script'
- }
- if (lower === 'style') {
- return 'style'
- }
- if (isMediaTag(tag)) {
- return 'media'
- }
- return 'other'
-}
-
-function scrubAttrs(ctx: ScrubContext, attrs: Record<string, unknown>, kind: TagKind): boolean {
- let changed = false
-
- for (const name of Object.keys(attrs)) {
- if (kind === 'media' && isMediaSrcAttr(name)) {
- continue
- }
- // Inlined rendered pixels (canvas/img `rr_dataURL`): blur the image, on any tag.
- if (name === INLINE_IMAGE_ATTR) {
- changed = blurInlineImageAttr(ctx, attrs, name) || changed
- continue
- }
- const value = attrs[name]
- // Only string attribute values are scrubbed (objects/numbers/bools are skipped).
- if (typeof value !== 'string') {
- continue
- }
- let result
- if (isUrlAttr(name)) {
- result = scrubUrl(ctx, value)
- } else if (name === 'style' || name === INLINED_STYLESHEET_ATTR) {
- changed = scrubCssImages(ctx, attrs, name) || changed
- continue
- } else if (isUserTextAttr(name)) {
- result = scrubText(ctx, value)
- } else if (isDataAttr(name)) {
- result = dataAttrLooksSensitive(value) ? scrubText(ctx, value) : redactEmails(value)
- } else {
- continue
- }
- if (result.changed) {
- attrs[name] = result.value
- changed = true
- }
- }
-
- if (kind === 'media') {
- applyBlur(ctx, attrs)
- changed = true
- }
-
- return changed
-}
-
-function isUserTextAttr(name: string): boolean {
- switch (name) {
- case 'alt':
- case 'title':
- case 'placeholder':
- case 'aria-label':
- case 'aria-description':
- case 'aria-roledescription':
- case 'aria-valuetext':
- case 'aria-placeholder':
- case 'value':
- case 'label':
- case 'summary':
- return true
- default:
- return false
- }
-}
-
-function isDataAttr(name: string): boolean {
- return name.startsWith('data-') && !name.startsWith('data-anon-original-')
-}
-
-function dataAttrLooksSensitive(value: string): boolean {
- // Free text (whitespace) or an email-ish token — not a single enum/state/id token.
- return value.includes('@') || /\s/.test(value)
-}
-
-function isUrlAttr(name: string): boolean {
- switch (name) {
- case 'href':
- case 'src':
- case 'rr_src':
- case 'srcset':
- case 'action':
- case 'formaction':
- case 'cite':
- case 'data':
- case 'poster':
- case 'background':
- case 'xlink:href':
- case 'manifest':
- case 'longdesc':
- return true
- default:
- return false
- }
-}
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/anonymize/index.ts b/nodejs/src/ingestion/pipelines/sessionreplay/anonymize/index.ts
deleted file mode 100644
index f3e5a782166b..000000000000
--- a/nodejs/src/ingestion/pipelines/sessionreplay/anonymize/index.ts
+++ /dev/null
@@ -1,5 +0,0 @@
-export { AllowLists } from './allow-lists'
-export { anonymizeEvent, anonymizeParsedMessage } from './anonymize-event'
-export { loadAllowLists } from './allow-list-loader'
-export { type ScrubContext } from './config'
-export { defaultAllowLists } from './default-dict'
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/anonymize/shared-fixtures.test.ts b/nodejs/src/ingestion/pipelines/sessionreplay/anonymize/shared-fixtures.test.ts
deleted file mode 100644
index 9dbc71fabcd5..000000000000
--- a/nodejs/src/ingestion/pipelines/sessionreplay/anonymize/shared-fixtures.test.ts
+++ /dev/null
@@ -1,278 +0,0 @@
-import fs from 'fs'
-import path from 'path'
-import { gzipSync, zstdDecompressSync } from 'zlib'
-
-import { parseJSON } from '~/common/utils/json-parse'
-import { logger } from '~/common/utils/logger'
-
-import { AllowLists } from './allow-lists'
-import { anonymizeEvent } from './anonymize-event'
-import { ScrubContext } from './config'
-import { scrubText } from './text'
-import { URL_SCHEME_ALLOWLIST, scrubUrl } from './url'
-
-// shared fixtures to guarantee identical behaviour between implementations
-const FIXTURE_DIR = path.resolve(__dirname, '../../../../../../rust/replay-anonymizer-node/tests/fixtures')
-
-interface AllowSpec {
- text: string[]
- url: string[]
-}
-interface TextCase {
- name: string
- allow: AllowSpec
- input: string
- expected: string
-}
-interface UrlCase extends TextCase {
- collapseHost?: boolean
- firstPartyHosts?: string[]
-}
-interface EventCase {
- name: string
- allow: AllowSpec
- event: Record<string, unknown>
- expected: Record<string, unknown>
-}
-interface MessageCase {
- name: string
- allow: AllowSpec
- message: Record<string, unknown[]>
- expected: Record<string, unknown>
-}
-
-function load<T>(name: string): T[] {
- return parseJSON(fs.readFileSync(path.join(FIXTURE_DIR, name), 'utf8'))
-}
-function ctxOf(allow: AllowSpec): ScrubContext {
- return { allow: new AllowLists(allow.text, allow.url) }
-}
-
-function anonymizeMessageTs(allow: AllowSpec, message: Record<string, unknown[]>): Record<string, unknown> {
- const ctx = ctxOf(allow)
- const clone = structuredClone(message) as Record<string, unknown[]>
- for (const events of Object.values(clone)) {
- if (Array.isArray(events)) {
- for (const event of events) {
- anonymizeEvent(ctx, event)
- }
- }
- }
- return clone
-}
-
-let rustAddon: typeof import('@posthog/replay-anonymizer') | null = null
-try {
- rustAddon = require('@posthog/replay-anonymizer')
-} catch (e) {
- if (process.env.CI) {
- throw new Error(`replay-anonymizer addon failed to load; native parity cannot run in CI: ${String(e)}`)
- }
- logger.warn('🙈', 'replay_anonymizer_addon_not_built_skipping_native_parity')
-}
-
-describe('anonymize shared fixtures', () => {
- const textCases = load<TextCase>('text.json')
- const urlCases = load<UrlCase>('url.json')
- const eventCases = load<EventCase>('events.json')
- const messageCases = load<MessageCase>('messages.json')
-
- describe('typescript scrubbers match the shared fixtures', () => {
- test.each(textCases.map((c) => [c.name, c] as const))('text: %s', (_name, c) => {
- expect(scrubText(ctxOf(c.allow), c.input).value).toEqual(c.expected)
- })
-
- test.each(urlCases.map((c) => [c.name, c] as const))('url: %s', (_name, c) => {
- const ctx = { ...ctxOf(c.allow), firstPartyHosts: c.firstPartyHosts }
- expect(scrubUrl(ctx, c.input, { collapseHost: c.collapseHost }).value).toEqual(c.expected)
- })
-
- test.each(eventCases.map((c) => [c.name, c] as const))('event: %s', (_name, c) => {
- const event = structuredClone(c.event)
- anonymizeEvent(ctxOf(c.allow), event)
- expect(event).toEqual(c.expected)
- })
-
- test.each(messageCases.map((c) => [c.name, c] as const))('message: %s', (_name, c) => {
- expect(anonymizeMessageTs(c.allow, c.message)).toEqual(c.expected)
- })
-
- // The rust constant is checked against the same fixture, so the two lists cannot drift.
- test('URL_SCHEME_ALLOWLIST matches the shared fixture', () => {
- expect([...URL_SCHEME_ALLOWLIST].sort()).toEqual(load<string>('url-scheme-allowlist.json'))
- })
- })
-
- const describeAddon = rustAddon ? describe : describe.skip
- describeAddon('native rust addon matches the shared fixtures', () => {
- const TS0 = 1_700_000_000_000
-
- // Wrap fixture events in the Kafka payload shape
- function payloadOf(windowId: string, events: unknown[]): Buffer {
- const items = structuredClone(events)
- items.forEach((ev, i) => {
- if (isRecord(ev)) {
- ev.timestamp ??= TS0 + i
- }
- })
- const inner = JSON.stringify({
- event: '$snapshot_items',
- properties: { $snapshot_items: items, $session_id: 's-1', $window_id: windowId },
- })
- return Buffer.from(JSON.stringify({ distinct_id: 'd-1', data: inner }))
- }
-
- function isRecord(v: unknown): v is Record<string, unknown> {
- return typeof v === 'object' && v !== null && !Array.isArray(v)
- }
-
- function expectedLines(windowId: string, expected: unknown[]): unknown[] {
- const events = structuredClone(expected)
- events.forEach((ev, i) => {
- if (isRecord(ev)) {
- ev.timestamp ??= TS0 + i
- }
- })
- return events.filter(isRecord).map((ev) => [windowId, ev])
- }
-
- function parseLines(lines: Buffer): unknown[] {
- return lines
- .toString()
- .split('\n')
- .filter((l) => l.length > 0)
- .map((l) => parseJSON(l))
- }
-
- describe('events', () => {
- test.each(eventCases.map((c) => [c.name, c] as const))('event: %s', async (_name, c) => {
- // --runInBand is required to ensure cases are sequential
- rustAddon!.initAnonymizer(c.allow)
- const result = await rustAddon!.anonymizeKafkaPayload(payloadOf('w', [c.event]))
- expect(result.failed).toBe(false)
- expect(parseLines(result.lines!)).toEqual(expectedLines('w', [c.expected]))
- })
- })
-
- test.each(messageCases.map((c) => [c.name, c] as const))('message: %s', async (_name, c) => {
- rustAddon!.initAnonymizer(c.allow)
- for (const [windowId, events] of Object.entries(c.message)) {
- const expected = expectedLines(windowId, (c.expected as Record<string, unknown[]>)[windowId])
- const result = await rustAddon!.anonymizeKafkaPayload(payloadOf(windowId, events))
- if (expected.length === 0) {
- // A window with only invalid events: the fused step drops the whole message.
- expect(result.failed).toBe(true)
- expect(result.reason).toBe('message_contained_no_valid_rrweb_events')
- continue
- }
- expect(result.failed).toBe(false)
- expect(parseLines(result.lines!)).toEqual(expected)
- }
- })
-
- it('collapses first-party hosts passed per call', async () => {
- const event = {
- type: 2,
- data: {
- node: {
- type: 0,
- childNodes: [
- {
- type: 2,
- tagName: 'a',
- attributes: { href: 'https://app.customer-site.test/settings' },
- childNodes: [],
- },
- ],
- },
- initialOffset: { top: 0, left: 0 },
- },
- }
- rustAddon!.initAnonymizer({ text: [], url: [] })
- const result = await rustAddon!.anonymizeKafkaPayload(payloadOf('w', [event]), undefined, [
- 'customer-site.test',
- ])
- expect(result.failed).toBe(false)
- const line = parseLines(result.lines!)[0] as [
- string,
- { data: { node: { childNodes: { attributes: Record<string, string> }[] } } },
- ]
- expect(line[1].data.node.childNodes[0].attributes.href).toBe('https://example.com/[redacted]')
- })
-
- // fixtures are plain text, convert to gzip bytes for this test
- describe('cv-compressed events through the production entry', () => {
- // latin-1: each compressed byte is a U+00XX codepoint, matching the SDK wire format.
- const gzipLatin1 = (json: string): string => Buffer.from(gzipSync(Buffer.from(json))).toString('latin1')
- const unzstdLatin1 = (s: string): unknown => {
- const raw = Buffer.from(s, 'latin1')
- // Magic-byte dispatch is the loader contract; pin the zstd frame magic on decode.
- expect([...raw.subarray(0, 4)]).toEqual([0x28, 0xb5, 0x2f, 0xfd])
- return parseJSON(zstdDecompressSync(raw).toString())
- }
-
- const fullSnapshot = {
- type: 2,
- cv: '2024-10',
- data: gzipLatin1(
- JSON.stringify({
- node: { type: 0, id: 1, childNodes: [{ type: 3, id: 5, textContent: 'keep secret' }] },
- initialOffset: { top: 0, left: 0 },
- })
- ),
- }
- const mutation = {
- type: 3,
- cv: '2024-10',
- data: { source: 0, texts: gzipLatin1(JSON.stringify([{ id: 5, value: 'keep secret' }])) },
- }
-
- it('scrubs a cv full snapshot and re-emits a decodable zstd payload', async () => {
- rustAddon!.initAnonymizer({ text: ['keep'], url: [] })
- const result = await rustAddon!.anonymizeKafkaPayload(payloadOf('w', [fullSnapshot]))
- expect(result.failed).toBe(false)
- const line = parseLines(result.lines!)[0] as [string, { data: string }]
- const decoded = unzstdLatin1(line[1].data) as { node: { childNodes: { textContent: string }[] } }
- expect(decoded.node.childNodes[0].textContent).toBe('keep ******')
- })
-
- it('media-scrubs an rr_src attribute inside a cv mutation sub-field', async () => {
- const attrMutation = {
- type: 3,
- cv: '2024-10',
- data: {
- source: 0,
- attributes: gzipLatin1(
- JSON.stringify([
- {
- id: 7,
- attributes: {
- rr_src: 'https://widget.example-vendor.co/v2/app/?refreshToken=FakeRefreshTok3nValue000',
- },
- },
- ])
- ),
- },
- }
- rustAddon!.initAnonymizer({ text: [], url: [] })
- const result = await rustAddon!.anonymizeKafkaPayload(payloadOf('w', [attrMutation]))
- expect(result.failed).toBe(false)
- const line = parseLines(result.lines!)[0] as [string, { data: { attributes: string } }]
- const decoded = unzstdLatin1(line[1].data.attributes) as { attributes: Record<string, string> }[]
- expect(decoded[0].attributes.rr_src).toMatch(/^data:image\/svg\+xml/)
- expect(decoded[0].attributes['data-anon-original-rr_src']).toBe(
- 'https://example.com/[redacted]/[redacted]/'
- )
- })
-
- it('scrubs a cv mutation sub-field and re-emits a decodable zstd payload', async () => {
- rustAddon!.initAnonymizer({ text: ['keep'], url: [] })
- const result = await rustAddon!.anonymizeKafkaPayload(payloadOf('w', [mutation]))
- expect(result.failed).toBe(false)
- const line = parseLines(result.lines!)[0] as [string, { data: { texts: string } }]
- const decoded = unzstdLatin1(line[1].data.texts) as { value: string }[]
- expect(decoded[0].value).toBe('keep ******')
- })
- })
- })
-})
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/anonymize/text.test.ts b/nodejs/src/ingestion/pipelines/sessionreplay/anonymize/text.test.ts
deleted file mode 100644
index 5d3290a26695..000000000000
--- a/nodejs/src/ingestion/pipelines/sessionreplay/anonymize/text.test.ts
+++ /dev/null
@@ -1,80 +0,0 @@
-import { defaultAllowLists } from './default-dict'
-import { redactEmails, scrubText } from './text'
-
-describe('anonymize/text', () => {
- const allow = defaultAllowLists()
- const scrub = (input: string): string => scrubText({ allow }, input).value
-
- it('keeps allow-listed words', () => {
- expect(scrub('Click submit to continue')).toBe('Click submit to continue')
- })
-
- it('redacts unknown words per char', () => {
- expect(scrub('Hello Mr Smithson')).toBe('Hello ** ********')
- })
-
- it('turns numbers into hash per char', () => {
- expect(scrub('user 42 home 99')).toBe('user ## home ##')
- })
-
- it('redacts numeric tokens with #', () => {
- expect(scrub('submit 4242 Smithson')).toBe('submit #### ********')
- })
-
- it('preserves punctuation', () => {
- expect(scrub('user, click submit!')).toBe('user, click submit!')
- })
-
- it('preserves contractions', () => {
- expect(scrub("I'll click submit but don't save it. Let's continue.")).toBe(
- "I'll click submit but don't save it. Let's continue."
- )
- })
-
- it('handles the typographic apostrophe', () => {
- expect(scrub('I’ll save it')).toBe('I’ll save it')
- })
-
- it('lets a possessive inherit its base allow-listing', () => {
- expect(scrub("the user's account")).toBe("the user's account")
- })
-
- it('keeps allow-listed words in long (>8 word) text — no full-redact threshold', () => {
- expect(scrub('click submit cancel click submit cancel click submit cancel Smithson')).toBe(
- 'click submit cancel click submit cancel click submit cancel ********'
- )
- })
-
- it('preserves code-point length when redacting astral (surrogate-pair) characters', () => {
- // Two CJK-extension-B letters = 2 code points (4 UTF-16 units). Redaction
- // must produce 2 mark chars, not 4.
- expect(scrub('𠀀𠀀')).toBe('**')
- })
-
- it('redacts whole email addresses via the regex pass (even allow-listed fragments)', () => {
- // `to`/`in` are stop-words the tokenizer would keep, but the email pass nukes the address first.
- expect(scrub('to [email protected]')).toBe('to ' + '*'.repeat('[email protected]'.length))
- expect(scrub('email [email protected]')).not.toContain('[email protected]')
- })
-
- test.each([
- ['[email protected]', '******'],
- ['[email protected]', '****************2'],
- ['a@[email protected]', 'a@*******'],
- ['[email protected] [email protected]', '*********** ************'],
- ['[email protected]', '******************'],
- ['[email protected]...', '****************...'],
- ])('redactEmails boundary semantics: %s', (input, expected) => {
- expect(redactEmails(input).value).toBe(expected)
- })
-
- it('scales linearly on a long unbroken email-charset run (no regex backtracking)', () => {
- // A backtracking email regex is O(n²) here: ~35s at this size vs ~10ms linear.
- const run = 'A1b2C3d4'.repeat((256 * 1024) / 8)
- const start = performance.now()
- scrub(run)
- expect(performance.now() - start).toBeLessThan(5000)
- })
-})
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/anonymize/text.ts b/nodejs/src/ingestion/pipelines/sessionreplay/anonymize/text.ts
deleted file mode 100644
index 25bca53fb9b7..000000000000
--- a/nodejs/src/ingestion/pipelines/sessionreplay/anonymize/text.ts
+++ /dev/null
@@ -1,182 +0,0 @@
-/** Length-preserving text scrub: numeric tokens → `#`, allow-listed words kept, everything else → `*`. */
-import { AllowLists } from './allow-lists'
-import { NUMBER_CHAR, REDACT_CHAR, ScrubContext } from './config'
-
-export interface ScrubResult {
- value: string
- changed: boolean
-}
-
-// A "word" is a maximal run of word chars: Unicode letters/numbers, `_`, `'`, `’`.
-const WORD_RE = /[\p{L}\p{N}_'’]+/gu
-
-// Guaranteed email-PII pass, run over all text. Hand-rolled scan (expand around each `@`,
-// equivalent to /[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}/g) because that regex
-// backtracks quadratically on long unbroken charset runs (base64 bodies: minutes per event).
-export function redactEmails(input: string): ScrubResult {
- let at = input.indexOf('@')
- if (at === -1) {
- return { value: input, changed: false }
- }
- let out = ''
- let last = 0
- let changed = false
- while (at !== -1) {
- let start = at
- while (start > last && isLocalChar(input.charCodeAt(start - 1))) {
- start--
- }
- let scanEnd = at + 1
- while (scanEnd < input.length && isDomainChar(input.charCodeAt(scanEnd))) {
- scanEnd++
- }
- const end = trimDomainToTld(input, at + 1, scanEnd)
- if (start < at && end !== -1) {
- out += input.slice(last, start) + REDACT_CHAR.repeat(codePointLength(input.slice(start, end)))
- last = end
- changed = true
- at = input.indexOf('@', end)
- } else {
- at = input.indexOf('@', at + 1)
- }
- }
- if (!changed) {
- return { value: input, changed: false }
- }
- return { value: out + input.slice(last), changed }
-}
-
-/** Longest `end` in (domainStart, scanEnd] where the domain ends with `.` + ≥2 letters, or -1. */
-function trimDomainToTld(input: string, domainStart: number, scanEnd: number): number {
- let i = scanEnd
- while (i > domainStart) {
- let letters = 0
- while (i > domainStart && isAsciiLetter(input.charCodeAt(i - 1))) {
- i--
- letters++
- }
- if (letters >= 2 && i - 1 > domainStart && input.charCodeAt(i - 1) === 0x2e /* . */) {
- return i + letters
- }
- i-- // skip the non-letter (or short-TLD dot) and keep looking left
- }
- return -1
-}
-
-function isAsciiLetter(c: number): boolean {
- return (c >= 0x41 && c <= 0x5a) || (c >= 0x61 && c <= 0x7a)
-}
-
-function isAsciiAlphanumeric(c: number): boolean {
- return isAsciiLetter(c) || (c >= 0x30 && c <= 0x39)
-}
-
-// [A-Za-z0-9._%+-]
-function isLocalChar(c: number): boolean {
- return isAsciiAlphanumeric(c) || c === 0x2e || c === 0x5f || c === 0x25 || c === 0x2b || c === 0x2d
-}
-
-// [A-Za-z0-9.-]
-function isDomainChar(c: number): boolean {
- return isAsciiAlphanumeric(c) || c === 0x2e || c === 0x2d
-}
-
-export function scrubText(ctx: ScrubContext, input: string): ScrubResult {
- // Nuke whole email addresses first; the tokenizer then runs over what's left.
- const emails = redactEmails(input)
- const text = emails.value
- let changed = emails.changed
- let out = ''
- let lastIndex = 0
-
- WORD_RE.lastIndex = 0
- let match: RegExpExecArray | null
- while ((match = WORD_RE.exec(text)) !== null) {
- const word = match[0]
- const start = match.index
- if (start > lastIndex) {
- out += text.slice(lastIndex, start)
- }
- const emitted = emitWord(word, ctx.allow)
- out += emitted.value
- changed = changed || emitted.changed
- lastIndex = WORD_RE.lastIndex
- }
- if (lastIndex < text.length) {
- out += text.slice(lastIndex)
- }
-
- return { value: out, changed }
-}
-
-function emitWord(word: string, allow: AllowLists): ScrubResult {
- if (isNumericToken(word)) {
- return { value: redact(word, NUMBER_CHAR), changed: true }
- }
- if (wordIsAllowed(allow, word)) {
- return { value: word, changed: false }
- }
- return { value: redact(word, REDACT_CHAR), changed: true }
-}
-
-/** Length-preserving redaction: one mark per source code point (not UTF-16 unit). */
-function redact(word: string, mark: string): string {
- return mark.repeat(codePointLength(word))
-}
-
-function codePointLength(s: string): number {
- let n = 0
- for (let i = 0; i < s.length; i++) {
- n++
- const c = s.charCodeAt(i)
- if (c >= 0xd800 && c <= 0xdbff && i + 1 < s.length) {
- i++ // skip the low surrogate
- }
- }
- return n
-}
-
-function wordIsAllowed(allow: AllowLists, word: string): boolean {
- if (allow.textContains(word)) {
- return true
- }
- if (word.includes('’')) {
- const normalized = word.replace(/’/g, "'")
- if (allow.textContains(normalized)) {
- return true
- }
- const base = stripPossessive(normalized)
- if (base !== null && allow.textContains(base)) {
- return true
- }
- }
- const base = stripPossessive(word)
- if (base !== null && allow.textContains(base)) {
- return true
- }
- return false
-}
-
-function stripPossessive(word: string): string | null {
- for (const suffix of ["'s", '’s', "'", '’']) {
- if (word.endsWith(suffix)) {
- const base = word.slice(0, word.length - suffix.length)
- if (base.length > 0) {
- return base
- }
- }
- }
- return null
-}
-
-function isNumericToken(word: string): boolean {
- let sawDigit = false
- for (const c of word) {
- if (c >= '0' && c <= '9') {
- sawDigit = true
- } else if (c !== '.' && c !== ',' && c !== '-' && c !== '+') {
- return false
- }
- }
- return sawDigit
-}
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/anonymize/url.test.ts b/nodejs/src/ingestion/pipelines/sessionreplay/anonymize/url.test.ts
deleted file mode 100644
index bf54e9f1f68b..000000000000
--- a/nodejs/src/ingestion/pipelines/sessionreplay/anonymize/url.test.ts
+++ /dev/null
@@ -1,121 +0,0 @@
-import { AllowLists } from './allow-lists'
-import { defaultAllowLists } from './default-dict'
-import { firstPartyHostPatterns, scrubUrl } from './url'
-
-describe('anonymize/url', () => {
- const allow = defaultAllowLists()
- const scrub = (input: string): string => scrubUrl({ allow }, input).value
-
- it('keeps allow-listed segments, masks numbers, and redacts other identifiers', () => {
- expect(scrub('https://example.com/api/v1/users/42/profile')).toBe('https://example.com/api/v1/users/$$/profile')
- })
-
- it('drops non-allow-listed query params and fragments', () => {
- expect(scrub('https://example.com/dashboard?token=secret#frag')).toBe('https://example.com/dashboard')
- })
-
- it('redacts segments in a relative path', () => {
- expect(scrub('/user/abc/edit')).toBe('/user/[redacted]/edit')
- })
-
- it('keeps the authority verbatim for a protocol-relative URL', () => {
- expect(scrub('//cdn.example.com/assets/abc/logo.png')).toBe('//cdn.example.com/assets/[redacted]/[redacted]')
- })
-
- it('treats a host-only URL (no path) as authority and leaves it unchanged', () => {
- expect(scrub('https://example.com')).toBe('https://example.com')
- expect(scrub('//cdn.example.com')).toBe('//cdn.example.com')
- })
-
- it('redacts a bare relative segment with no authority', () => {
- expect(scrub('secrettoken')).toBe('[redacted]')
- })
-
- it('leaves a fully allow-listed path untouched (no change)', () => {
- expect(scrub('https://example.com/api/v1/users')).toBe('https://example.com/api/v1/users')
- })
-
- describe('collapseHost (Meta only)', () => {
- const ctx = { allow: new AllowLists([], ['us', 'api', 'v1', 'users', 'profile']) }
- const sa = (i: string): string => scrubUrl(ctx, i, { collapseHost: true }).value
-
- it('keeps an allow-listed subdomain and rewrites the rest to example.com', () => {
- expect(sa('https://us.website.com/api/v1/users/42/profile')).toBe(
- 'https://us.example.com/api/v1/users/$$/profile'
- )
- })
- it('drops a 2-label host to example.com (no doubled label)', () => {
- expect(sa('https://website.com/x')).toBe('https://example.com/[redacted]')
- expect(sa('https://example.com/x')).toBe('https://example.com/[redacted]')
- })
- it('strips userinfo and port', () => {
- expect(sa('https://user:[email protected]:8443/x')).toBe('https://us.example.com/[redacted]')
- })
- it('default (no opts) keeps the authority verbatim', () => {
- expect(scrub('https://us.website.com/users/42')).toBe('https://us.website.com/users/$$')
- })
- })
-
- describe('query and fragment (numbers scrubbed; key/value allow-listed with [key]/[value] fallback)', () => {
- const ctx = { allow: new AllowLists([], ['app', 'page', 'sort', 'tab', 'q', 'about', 'asc', 'settings']) }
- const u = (i: string): string => scrubUrl(ctx, i).value
-
- it('keeps params whose key and value are both allow-listed (+ an allow-listed fragment)', () => {
- expect(u('https://example.com/app?sort=asc&tab=settings#about')).toBe(
- 'https://example.com/app?sort=asc&tab=settings#about'
- )
- })
- it('masks a numeric value with $ per digit, kept because the key is allow-listed', () => {
- expect(u('https://example.com/app?page=2')).toBe('https://example.com/app?page=$')
- expect(u('https://example.com/app?page=2024')).toBe('https://example.com/app?page=$$$$')
- })
- it('drops a param whose only non-denied side is a number (number counts as denied)', () => {
- expect(u('https://example.com/app?id=42')).toBe('https://example.com/app')
- })
- it('replaces the denied side: key allowed + value denied → key=[value]', () => {
- expect(u('https://example.com/app?sort=secret')).toBe('https://example.com/app?sort=[value]')
- })
- it('replaces the denied side: key denied + value allowed → [key]=value', () => {
- expect(u('https://example.com/app?xyz=asc')).toBe('https://example.com/app?[key]=asc')
- })
- it('drops the param only when both key and value are denied', () => {
- expect(u('https://example.com/app?token=secret')).toBe('https://example.com/app')
- })
- it('treats a complex (non-alphanumeric) value as denied → [value]', () => {
- expect(u('https://example.com/app?q=a%20b')).toBe('https://example.com/app?q=[value]')
- })
- it('keeps a bare allow-listed flag and drops a denied one', () => {
- expect(u('https://example.com/app?sort&token')).toBe('https://example.com/app?sort')
- })
- it('keeps an allow-listed fragment and drops a numeric or non-allow-listed one', () => {
- expect(u('https://example.com/app#about')).toBe('https://example.com/app#about')
- expect(u('https://example.com/app#42')).toBe('https://example.com/app') // number alone → dropped
- expect(u('https://example.com/app#xyz')).toBe('https://example.com/app') // not allow-listed
- })
- })
-
- it('masks a bare-number path segment with $', () => {
- const numCtx = { allow: new AllowLists([], ['users']) }
- expect(scrubUrl(numCtx, 'https://example.com/users/2/x').value).toBe('https://example.com/users/$/[redacted]')
- })
-
- describe('firstPartyHostPatterns reduces recording domains to registrable domains', () => {
- test.each([
- ['subdomain and scheme dropped', ['https://www.example.com'], ['example.com']],
- ['deep subdomain dropped', ['https://app.eu.example.com'], ['example.com']],
- ['multi-part public suffix kept', ['https://www.example.co.uk'], ['example.co.uk']],
- ['wildcard entry reduces to its base', ['https://*.example.com'], ['example.com']],
- ['port and path dropped', ['https://app.example.com:5000/welcome'], ['example.com']],
- ['localhost kept whole', ['capacitor://localhost'], ['localhost']],
- ['ip kept whole', ['http://192.168.0.10:3000'], ['192.168.0.10']],
- ['bare wildcard ignored, casing normalized', ['*', 'https://App.Example.com'], ['example.com']],
- ['null and empty input give no patterns', null, []],
- ['private-suffix platform host keeps the tenant label', ['https://myapp.vercel.app'], ['myapp.vercel.app']],
- ['bare public suffix entries are dropped', ['https://*.com', 'https://co.uk'], []],
- ['non-string elements are skipped', [null as any, 'https://www.example.com'], ['example.com']],
- ['opaque-scheme host is lowercased', ['capacitor://LocalHost'], ['localhost']],
- ] as [string, string[] | null, string[]][])('%s', (_name, domains, expected) => {
- expect(firstPartyHostPatterns(domains)).toEqual(expected)
- })
- })
-})
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/anonymize/url.ts b/nodejs/src/ingestion/pipelines/sessionreplay/anonymize/url.ts
deleted file mode 100644
index 09451f809e25..000000000000
--- a/nodejs/src/ingestion/pipelines/sessionreplay/anonymize/url.ts
+++ /dev/null
@@ -1,324 +0,0 @@
-/**
- * URL scrub.
- *
- * - Numbers (a bare run of digits) are masked to `$` per digit (length-preserving; `$` rather than `#`
- * so it doesn't clash with the fragment separator).
- * - Path: keep allow-listed segments; a number → `$$`; anything else → `[redacted]`.
- * - Query: a param survives only if its key or value is an allow-listed alphanumeric token. A number
- * counts as denied for survival, so `id=42` is dropped while `page=2` → `page=$`. When a param
- * survives, each side renders independently: allow-listed → kept, number → `$$`, denied → `[key]`/`[value]`.
- * - Fragment: kept only if it is an allow-listed alphanumeric token; numbers and everything else dropped.
- * - Userinfo (`user:pass@`) is always stripped from the authority.
- * - A scheme without slashes (`mailto:`, `tel:`) is kept; the rest is scrubbed as a path.
- * - With `{ collapseHost: true }`, or when the host matches the context's first-party host
- * patterns (the team's recording domains), it additionally drops the port and collapses the
- * host to `example.com` (keeping a leading allow-listed subdomain label).
- */
-import { parse as parseHostname } from 'tldts'
-
-import { ScrubContext } from './config'
-import { ScrubResult } from './text'
-
-export interface UrlScrubOptions {
- collapseHost?: boolean
-}
-
-export const URL_ALLOWLIST = ['about:blank', 'about:srcdoc']
-
-const SIMPLE = /^[A-Za-z0-9]*$/ // 100% alphanumeric (empty allowed)
-const NUMERIC = /^[0-9]+$/ // a bare number
-const HOST_PORT = /^(\[[0-9A-Fa-f:.]+\]|[A-Za-z0-9._-]*)(:\d+)?$/ // host or [ipv6], optional port
-
-const maskNumber = (n: string): string => '$'.repeat(n.length) // `$`, not `#` (the fragment separator)
-
-// An allow-listed, alphanumeric, non-number token — the only kind that keeps a query param/fragment
-// alive.
-function isAllowed(ctx: ScrubContext, t: string): boolean {
- return t.length > 0 && SIMPLE.test(t) && !NUMERIC.test(t) && ctx.allow.urlContains(t)
-}
-
-// Rendered form of a surviving token: a number → `$$`, an allow-listed token → itself, else null.
-function renderToken(ctx: ScrubContext, t: string): string | null {
- return NUMERIC.test(t) ? maskNumber(t) : isAllowed(ctx, t) ? t : null
-}
-
-export function scrubUrl(ctx: ScrubContext, input: string, opts?: UrlScrubOptions): ScrubResult {
- if (URL_ALLOWLIST.includes(input)) {
- return { value: input, changed: false }
- }
- const tailIdx = input.search(/[?#]/)
- const base = tailIdx === -1 ? input : input.slice(0, tailIdx)
- const tail = tailIdx === -1 ? '' : input.slice(tailIdx) // starts with ? or #
- let changed = false
-
- const { scheme, authority, path } = splitUrl(base)
- let out = scheme
- if (authority) {
- const at = authority.lastIndexOf('@')
- if (at !== -1) {
- changed = true
- }
- const hostPort = authority.slice(at + 1)
- if (!HOST_PORT.test(hostPort)) {
- // A structurally invalid "host" (e.g. an unencoded `?` in userinfo makes `user:pa`
- // parse as the authority) must not pass through as if it were a hostname.
- out += '[redacted]'
- changed = true
- } else if (opts?.collapseHost || isFirstPartyHost(ctx, hostPort)) {
- const collapsed = collapsedHost(ctx, hostPort)
- if (collapsed !== hostPort) {
- changed = true
- }
- out += collapsed
- } else {
- out += hostPort
- }
- }
-
- let first = true
- for (const raw of path.split('/')) {
- if (first) {
- first = false
- } else {
- out += '/'
- }
- if (raw.length === 0) {
- continue
- }
- if (NUMERIC.test(raw)) {
- out += maskNumber(raw) // a bare number → $$
- changed = true
- } else if (isSafeSegment(raw) || ctx.allow.urlContains(raw)) {
- out += raw
- } else {
- out += '[redacted]'
- changed = true
- }
- }
-
- const tailOut = scrubTail(ctx, tail)
- if (tailOut !== tail) {
- changed = true
- }
- out += tailOut
-
- return { value: out, changed }
-}
-
-function scrubTail(ctx: ScrubContext, tail: string): string {
- if (tail === '') {
- return ''
- }
- let query = ''
- let frag = ''
- if (tail[0] === '?') {
- const h = tail.indexOf('#')
- query = h === -1 ? tail.slice(1) : tail.slice(1, h)
- frag = h === -1 ? '' : tail.slice(h + 1)
- } else {
- frag = tail.slice(1) // tail starts with '#'
- }
-
- let out = ''
- if (tail[0] === '?') {
- const kept: string[] = []
- for (const pair of query.split('&')) {
- if (pair === '') {
- continue
- }
- const eq = pair.indexOf('=')
- if (eq === -1) {
- if (isAllowed(ctx, pair)) {
- kept.push(pair)
- }
- continue
- }
- const key = pair.slice(0, eq)
- const value = pair.slice(eq + 1)
- if (!isAllowed(ctx, key) && !(value !== '' && isAllowed(ctx, value))) {
- continue
- }
- const kr = renderToken(ctx, key) ?? '[key]'
- const vr = value === '' ? '' : (renderToken(ctx, value) ?? '[value]')
- kept.push(`${kr}=${vr}`)
- }
- if (kept.length > 0) {
- out += '?' + kept.join('&')
- }
- }
- if (frag.length > 0 && isAllowed(ctx, frag)) {
- out += '#' + frag
- }
- return out
-}
-
-export function firstPartyHostPatterns(recordingDomains: string[] | null | undefined): string[] {
- const patterns: string[] = []
- for (const domain of recordingDomains ?? []) {
- // The DB column allows NULL elements; one bad entry must not poison the team refresh.
- if (typeof domain !== 'string') {
- continue
- }
- const trimmed = domain.trim()
- if (trimmed === '') {
- continue
- }
- let hostname: string
- try {
- hostname = new URL(trimmed.includes('://') ? trimmed : `https://${trimmed}`).hostname
- } catch {
- continue
- }
- if (hostname.startsWith('*.')) {
- hostname = hostname.slice(2)
- }
- if (hostname === '' || hostname === '*') {
- continue
- }
- const parsed = parseHostname(hostname, { allowPrivateDomains: true })
- if (parsed.domain !== null) {
- patterns.push(parsed.domain.toLowerCase())
- continue
- }
- // No registrable domain: keep bare machine names (`localhost`, `intranet`) and IPs, but
- // drop listed public suffixes (`com`, `co.uk`, a bare `github.io`) — a suffix pattern
- // would match every host under it.
- if (parsed.isIp || !(parsed.isIcann || parsed.isPrivate)) {
- patterns.push(hostname.toLowerCase())
- }
- }
- return patterns
-}
-
-function isFirstPartyHost(ctx: ScrubContext, hostPort: string): boolean {
- const patterns = ctx.firstPartyHosts
- if (!patterns || patterns.length === 0) {
- return false
- }
- const host = hostPort.replace(/:\d+$/, '').toLowerCase()
- return patterns.some((pattern) => host === pattern || host.endsWith(`.${pattern}`))
-}
-
-// Drop the port and rewrite the host to example.com. Keep a leading *subdomain* label
-// (only when there is one, i.e. ≥3 labels) if it's url-allow-listed: `us.test.com` → `us.example.com`.
-function collapsedHost(ctx: ScrubContext, hostPort: string): string {
- const host = hostPort.replace(/:\d+$/, '')
- const labels = host.split('.')
- const first = labels[0] ?? ''
- return labels.length > 2 && first && ctx.allow.urlContains(first) ? `${first}.example.com` : 'example.com'
-}
-
-const SCHEME_NO_SLASHES = /^[A-Za-z][A-Za-z0-9+.-]*:/ // RFC 3986 scheme, e.g. `mailto:`, `tel:`
-
-export const URL_SCHEME_ALLOWLIST = new Set([
- // Web platform
- 'about',
- 'blob',
- 'data',
- 'file',
- 'ftp',
- 'geo',
- 'javascript',
- 'magnet',
- 'mailto',
- 'sms',
- 'tel',
- 'urn',
- 'ws',
- 'wss',
- // Microsoft
- 'ms-access',
- 'ms-excel',
- 'ms-outlook',
- 'ms-powerpoint',
- 'ms-project',
- 'ms-publisher',
- 'ms-visio',
- 'ms-word',
- 'msteams',
- 'onenote',
- 'sip',
- 'sips',
- 'skype',
- // Google
- 'comgooglemaps',
- 'googlechrome',
- 'googlegmail',
- 'googlemaps',
- // Apple
- 'facetime',
- 'facetime-audio',
- 'itms',
- 'itms-apps',
- 'maps',
- 'music',
- 'shortcuts',
- // Chat and social
- 'bluesky',
- 'callto',
- 'discord',
- 'fb',
- 'fb-messenger',
- 'instagram',
- 'irc',
- 'line',
- 'linkedin',
- 'matrix',
- 'reddit',
- 'sgnl',
- 'slack',
- 'snapchat',
- 'telegram',
- 'tg',
- 'tiktok',
- 'twitter',
- 'viber',
- 'wechat',
- 'weixin',
- 'whatsapp',
- 'xmpp',
- // Media, payments, and tools
- 'bitcoin',
- 'bittorrent',
- 'figma',
- 'notion',
- 'obsidian',
- 'spotify',
- 'steam',
- 'vscode',
- 'zoommtg',
- 'zoomus',
-])
-
-const VALID_SCHEME = /^[A-Za-z][A-Za-z0-9+.-]*$/ // RFC 3986 scheme body
-
-// Split into scheme prefix (incl. `://` or `//`), authority (`[userinfo@]host[:port]`), and path.
-function splitUrl(s: string): { scheme: string; authority: string; path: string } {
- let scheme = ''
- let rest = s
- const schemeEnd = s.indexOf('://')
- if (schemeEnd !== -1 && VALID_SCHEME.test(s.slice(0, schemeEnd))) {
- scheme = s.slice(0, schemeEnd + 3)
- rest = s.slice(schemeEnd + 3)
- } else if (s.startsWith('//')) {
- scheme = '//'
- rest = s.slice(2)
- } else {
- // Free text before a colon (or before an embedded `://`) must not pass through as a
- // "scheme"; only allowlisted schemes survive, and only in the slashless form.
- const m = SCHEME_NO_SLASHES.exec(s)
- if (m && URL_SCHEME_ALLOWLIST.has(m[0].slice(0, -1).toLowerCase())) {
- return { scheme: m[0], authority: '', path: s.slice(m[0].length) }
- }
- return { scheme: '', authority: '', path: s } // relative URL: all path
- }
- const pathOff = rest.indexOf('/')
- if (pathOff === -1) {
- return { scheme, authority: rest, path: '' }
- }
- return { scheme, authority: rest.slice(0, pathOff), path: rest.slice(pathOff) }
-}
-
-function isSafeSegment(seg: string): boolean {
- return seg === '' || seg === '.' || seg === '..'
-}
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/anonymize/value.test.ts b/nodejs/src/ingestion/pipelines/sessionreplay/anonymize/value.test.ts
deleted file mode 100644
index 57b777f7981a..000000000000
--- a/nodejs/src/ingestion/pipelines/sessionreplay/anonymize/value.test.ts
+++ /dev/null
@@ -1,65 +0,0 @@
-import { defaultAllowLists } from './default-dict'
-import { scrubConsolePlugin, scrubGenericField, scrubNetworkPlugin } from './value'
-
-describe('anonymize/value', () => {
- const ctx = { allow: defaultAllowLists() }
-
- describe('scrubGenericField', () => {
- it('recurses objects/arrays, scrubs string leaves, leaves keys and non-strings alone', () => {
- const owner = {
- payload: {
- a: 'Hello SecretName',
- b: ['Hello SecretName', 42, true],
- c: { url: 'https://example.com/user/abc/profile?token=secret' },
- },
- }
- expect(scrubGenericField(ctx, owner, 'payload')).toBe(true)
- expect(owner.payload.a).toBe('Hello **********')
- expect(owner.payload.b[0]).toBe('Hello **********')
- expect(owner.payload.b[1]).toBe(42)
- expect(owner.payload.b[2]).toBe(true)
- // http(s) string leaves are URL-scrubbed (denied query dropped), not text-scrubbed.
- expect(owner.payload.c.url).toBe('https://example.com/user/[redacted]/profile')
- })
-
- it('scrubs a bare string field in place', () => {
- const owner: Record<string, unknown> = { payload: 'Hello SecretName' }
- expect(scrubGenericField(ctx, owner, 'payload')).toBe(true)
- expect(owner.payload).toBe('Hello **********')
- })
-
- it('reports no change when nothing is scrubbable', () => {
- const owner = { payload: { count: 1, ok: true } }
- expect(scrubGenericField(ctx, owner, 'payload')).toBe(false)
- })
- })
-
- describe('scrubNetworkPlugin', () => {
- it('scrubs request header values', () => {
- const owner = {
- payload: { requests: [{ requestHeaders: { Authorization: 'Bearer SecretToken' } }] },
- }
- expect(scrubNetworkPlugin(ctx, owner, 'payload')).toBe(true)
- expect(owner.payload.requests[0].requestHeaders.Authorization).toBe('Bearer ***********')
- })
-
- it('falls back to a generic scrub when the payload is not an object', () => {
- const owner: Record<string, unknown> = { payload: 'Hello SecretName' }
- expect(scrubNetworkPlugin(ctx, owner, 'payload')).toBe(true)
- expect(owner.payload).toBe('Hello **********')
- })
-
- it('returns no change when the requests array is missing', () => {
- const owner = { payload: { somethingElse: 1 } }
- expect(scrubNetworkPlugin(ctx, owner, 'payload')).toBe(false)
- })
- })
-
- describe('scrubConsolePlugin', () => {
- it('falls back to a generic scrub when the payload is not an object', () => {
- const owner: Record<string, unknown> = { payload: 'Hello SecretName' }
- expect(scrubConsolePlugin(ctx, owner, 'payload')).toBe(true)
- expect(owner.payload).toBe('Hello **********')
- })
- })
-})
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/anonymize/value.ts b/nodejs/src/ingestion/pipelines/sessionreplay/anonymize/value.ts
deleted file mode 100644
index 5f560c281115..000000000000
--- a/nodejs/src/ingestion/pipelines/sessionreplay/anonymize/value.ts
+++ /dev/null
@@ -1,121 +0,0 @@
-/** Generic / network / console value scrubs over parsed JSON (Custom and Plugin payloads). */
-import { ScrubContext, isObject } from './config'
-import { ScrubResult, scrubText } from './text'
-import { scrubUrl } from './url'
-
-const NETWORK_BODY_FIELDS = ['requestBody', 'responseBody']
-const NETWORK_HEADER_FIELDS = ['requestHeaders', 'responseHeaders']
-const CONSOLE_FIELDS = ['payload', 'trace']
-
-type ScrubFn = (ctx: ScrubContext, s: string) => ScrubResult
-
-function looksLikeUrl(s: string): boolean {
- return s.startsWith('http://') || s.startsWith('https://')
-}
-
-function scrubStringLeaf(ctx: ScrubContext, s: string): ScrubResult {
- return looksLikeUrl(s) ? scrubUrl(ctx, s) : scrubText(ctx, s)
-}
-
-/** Scrub `container[key]` if it is a string, writing back on change. */
-function scrubFieldWith(ctx: ScrubContext, container: any, key: string | number, scrub: ScrubFn): boolean {
- const value = container[key]
- if (typeof value !== 'string') {
- return false
- }
- const result = scrub(ctx, value)
- if (result.changed) {
- container[key] = result.value
- return true
- }
- return false
-}
-
-/** Scrub `container[key]`: a string leaf (with writeback), otherwise recurse into it. */
-function scrubChild(ctx: ScrubContext, container: any, key: string | number): boolean {
- const value = container[key]
- if (typeof value !== 'string') {
- return scrubValueInPlace(ctx, value)
- }
- const result = scrubStringLeaf(ctx, value)
- if (result.changed) {
- container[key] = result.value
- return true
- }
- return false
-}
-
-/** Recursively scrub string leaves inside an array/object, mutating in place. */
-export function scrubValueInPlace(ctx: ScrubContext, value: unknown): boolean {
- let changed = false
- if (Array.isArray(value)) {
- for (let i = 0; i < value.length; i++) {
- changed = scrubChild(ctx, value, i) || changed
- }
- } else if (isObject(value)) {
- for (const key of Object.keys(value)) {
- changed = scrubChild(ctx, value, key) || changed
- }
- }
- return changed
-}
-
-/** Generic scrub of `owner[key]`, handling both a string leaf and a container. */
-export function scrubGenericField(ctx: ScrubContext, owner: Record<string, unknown>, key: string): boolean {
- return scrubChild(ctx, owner, key)
-}
-
-/**
- * rrweb/network@1 payload at `owner[key]`: `{ requests: CapturedNetworkRequest[] }`.
- * Per request: `name` is a Resource Timing URL (URL-scrub); request/response
- * bodies and every header value are free text. Falls back to the generic field
- * scrub if the shape is off.
- */
-export function scrubNetworkPlugin(ctx: ScrubContext, owner: Record<string, unknown>, key: string): boolean {
- const payload = owner[key]
- if (!isObject(payload)) {
- return scrubGenericField(ctx, owner, key)
- }
- const reqs = payload.requests
- if (!Array.isArray(reqs)) {
- return false
- }
- let changed = false
- for (const req of reqs) {
- if (!isObject(req)) {
- continue
- }
- changed = scrubFieldWith(ctx, req, 'name', scrubUrl) || changed
- for (const field of NETWORK_BODY_FIELDS) {
- changed = scrubFieldWith(ctx, req, field, scrubText) || changed
- }
- for (const field of NETWORK_HEADER_FIELDS) {
- const hdrs = req[field]
- if (isObject(hdrs)) {
- for (const k of Object.keys(hdrs)) {
- changed = scrubFieldWith(ctx, hdrs, k, scrubText) || changed
- }
- }
- }
- }
- return changed
-}
-
-/** rrweb/console@1 payload at `owner[key]`: `{ level, payload: string[], trace: string[] }`. */
-export function scrubConsolePlugin(ctx: ScrubContext, owner: Record<string, unknown>, key: string): boolean {
- const payload = owner[key]
- if (!isObject(payload)) {
- return scrubGenericField(ctx, owner, key)
- }
- let changed = false
- for (const field of CONSOLE_FIELDS) {
- const arr = payload[field]
- if (Array.isArray(arr)) {
- for (let i = 0; i < arr.length; i++) {
- // Console frames can hold URLs (stack traces); scrub URL-aware, not as plain text.
- changed = scrubFieldWith(ctx, arr, i, scrubStringLeaf) || changed
- }
- }
- }
- return changed
-}
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/src/blur.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/src/blur.ts
index 21ef04423cc4..a1d3a95268fc 100644
--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/src/blur.ts
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/src/blur.ts
@@ -1,4 +1,4 @@
-// These params must stay in sync with nodejs/.../anonymize/blur.ts, or the mirror diverges from the inline anonymizer.
+// These params must stay in sync with rust/replay-anonymizer-node/src/blur.rs, or the mirror diverges from the inline anonymizer.
import sharp from 'sharp'
// One libvips thread per op and no cross-request cache, so N concurrent scrubs cost ~N threads (not N x CPU)
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/config.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/config.ts
index 576e59c0343e..3d7bcc833856 100644
--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/config.ts
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/config.ts
@@ -36,8 +36,6 @@ export type MlMirrorConfig = {
// Scrub-phase budget. Sized so scrub + 2x the S3 write timeout stays under Kafka's max.poll.interval.ms
// (300s), or a hung sidecar/S3 evicts us mid-batch and livelocks.
SESSION_RECORDING_ML_IMAGE_SCRUB_MAX_BATCH_SCRUB_MS: number
- /** Route anonymization through the native Rust addon (`@posthog/replay-anonymizer`, the default); off → the TS scrubbers. */
- SESSION_RECORDING_ML_RUST_ANONYMIZER: boolean
}
export function getDefaultMlMirrorConfig(): MlMirrorConfig {
@@ -63,6 +61,5 @@ export function getDefaultMlMirrorConfig(): MlMirrorConfig {
SESSION_RECORDING_ML_IMAGE_SCRUB_SCRUB_RETRIES: 3,
SESSION_RECORDING_ML_IMAGE_SCRUB_S3_WRITE_TIMEOUT_MS: 30 * 1000,
SESSION_RECORDING_ML_IMAGE_SCRUB_MAX_BATCH_SCRUB_MS: 120 * 1000,
- SESSION_RECORDING_ML_RUST_ANONYMIZER: true,
}
}
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/first-party-hosts.test.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/first-party-hosts.test.ts
new file mode 100644
index 000000000000..cae48f08ede1
--- /dev/null
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/first-party-hosts.test.ts
@@ -0,0 +1,21 @@
+import { firstPartyHostPatterns } from './first-party-hosts'
+
+describe('firstPartyHostPatterns reduces recording domains to registrable domains', () => {
+ test.each([
+ ['subdomain and scheme dropped', ['https://www.example.com'], ['example.com']],
+ ['deep subdomain dropped', ['https://app.eu.example.com'], ['example.com']],
+ ['multi-part public suffix kept', ['https://www.example.co.uk'], ['example.co.uk']],
+ ['wildcard entry reduces to its base', ['https://*.example.com'], ['example.com']],
+ ['port and path dropped', ['https://app.example.com:5000/welcome'], ['example.com']],
+ ['localhost kept whole', ['capacitor://localhost'], ['localhost']],
+ ['ip kept whole', ['http://192.168.0.10:3000'], ['192.168.0.10']],
+ ['bare wildcard ignored, casing normalized', ['*', 'https://App.Example.com'], ['example.com']],
+ ['null and empty input give no patterns', null, []],
+ ['private-suffix platform host keeps the tenant label', ['https://myapp.vercel.app'], ['myapp.vercel.app']],
+ ['bare public suffix entries are dropped', ['https://*.com', 'https://co.uk'], []],
+ ['non-string elements are skipped', [null as any, 'https://www.example.com'], ['example.com']],
+ ['opaque-scheme host is lowercased', ['capacitor://LocalHost'], ['localhost']],
+ ] as [string, string[] | null, string[]][])('%s', (_name, domains, expected) => {
+ expect(firstPartyHostPatterns(domains)).toEqual(expected)
+ })
+})
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/first-party-hosts.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/first-party-hosts.ts
new file mode 100644
index 000000000000..36f17b597620
--- /dev/null
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/first-party-hosts.ts
@@ -0,0 +1,43 @@
+import { parse as parseHostname } from 'tldts'
+
+/**
+ * Reduce a team's recording domains to registrable-domain patterns; the anonymizer collapses
+ * matching hosts to `example.com`.
+ */
+export function firstPartyHostPatterns(recordingDomains: string[] | null | undefined): string[] {
+ const patterns: string[] = []
+ for (const domain of recordingDomains ?? []) {
+ // The DB column allows NULL elements; one bad entry must not poison the team refresh.
+ if (typeof domain !== 'string') {
+ continue
+ }
+ const trimmed = domain.trim()
+ if (trimmed === '') {
+ continue
+ }
+ let hostname: string
+ try {
+ hostname = new URL(trimmed.includes('://') ? trimmed : `https://${trimmed}`).hostname
+ } catch {
+ continue
+ }
+ if (hostname.startsWith('*.')) {
+ hostname = hostname.slice(2)
+ }
+ if (hostname === '' || hostname === '*') {
+ continue
+ }
+ const parsed = parseHostname(hostname, { allowPrivateDomains: true })
+ if (parsed.domain !== null) {
+ patterns.push(parsed.domain.toLowerCase())
+ continue
+ }
+ // No registrable domain: keep bare machine names (`localhost`, `intranet`) and IPs, but
+ // drop listed public suffixes (`com`, `co.uk`, a bare `github.io`) — a suffix pattern
+ // would match every host under it.
+ if (parsed.isIp || !(parsed.isIcann || parsed.isPrivate)) {
+ patterns.push(hostname.toLowerCase())
+ }
+ }
+ return patterns
+}
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/ml-mirror-pipeline.test.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/ml-mirror-pipeline.test.ts
index 6ffd373938e6..9789fb581ef8 100644
--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/ml-mirror-pipeline.test.ts
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/ml-mirror-pipeline.test.ts
@@ -4,6 +4,8 @@ import { Message } from 'node-rdkafka'
import { DLQ_OUTPUT, INGESTION_WARNINGS_OUTPUT, OVERFLOW_OUTPUT } from '~/common/outputs'
import { IngestionOutputs } from '~/common/outputs/ingestion-outputs'
import { EventIngestionRestrictionManager } from '~/common/utils/event-ingestion-restrictions'
+import { parseJSON } from '~/common/utils/json-parse'
+import { logger } from '~/common/utils/logger'
import { PromiseScheduler } from '~/common/utils/promise-scheduler'
import { createApplyEventRestrictionsStep, createParseHeadersStep } from '~/ingestion/common/steps/event-preprocessing'
import { TopHogRegistry } from '~/ingestion/framework/extensions/tophog'
@@ -34,6 +36,19 @@ jest.mock('~/ingestion/common/steps/event-preprocessing', () => ({
const mockCreateParseHeadersStep = createParseHeadersStep as jest.Mock
const mockCreateApplyEventRestrictionsStep = createApplyEventRestrictionsStep as jest.Mock
+// The pipeline's parse+anonymize step runs inside the native addon; scrub-dependent tests need it built.
+let rustAddon: typeof import('@posthog/replay-anonymizer') | null = null
+try {
+ rustAddon = require('@posthog/replay-anonymizer')
+ rustAddon!.initAnonymizer(defaultAllowLists().entries())
+} catch (e) {
+ if (process.env.CI) {
+ throw new Error(`replay-anonymizer addon failed to load; pipeline tests cannot run in CI: ${String(e)}`)
+ }
+ logger.warn('🙈', 'replay_anonymizer_addon_not_built_skipping_pipeline_scrub_tests')
+}
+const itAddon = rustAddon ? it : it.skip
+
function createMockTopHog(): TopHogRegistry {
const recorder = { record: jest.fn() }
return {
@@ -52,7 +67,6 @@ describe('ml-mirror-pipeline', () => {
let outputs: jest.Mocked<
IngestionOutputs<typeof DLQ_OUTPUT | typeof OVERFLOW_OUTPUT | typeof INGESTION_WARNINGS_OUTPUT>
>
- const scrubContext = { allow: defaultAllowLists() }
// Resolves every session to 30d so messages flow through to recording.
const retentionService = {
@@ -136,7 +150,6 @@ describe('ml-mirror-pipeline', () => {
topHog,
sessionBatchManager: mockSessionBatchManager,
isDebugLoggingEnabled: () => false,
- scrubContext,
})
}
@@ -221,7 +234,17 @@ describe('ml-mirror-pipeline', () => {
} as unknown as Message
}
- it('anonymizes events before recording for an opted-in team', async () => {
+ // The fused step emits pre-serialized JSONL lines of [windowId, event].
+ function recordedEvents(): [string, any][] {
+ const lines: Buffer = recordMock.mock.calls[0][0].message.preSerialized.lines
+ return lines
+ .toString()
+ .split('\n')
+ .filter((l) => l.length > 0)
+ .map((l) => parseJSON(l))
+ }
+
+ itAddon('anonymizes events before recording for an opted-in team', async () => {
mockTeamService = {
getTeamByToken: jest.fn().mockResolvedValue(team(true)),
getRetentionPeriodByTeamId: jest.fn().mockResolvedValue(30),
@@ -230,9 +253,10 @@ describe('ml-mirror-pipeline', () => {
await runSessionReplayPipeline(buildPipeline(), [message('sess-1')])
expect(recordMock).toHaveBeenCalledTimes(1)
- const recorded = recordMock.mock.calls[0][0]
+ const [windowId, event] = recordedEvents()[0]
+ expect(windowId).toBe('window-1')
// The Input event's text was scrubbed before it reached the recorder.
- expect(recorded.message.eventsByWindowId['window-1'][0].data.text).toBe('Hello **********')
+ expect(event.data.text).toBe('Hello **********')
})
it('drops sessions for a team that did not opt into AI training', async () => {
@@ -246,7 +270,7 @@ describe('ml-mirror-pipeline', () => {
expect(recordMock).not.toHaveBeenCalled()
})
- it('scrubs a FullSnapshot (text, url, free-text data-*) end-to-end before recording', async () => {
+ itAddon('scrubs a FullSnapshot (text, url, free-text data-*) end-to-end before recording', async () => {
mockTeamService = {
getTeamByToken: jest.fn().mockResolvedValue(team(true)),
getRetentionPeriodByTeamId: jest.fn().mockResolvedValue(30),
@@ -255,7 +279,7 @@ describe('ml-mirror-pipeline', () => {
await runSessionReplayPipeline(buildPipeline(), [fullSnapshotMessage('sess-3')])
expect(recordMock).toHaveBeenCalledTimes(1)
- const node = recordMock.mock.calls[0][0].message.eventsByWindowId['window-1'][0].data.node.childNodes[0]
+ const node = recordedEvents()[0][1].data.node.childNodes[0]
expect(node.childNodes[0].textContent).toBe('Hello **********') // DOM text
expect(node.attributes.href).toContain('https://example.com/') // authority kept...
expect(node.attributes.href).not.toContain('abc') // ...path segments redacted
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/ml-mirror-pipeline.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/ml-mirror-pipeline.ts
index daa4c2ec27f8..483d7552edf5 100644
--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/ml-mirror-pipeline.ts
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/ml-mirror-pipeline.ts
@@ -11,10 +11,7 @@ import {
SessionReplayPipelineOutput,
} from '~/ingestion/pipelines/sessionreplay'
import { createAiTrainingOptInFilterStep } from '~/ingestion/pipelines/sessionreplay/ai-training-optin-filter-step'
-import { createAnonymizeStep } from '~/ingestion/pipelines/sessionreplay/anonymize-step'
-import { ScrubContext } from '~/ingestion/pipelines/sessionreplay/anonymize/config'
import { createParseAndAnonymizeMessageStep } from '~/ingestion/pipelines/sessionreplay/parse-and-anonymize-step'
-import { createParseMessageStep } from '~/ingestion/pipelines/sessionreplay/parse-message-step'
import { MessageContext } from '~/ingestion/pipelines/sessionreplay/pipeline-types'
import { createRecordSessionEventStep } from '~/ingestion/pipelines/sessionreplay/record-session-event-step'
import { createMarkSeenStep } from '~/ingestion/pipelines/sessionreplay/session-batch-mark-seen-step'
@@ -24,13 +21,8 @@ import { createResolveKeyStep } from '~/ingestion/pipelines/sessionreplay/sessio
import { createTeamFilterStep } from '~/ingestion/pipelines/sessionreplay/team-filter-step'
import { createValidateSessionReplayHeadersStep } from '~/ingestion/pipelines/sessionreplay/validate-headers-step'
-export type MlMirrorReplayPipelineConfig = SessionReplayPipelineConfig & {
- /** Shared, immutable scrub context (allow lists + tunables). */
- scrubContext: ScrubContext
-}
-
export function createMlMirrorReplayPipeline(
- config: MlMirrorReplayPipelineConfig
+ config: SessionReplayPipelineConfig
): BatchPipeline<
SessionReplayPipelineInput,
SessionReplayPipelineOutput,
@@ -52,7 +44,6 @@ export function createMlMirrorReplayPipeline(
topHog,
sessionBatchManager,
isDebugLoggingEnabled,
- scrubContext,
} = config
const pipelineConfig: PipelineConfig<OverflowOutput> = { outputs, promiseScheduler }
@@ -121,26 +112,15 @@ export function createMlMirrorReplayPipeline(
.teamAware((b) =>
b
.sequentially((b) => {
- // The Rust native path fuses parse+anonymize in one step
- const parsed = scrubContext.useRustAnonymizer
- ? b.pipe(
- topHogWrapper(createParseAndAnonymizeMessageStep(), [
- timer('parse_time_ms_by_session_id', (input) => ({
- token: input.headers.token ?? 'unknown',
- session_id: input.headers.session_id ?? 'unknown',
- })),
- ])
- )
- : b
- .pipe(
- topHogWrapper(createParseMessageStep(), [
- timer('parse_time_ms_by_session_id', (input) => ({
- token: input.headers.token ?? 'unknown',
- session_id: input.headers.session_id ?? 'unknown',
- })),
- ])
- )
- .pipe(createAnonymizeStep({ scrubContext }))
+ // The native Rust addon fuses parse+anonymize in one step.
+ const parsed = b.pipe(
+ topHogWrapper(createParseAndAnonymizeMessageStep(), [
+ timer('parse_time_ms_by_session_id', (input) => ({
+ token: input.headers.token ?? 'unknown',
+ session_id: input.headers.session_id ?? 'unknown',
+ })),
+ ])
+ )
return parsed.pipe(
topHogWrapper(
createRecordSessionEventStep({
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/shared-fixtures.test.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/shared-fixtures.test.ts
new file mode 100644
index 000000000000..10dc248c7663
--- /dev/null
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/shared-fixtures.test.ts
@@ -0,0 +1,217 @@
+import fs from 'fs'
+import path from 'path'
+import { gzipSync, zstdDecompressSync } from 'zlib'
+
+import { parseJSON } from '~/common/utils/json-parse'
+import { logger } from '~/common/utils/logger'
+
+// Shared fixtures pin the addon's behavior through the FFI; the pure-Rust side of the same
+// fixtures is covered by rust/replay-anonymizer-node/tests/parity.rs.
+const FIXTURE_DIR = path.resolve(__dirname, '../../../../../../rust/replay-anonymizer-node/tests/fixtures')
+
+interface AllowSpec {
+ text: string[]
+ url: string[]
+}
+interface EventCase {
+ name: string
+ allow: AllowSpec
+ event: Record<string, unknown>
+ expected: Record<string, unknown>
+}
+interface MessageCase {
+ name: string
+ allow: AllowSpec
+ message: Record<string, unknown[]>
+ expected: Record<string, unknown>
+}
+
+function load<T>(name: string): T[] {
+ return parseJSON(fs.readFileSync(path.join(FIXTURE_DIR, name), 'utf8'))
+}
+
+let rustAddon: typeof import('@posthog/replay-anonymizer') | null = null
+try {
+ rustAddon = require('@posthog/replay-anonymizer')
+} catch (e) {
+ if (process.env.CI) {
+ throw new Error(`replay-anonymizer addon failed to load; native parity cannot run in CI: ${String(e)}`)
+ }
+ logger.warn('🙈', 'replay_anonymizer_addon_not_built_skipping_native_parity')
+}
+
+const describeAddon = rustAddon ? describe : describe.skip
+describeAddon('native rust addon matches the shared fixtures', () => {
+ const eventCases = load<EventCase>('events.json')
+ const messageCases = load<MessageCase>('messages.json')
+
+ const TS0 = 1_700_000_000_000
+
+ // Wrap fixture events in the Kafka payload shape
+ function payloadOf(windowId: string, events: unknown[]): Buffer {
+ const items = structuredClone(events)
+ items.forEach((ev, i) => {
+ if (isRecord(ev)) {
+ ev.timestamp ??= TS0 + i
+ }
+ })
+ const inner = JSON.stringify({
+ event: '$snapshot_items',
+ properties: { $snapshot_items: items, $session_id: 's-1', $window_id: windowId },
+ })
+ return Buffer.from(JSON.stringify({ distinct_id: 'd-1', data: inner }))
+ }
+
+ function isRecord(v: unknown): v is Record<string, unknown> {
+ return typeof v === 'object' && v !== null && !Array.isArray(v)
+ }
+
+ function expectedLines(windowId: string, expected: unknown[]): unknown[] {
+ const events = structuredClone(expected)
+ events.forEach((ev, i) => {
+ if (isRecord(ev)) {
+ ev.timestamp ??= TS0 + i
+ }
+ })
+ return events.filter(isRecord).map((ev) => [windowId, ev])
+ }
+
+ function parseLines(lines: Buffer): unknown[] {
+ return lines
+ .toString()
+ .split('\n')
+ .filter((l) => l.length > 0)
+ .map((l) => parseJSON(l))
+ }
+
+ describe('events', () => {
+ test.each(eventCases.map((c) => [c.name, c] as const))('event: %s', async (_name, c) => {
+ // --runInBand is required to ensure cases are sequential
+ rustAddon!.initAnonymizer(c.allow)
+ const result = await rustAddon!.anonymizeKafkaPayload(payloadOf('w', [c.event]))
+ expect(result.failed).toBe(false)
+ expect(parseLines(result.lines!)).toEqual(expectedLines('w', [c.expected]))
+ })
+ })
+
+ test.each(messageCases.map((c) => [c.name, c] as const))('message: %s', async (_name, c) => {
+ rustAddon!.initAnonymizer(c.allow)
+ for (const [windowId, events] of Object.entries(c.message)) {
+ const expected = expectedLines(windowId, (c.expected as Record<string, unknown[]>)[windowId])
+ const result = await rustAddon!.anonymizeKafkaPayload(payloadOf(windowId, events))
+ if (expected.length === 0) {
+ // A window with only invalid events: the fused step drops the whole message.
+ expect(result.failed).toBe(true)
+ expect(result.reason).toBe('message_contained_no_valid_rrweb_events')
+ continue
+ }
+ expect(result.failed).toBe(false)
+ expect(parseLines(result.lines!)).toEqual(expected)
+ }
+ })
+
+ it('collapses first-party hosts passed per call', async () => {
+ const event = {
+ type: 2,
+ data: {
+ node: {
+ type: 0,
+ childNodes: [
+ {
+ type: 2,
+ tagName: 'a',
+ attributes: { href: 'https://app.customer-site.test/settings' },
+ childNodes: [],
+ },
+ ],
+ },
+ initialOffset: { top: 0, left: 0 },
+ },
+ }
+ rustAddon!.initAnonymizer({ text: [], url: [] })
+ const result = await rustAddon!.anonymizeKafkaPayload(payloadOf('w', [event]), undefined, [
+ 'customer-site.test',
+ ])
+ expect(result.failed).toBe(false)
+ const line = parseLines(result.lines!)[0] as [
+ string,
+ { data: { node: { childNodes: { attributes: Record<string, string> }[] } } },
+ ]
+ expect(line[1].data.node.childNodes[0].attributes.href).toBe('https://example.com/[redacted]')
+ })
+
+ // fixtures are plain text, convert to gzip bytes for this test
+ describe('cv-compressed events through the production entry', () => {
+ // latin-1: each compressed byte is a U+00XX codepoint, matching the SDK wire format.
+ const gzipLatin1 = (json: string): string => Buffer.from(gzipSync(Buffer.from(json))).toString('latin1')
+ const unzstdLatin1 = (s: string): unknown => {
+ const raw = Buffer.from(s, 'latin1')
+ // Magic-byte dispatch is the loader contract; pin the zstd frame magic on decode.
+ expect([...raw.subarray(0, 4)]).toEqual([0x28, 0xb5, 0x2f, 0xfd])
+ return parseJSON(zstdDecompressSync(raw).toString())
+ }
+
+ const fullSnapshot = {
+ type: 2,
+ cv: '2024-10',
+ data: gzipLatin1(
+ JSON.stringify({
+ node: { type: 0, id: 1, childNodes: [{ type: 3, id: 5, textContent: 'keep secret' }] },
+ initialOffset: { top: 0, left: 0 },
+ })
+ ),
+ }
+ const mutation = {
+ type: 3,
+ cv: '2024-10',
+ data: { source: 0, texts: gzipLatin1(JSON.stringify([{ id: 5, value: 'keep secret' }])) },
+ }
+
+ it('scrubs a cv full snapshot and re-emits a decodable zstd payload', async () => {
+ rustAddon!.initAnonymizer({ text: ['keep'], url: [] })
+ const result = await rustAddon!.anonymizeKafkaPayload(payloadOf('w', [fullSnapshot]))
+ expect(result.failed).toBe(false)
+ const line = parseLines(result.lines!)[0] as [string, { data: string }]
+ const decoded = unzstdLatin1(line[1].data) as { node: { childNodes: { textContent: string }[] } }
+ expect(decoded.node.childNodes[0].textContent).toBe('keep ******')
+ })
+
+ it('media-scrubs an rr_src attribute inside a cv mutation sub-field', async () => {
+ const attrMutation = {
+ type: 3,
+ cv: '2024-10',
+ data: {
+ source: 0,
+ attributes: gzipLatin1(
+ JSON.stringify([
+ {
+ id: 7,
+ attributes: {
+ rr_src: 'https://widget.example-vendor.co/v2/app/?refreshToken=FakeRefreshTok3nValue000',
+ },
+ },
+ ])
+ ),
+ },
+ }
+ rustAddon!.initAnonymizer({ text: [], url: [] })
+ const result = await rustAddon!.anonymizeKafkaPayload(payloadOf('w', [attrMutation]))
+ expect(result.failed).toBe(false)
+ const line = parseLines(result.lines!)[0] as [string, { data: { attributes: string } }]
+ const decoded = unzstdLatin1(line[1].data.attributes) as { attributes: Record<string, string> }[]
+ expect(decoded[0].attributes.rr_src).toMatch(/^data:image\/svg\+xml/)
+ expect(decoded[0].attributes['data-anon-original-rr_src']).toBe(
+ 'https://example.com/[redacted]/[redacted]/'
+ )
+ })
+
+ it('scrubs a cv mutation sub-field and re-emits a decodable zstd payload', async () => {
+ rustAddon!.initAnonymizer({ text: ['keep'], url: [] })
+ const result = await rustAddon!.anonymizeKafkaPayload(payloadOf('w', [mutation]))
+ expect(result.failed).toBe(false)
+ const line = parseLines(result.lines!)[0] as [string, { data: { texts: string } }]
+ const decoded = unzstdLatin1(line[1].data.texts) as { value: string }[]
+ expect(decoded[0].value).toBe('keep ******')
+ })
+ })
+})
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/parse-and-anonymize-step.ts b/nodejs/src/ingestion/pipelines/sessionreplay/parse-and-anonymize-step.ts
index caac1100288e..e4d361f8bef3 100644
--- a/nodejs/src/ingestion/pipelines/sessionreplay/parse-and-anonymize-step.ts
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/parse-and-anonymize-step.ts
@@ -15,7 +15,7 @@ import { TeamForReplay } from './shared/teams/types'
const MESSAGE_TIMESTAMP_DIFF_THRESHOLD_DAYS = 7
-// Lazily loaded so environments that never enable the flag don't pay the native-module load (and so a
+// Lazily loaded so deployments that never run this step don't pay the native-module load (and so a
// missing addon only breaks the native path, not every import of this module).
type RustAnonymizer = typeof import('@posthog/replay-anonymizer')
let rustAnonymizer: RustAnonymizer | undefined
@@ -38,8 +38,7 @@ const DLQ_REASONS = new Set([
* Fused parse + anonymize through the native Rust addon (`@posthog/replay-anonymizer`): the
* decompressed Kafka payload bytes go in, scrubbed JSONL block lines plus the envelope/per-event
* metadata come out — no per-event JS objects are ever built, and no JSON crosses the FFI boundary
- * as a string. Replaces `createParseMessageStep` + `createAnonymizeStep` on the ml-mirror pipeline
- * when `SESSION_RECORDING_ML_RUST_ANONYMIZER` is on.
+ * as a string.
*
* Fail-closed: any addon failure drops (or DLQs) the message — un-anonymized data never reaches the
* unencrypted ML bucket. Failure classification matches the TS parse step so DLQ/drop behavior and
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/shared/teams/team-service.ts b/nodejs/src/ingestion/pipelines/sessionreplay/shared/teams/team-service.ts
index 739e108beb0a..45a70f1d909a 100644
--- a/nodejs/src/ingestion/pipelines/sessionreplay/shared/teams/team-service.ts
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/shared/teams/team-service.ts
@@ -1,7 +1,7 @@
import { BackgroundRefresher } from '~/common/utils/background-refresher'
import { PostgresRouter, PostgresUse } from '~/common/utils/db/postgres'
import { logger } from '~/common/utils/logger'
-import { firstPartyHostPatterns } from '~/ingestion/pipelines/sessionreplay/anonymize/url'
+import { firstPartyHostPatterns } from '~/ingestion/pipelines/sessionreplay/ml-mirror/first-party-hosts'
import { RetentionPeriod, isValidRetentionPeriod } from '~/ingestion/pipelines/sessionreplay/shared/constants'
import { Team, TeamId } from '~/types'
diff --git a/nodejs/src/servers/ingestion-session-replay-ml-mirror-server.ts b/nodejs/src/servers/ingestion-session-replay-ml-mirror-server.ts
index 7376443af805..1e32dbc74870 100644
--- a/nodejs/src/servers/ingestion-session-replay-ml-mirror-server.ts
+++ b/nodejs/src/servers/ingestion-session-replay-ml-mirror-server.ts
@@ -9,7 +9,6 @@ import { logger } from '~/common/utils/logger'
import { getDefaultKafkaDownstreamProducerEnvConfig } from '~/ingestion/common/outputs/producers'
import { getDefaultIngestionConsumerConfig } from '~/ingestion/config'
import { AllowListFetcher, loadAllowLists } from '~/ingestion/pipelines/sessionreplay/anonymize/allow-list-loader'
-import { ScrubContext } from '~/ingestion/pipelines/sessionreplay/anonymize/config'
import {
type SessionReplayProducerName,
getDefaultSessionRecordingApiConfig,
@@ -129,18 +128,14 @@ export class IngestionSessionReplayMlMirrorServer implements NodeServer {
: new BlackholeSessionBatchFileStorage()
const allow = await loadAllowLists(this.buildAllowListFetcher(s3Client, bucket))
- const useRustAnonymizer = this.config.SESSION_RECORDING_ML_RUST_ANONYMIZER
- if (useRustAnonymizer) {
- // Lazy require so the native addon is only loaded (and only needs to ship) when the flag is
- // on; the addon holds its own copy of the immutable allow lists, set once at startup.
- const anonymizer = require('@posthog/replay-anonymizer') as typeof import('@posthog/replay-anonymizer')
- anonymizer.initAnonymizer(allow.entries())
- // The addon's scrub runs on the libuv threadpool (UV_THREADPOOL_SIZE, default 4) shared
- // with the recorder's snappy compression — size it for the deployment if scrub backs up.
- await assertAnonymizerHealthy(anonymizer)
- logger.info('🦀', 'ml_mirror_rust_anonymizer_enabled')
- }
- const scrubContext: ScrubContext = { allow, useRustAnonymizer }
+ // Lazy require so only ml-mirror deployments load (and need to ship) the native addon; the
+ // addon holds its own copy of the immutable allow lists, set once at startup.
+ const anonymizer = require('@posthog/replay-anonymizer') as typeof import('@posthog/replay-anonymizer')
+ anonymizer.initAnonymizer(allow.entries())
+ // The addon's scrub runs on the libuv threadpool (UV_THREADPOOL_SIZE, default 4) shared
+ // with the recorder's snappy compression — size it for the deployment if scrub backs up.
+ await assertAnonymizerHealthy(anonymizer)
+ logger.info('🦀', 'ml_mirror_rust_anonymizer_initialized')
// Block metadata is produced to Kafka; the dedicated Parquet-sink deployment writes it to the ML bucket.
const metadataStore = new MlBlockMetadataSink(outputs, pseudonymSecret)
@@ -158,7 +153,7 @@ export class IngestionSessionReplayMlMirrorServer implements NodeServer {
featureStore: new SessionFeatureStore(outputs, false),
keyStore,
encryptor: new CleartextRecordingEncryptor(keyStore),
- createPipeline: (pipelineConfig) => createMlMirrorReplayPipeline({ ...pipelineConfig, scrubContext }),
+ createPipeline: (pipelineConfig) => createMlMirrorReplayPipeline(pipelineConfig),
// Isolate the mirror's session tracker/filter keys from the main lane. Sharing them would let
// the cleartext mirror mark a session seen without the main lane's KMS key, so the main lane
// would then fetch a missing key and record cleartext.
diff --git a/rust/replay-anonymizer-node/src/assets.rs b/rust/replay-anonymizer-node/src/assets.rs
index 2470f7272f82..0ca4d1b7a56a 100644
--- a/rust/replay-anonymizer-node/src/assets.rs
+++ b/rust/replay-anonymizer-node/src/assets.rs
@@ -1,4 +1,4 @@
-//! Media detection + placeholder/blur dispatch. Mirrors `anonymize/assets.ts`.
+//! Media detection + placeholder/blur dispatch.
//! Blur runs inline (native), so there is no deferred-job/blank-first dance — the attribute lands on
//! its final blurred (or placeholder) value directly.
diff --git a/rust/replay-anonymizer-node/src/blur.rs b/rust/replay-anonymizer-node/src/blur.rs
index 6b8d73d90e68..2c5b6e0f9232 100644
--- a/rust/replay-anonymizer-node/src/blur.rs
+++ b/rust/replay-anonymizer-node/src/blur.rs
@@ -1,6 +1,6 @@
//! Downsample + blur media/canvas images — scene stays legible, faces/text don't.
-//! Native Rust replacement for `anonymize/blur.ts` (which used `sharp`). Runs inline (synchronously);
-//! output is never byte-identical to sharp, so tests assert structure (decodes to W x H PNG), not bytes.
+//! Runs inline (synchronously). Output is never byte-identical to `sharp` (which the image-scrub
+//! sidecar still uses, with matching params), so tests assert structure (decodes to W x H PNG), not bytes.
use base64::Engine;
use image::{DynamicImage, GenericImageView, RgbaImage};
diff --git a/rust/replay-anonymizer-node/src/canvas.rs b/rust/replay-anonymizer-node/src/canvas.rs
index 42b3fe14be58..eb728dba8480 100644
--- a/rust/replay-anonymizer-node/src/canvas.rs
+++ b/rust/replay-anonymizer-node/src/canvas.rs
@@ -1,6 +1,6 @@
//! Scrubs rrweb CanvasMutation events: redacts text drawn via fill/strokeText and blurs drawn images
-//! and canvas snapshots. Mirrors `anonymize/canvas.ts`, with the deferred sharp jobs replaced by inline
-//! native blur (so the object lands on its final blurred/blanked value directly).
+//! and canvas snapshots. Blur runs inline (native), so the object lands on its final blurred/blanked
+//! value directly.
use base64::Engine;
use simd_json::borrowed::{Object, Value};
diff --git a/rust/replay-anonymizer-node/src/css.rs b/rust/replay-anonymizer-node/src/css.rs
index fcccda411cec..c7923053dcc7 100644
--- a/rust/replay-anonymizer-node/src/css.rs
+++ b/rust/replay-anonymizer-node/src/css.rs
@@ -1,6 +1,5 @@
-//! Blur inline `url(data:image/...;base64,...)` backgrounds in CSS. Mirrors `anonymize/css.ts`, but the
-//! regex `URL_DATA_IMAGE_RE` is replaced with a single linear left-to-right scan (no backtracking).
-//! `None` means "unchanged".
+//! Blur inline `url(data:image/...;base64,...)` backgrounds in CSS, using a single linear
+//! left-to-right scan (no backtracking regex). `None` means "unchanged".
use std::borrow::Cow;
diff --git a/rust/replay-anonymizer-node/src/cv.rs b/rust/replay-anonymizer-node/src/cv.rs
index 251f2fe0a192..5050ccb7f9b2 100644
--- a/rust/replay-anonymizer-node/src/cv.rs
+++ b/rust/replay-anonymizer-node/src/cv.rs
@@ -1,5 +1,4 @@
//! Decode/scrub/re-encode per-event `cv` compression (gzip stored as latin-1 codepoints).
-//! Mirrors `anonymize/cv.ts`.
use anyhow::{bail, Context, Result};
use simd_json::borrowed::{Object, Value};
diff --git a/rust/replay-anonymizer-node/src/dom.rs b/rust/replay-anonymizer-node/src/dom.rs
index 3a46a8e553a6..ea9361c0c249 100644
--- a/rust/replay-anonymizer-node/src/dom.rs
+++ b/rust/replay-anonymizer-node/src/dom.rs
@@ -1,6 +1,6 @@
//! Walks parsed rrweb serialized nodes, scrubbing text content and attributes in place.
-//! Mirrors `anonymize/dom.ts`, operating on `simd_json::BorrowedValue` (generic objects) so unknown
-//! fields survive the round-trip exactly, matching the TS in-place mutation.
+//! Operates on `simd_json::BorrowedValue` (generic objects) so unknown fields survive the
+//! round-trip exactly.
use simd_json::borrowed::{Object, Value};
diff --git a/rust/replay-anonymizer-node/src/event.rs b/rust/replay-anonymizer-node/src/event.rs
index d48189df820b..4cd6220b3206 100644
--- a/rust/replay-anonymizer-node/src/event.rs
+++ b/rust/replay-anonymizer-node/src/event.rs
@@ -1,5 +1,5 @@
//! Routes each parsed rrweb event to the right scrubber by type/source, and walks a whole parsed
-//! message (`{ windowId: Event[] }`). Mirrors `anonymize/anonymize-event.ts` (`routeEvent`).
+//! message (`{ windowId: Event[] }`).
use anyhow::{bail, Context, Result};
use simd_json::borrowed::{Object, Value};
diff --git a/rust/replay-anonymizer-node/src/lib.rs b/rust/replay-anonymizer-node/src/lib.rs
index bdbca8483770..13acdbff360f 100644
--- a/rust/replay-anonymizer-node/src/lib.rs
+++ b/rust/replay-anonymizer-node/src/lib.rs
@@ -1,10 +1,9 @@
//! Session-replay anonymizer: PII-scrubs rrweb events for the ml-mirror pipeline, exposed to Node as
//! a Neon native addon.
//!
-//! The scrubbers are a Rust port of `nodejs/src/ingestion/pipelines/sessionreplay/anonymize/*.ts`
-//! (the source of truth): text/URL redaction, native image blur, `cv` de/recompression. Parity with
-//! the TS is asserted via shared JSON fixtures under `tests/fixtures/` (the same fixtures the Jest
-//! suite runs against).
+//! The scrubbers cover text/URL redaction, native image blur, and `cv` de/recompression. Behavior
+//! is pinned by the shared JSON fixtures under `tests/fixtures/`, which both `tests/parity.rs` and
+//! the Jest suite (through the addon) run against.
//!
//! The production surface is the byte-buffer pipeline in [`snapshot`]: the decompressed Kafka payload
//! goes in, ready-to-write JSONL block lines plus envelope/per-event metadata come out — Rust owns
diff --git a/rust/replay-anonymizer-node/src/text.rs b/rust/replay-anonymizer-node/src/text.rs
index 5d37aae2bf96..48503c4dcf2e 100644
--- a/rust/replay-anonymizer-node/src/text.rs
+++ b/rust/replay-anonymizer-node/src/text.rs
@@ -1,5 +1,5 @@
//! Length-preserving text scrub: numeric tokens -> `#`, allow-listed words kept, everything else -> `*`.
-//! Mirrors `anonymize/text.ts`. `None` means "unchanged" (caller keeps the original).
+//! `None` means "unchanged" (caller keeps the original).
use crate::allow_lists::AllowLists;
diff --git a/rust/replay-anonymizer-node/src/url.rs b/rust/replay-anonymizer-node/src/url.rs
index b2c4b5d31f3b..620362de8c6a 100644
--- a/rust/replay-anonymizer-node/src/url.rs
+++ b/rust/replay-anonymizer-node/src/url.rs
@@ -1,4 +1,4 @@
-//! URL scrub. Mirrors `anonymize/url.ts`. `None` means "unchanged".
+//! URL scrub. `None` means "unchanged".
//!
//! - Numbers (a bare run of digits) are masked to `$` per digit (length-preserving; `$` rather than
//! `#` so it doesn't clash with the fragment separator).
@@ -14,7 +14,6 @@
use crate::allow_lists::AllowLists;
use crate::context::Ctx;
-// Mirrors `URL_ALLOWLIST` in `anonymize/url.ts`.
pub const URL_ALLOWLIST: &[&str] = &["about:blank", "about:srcdoc"];
fn strip_port(host: &mut String) {
@@ -194,7 +193,7 @@ fn collapsed_host(allow: &AllowLists, host_port: &str) -> String {
}
}
-// Mirrors `URL_SCHEME_ALLOWLIST` in `anonymize/url.ts`.
+// Pinned by `tests/fixtures/url-scheme-allowlist.json` (see `tests/parity.rs`).
pub const URL_SCHEME_ALLOWLIST: &[&str] = &[
// Web platform
"about",
@@ -320,7 +319,7 @@ fn split_url(s: &str) -> (&str, &str, &str) {
}
}
-// Host or `[ipv6]`, with an optional `:digits` port. Mirrors `HOST_PORT` in `anonymize/url.ts`.
+// Host or `[ipv6]`, with an optional `:digits` port.
fn is_valid_host_port(host_port: &str) -> bool {
let host = match host_port.split_once(':') {
None => host_port,
diff --git a/rust/replay-anonymizer-node/src/value.rs b/rust/replay-anonymizer-node/src/value.rs
index a816858e3cdf..5abca59d8911 100644
--- a/rust/replay-anonymizer-node/src/value.rs
+++ b/rust/replay-anonymizer-node/src/value.rs
@@ -1,5 +1,4 @@
//! Generic / network / console value scrubs over parsed JSON (Custom and Plugin payloads).
-//! Mirrors `anonymize/value.ts`.
use simd_json::borrowed::{Object, Value};