Skip to content

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

feat(ai-research): Rust (Neon) session-replay anonymizer for ml-mirror (#67917)

Robbiea57886eee8ec
diff --git a/.github/CODEOWNERS-soft b/.github/CODEOWNERS-soft
index 831f801d8926..e68b2dc0c379 100644
--- a/.github/CODEOWNERS-soft
+++ b/.github/CODEOWNERS-soft
@@ -25,6 +25,8 @@ frontend/src/toolbar/product-tours/** @PostHog/team-surveys
nodejs/tests/ @PostHog/team-ingestion
nodejs/src/ingestion/ @PostHog/team-ingestion
nodejs/src/ingestion/pipelines/sessionreplay/ @PostHog/team-replay @PostHog/team-ingestion
+# Rust session-replay anonymizer (native counterpart of the sessionreplay anonymize pipeline)
+rust/replay-anonymizer-node/** @PostHog/team-ai-research
nodejs/src/cdp/ @PostHog/team-workflows
nodejs/src/session-replay/recording-rasterizer/ @PostHog/team-replay
diff --git a/.github/workflows/ci-nodejs-container.yml b/.github/workflows/ci-nodejs-container.yml
index b158d2c47072..0cc6900be655 100644
--- a/.github/workflows/ci-nodejs-container.yml
+++ b/.github/workflows/ci-nodejs-container.yml
@@ -47,6 +47,7 @@ jobs:
- 'common/replay-headless/**'
- 'rust/cyclotron-node/**'
- 'rust/common/hogvm/**'
+ - 'rust/replay-anonymizer-node/**'
- 'Dockerfile.node'
- '.github/workflows/ci-nodejs-container.yml'
- 'turbo.json'
diff --git a/.github/workflows/ci-nodejs.yml b/.github/workflows/ci-nodejs.yml
index 4d4832540698..a8a24f9ab3f4 100644
--- a/.github/workflows/ci-nodejs.yml
+++ b/.github/workflows/ci-nodejs.yml
@@ -58,6 +58,9 @@ jobs:
# Node DB setup builds sqlx-cli via this composite; changes to it must exercise these jobs.
- '.github/actions/setup-sqlx-cli/**'
- 'nodejs/**'
+ # The Jest shared-fixtures suite pins the native replay anonymizer against
+ # its Rust tests; a rust-side change (incl. the shared fixtures) must run it.
+ - 'rust/replay-anonymizer-node/**'
- 'posthog/clickhouse/**'
- 'ee/migrations/**'
- 'posthog/management/commands/setup_test_environment.py'
diff --git a/.github/workflows/ci-rust.yml b/.github/workflows/ci-rust.yml
index f045ed859f29..0b6f837e262c 100644
--- a/.github/workflows/ci-rust.yml
+++ b/.github/workflows/ci-rust.yml
@@ -153,6 +153,7 @@ jobs:
"personhog-router": 38,
"posthog-symbol-data": 19,
"property-defs-rs": 136,
+ "replay-anonymizer-node": 20,
"property-vals-rs": 5,
"serve-metrics": 14,
}
diff --git a/Dockerfile.node b/Dockerfile.node
index a182e946e05a..db0114d24b58 100644
--- a/Dockerfile.node
+++ b/Dockerfile.node
@@ -76,6 +76,9 @@ RUN NODE_OPTIONS="--max-old-space-size=16384" bin/turbo --filter=@posthog/cyclot
# Build the rust hogvm napi addon (shadow execution of transformations)
RUN NODE_OPTIONS="--max-old-space-size=16384" bin/turbo --filter=@posthog/hogvm-node build
+# Build the session-replay anonymizer native addon
+RUN NODE_OPTIONS="--max-old-space-size=16384" bin/turbo --filter=@posthog/replay-anonymizer build
+
# Build replay-headless (dependency of nodejs rasterizer code)
RUN NODE_OPTIONS="--max-old-space-size=16384" bin/turbo --filter=@posthog/replay-headless build
# Then build the nodejs services
@@ -133,6 +136,9 @@ COPY --from=nodejs-build --chown=posthog:posthog /code/rust/cyclotron-node/index
COPY --from=nodejs-build --chown=posthog:posthog /code/rust/common/hogvm/node/package.json /code/rust/common/hogvm/node/package.json
COPY --from=nodejs-build --chown=posthog:posthog /code/rust/common/hogvm/node/index.js /code/rust/common/hogvm/node/index.js
COPY --from=nodejs-build --chown=posthog:posthog /code/rust/common/hogvm/node/index.node /code/rust/common/hogvm/node/index.node
+COPY --from=nodejs-build --chown=posthog:posthog /code/rust/replay-anonymizer-node/dist /code/rust/replay-anonymizer-node/dist
+COPY --from=nodejs-build --chown=posthog:posthog /code/rust/replay-anonymizer-node/package.json /code/rust/replay-anonymizer-node/package.json
+COPY --from=nodejs-build --chown=posthog:posthog /code/rust/replay-anonymizer-node/index.node /code/rust/replay-anonymizer-node/index.node
COPY --from=nodejs-build --chown=posthog:posthog /code/common/plugin_transpiler/dist /code/common/plugin_transpiler/dist
COPY --from=nodejs-build --chown=posthog:posthog /code/common/plugin_transpiler/node_modules /code/common/plugin_transpiler/node_modules
COPY --from=nodejs-build --chown=posthog:posthog /code/common/plugin_transpiler/package.json /code/common/plugin_transpiler/package.json
diff --git a/nodejs/.eslintrc.js b/nodejs/.eslintrc.js
index 081462fb6d21..8741f4e40398 100644
--- a/nodejs/.eslintrc.js
+++ b/nodejs/.eslintrc.js
@@ -19,6 +19,7 @@ module.exports = {
'src/common/config/idl',
// Standalone package with its own oxlint config; not part of the plugin-server eslint pass.
'src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar',
+ '**/dev/**',
],
rules: {
'no-restricted-syntax': [
diff --git a/nodejs/jest.config.js b/nodejs/jest.config.js
index adda62b60600..a02db978576d 100644
--- a/nodejs/jest.config.js
+++ b/nodejs/jest.config.js
@@ -19,6 +19,8 @@ module.exports = {
'<rootDir>/.tmp/',
'<rootDir>/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/',
],
+ // `dev/` folders hold dev-only benchmarks/scripts, never CI tests.
+ testPathIgnorePatterns: ['/node_modules/', '/dev/'],
// NOTE: This should be kept in sync with tsconfig.json
moduleNameMapper: {
diff --git a/nodejs/package.json b/nodejs/package.json
index eb00ff6802f4..7a1f17a09a50 100644
--- a/nodejs/package.json
+++ b/nodejs/package.json
@@ -8,7 +8,7 @@
"main": "dist/index.js",
"types": "dist/index.d.ts",
"scripts": {
- "test": "SHARD_IDX=${SHARD_INDEX:-1}; SHARD_TOTAL=${SHARD_COUNT:-1}; echo $SHARD_IDX/$SHARD_TOTAL; jest --runInBand --forceExit --shard=$SHARD_IDX/$SHARD_TOTAL --testPathIgnorePatterns='postgres-parity|service-e2e'",
+ "test": "SHARD_IDX=${SHARD_INDEX:-1}; SHARD_TOTAL=${SHARD_COUNT:-1}; echo $SHARD_IDX/$SHARD_TOTAL; jest --runInBand --forceExit --shard=$SHARD_IDX/$SHARD_TOTAL --testPathIgnorePatterns='postgres-parity|service-e2e|/dev/'",
"test:rust-ingestion-e2e": "jest --runInBand --forceExit --testPathPatterns='service-e2e/rust-ingestion-consumer.test.ts'",
"test:postgres-parity": "jest --runInBand --forceExit --testPathPatterns='postgres-parity'",
"start": "pnpm start:dev",
@@ -48,6 +48,8 @@
"build:cyclotron:dev": "pnpm --filter=@posthog/cyclotron run build:dev",
"build:hogvm-node": "pnpm --filter=@posthog/hogvm-node build",
"build:hogvm-node:dev": "pnpm --filter=@posthog/hogvm-node run build:dev",
+ "build:replay-anonymizer": "pnpm --filter=@posthog/replay-anonymizer package",
+ "build:replay-anonymizer:dev": "pnpm --filter=@posthog/replay-anonymizer run build:dev",
"generate:personhog-proto": "cd ../proto && buf generate --template ../nodejs/buf.gen.yaml --path personhog/service --path personhog/types .",
"update-ai-costs": "ts-node src/ingestion/pipelines/ai/costs/scripts/update-ai-costs.ts",
"sync-segment-icons": "DATABASE_URL=something ts-node src/cdp/segment/sync-segment-icons.ts",
@@ -90,6 +92,7 @@
"@posthog/cyclotron": "workspace:*",
"@posthog/hogvm": "workspace:*",
"@posthog/hogvm-node": "workspace:*",
+ "@posthog/replay-anonymizer": "workspace:*",
"@posthog/replay-headless": "workspace:*",
"@posthog/siphash": "1.1.1",
"@pyroscope/nodejs": "^0.4.8",
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/anonymize/allow-lists.ts b/nodejs/src/ingestion/pipelines/sessionreplay/anonymize/allow-lists.ts
index 8d79f9b2f462..0c930f3952c4 100644
--- a/nodejs/src/ingestion/pipelines/sessionreplay/anonymize/allow-lists.ts
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/anonymize/allow-lists.ts
@@ -42,4 +42,8 @@ export class AllowLists {
public urlContains(segment: string): boolean {
return this.url.has(hasUpperAscii(segment) ? asciiLowercase(segment) : segment)
}
+
+ public entries(): { text: string[]; url: string[] } {
+ return { text: [...this.text], url: [...this.url] }
+ }
}
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/anonymize/anonymize-event.ts b/nodejs/src/ingestion/pipelines/sessionreplay/anonymize/anonymize-event.ts
index 6bae9d3c6aa1..e56a79b2f3e1 100644
--- a/nodejs/src/ingestion/pipelines/sessionreplay/anonymize/anonymize-event.ts
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/anonymize/anonymize-event.ts
@@ -1,6 +1,7 @@
/** 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'
@@ -46,6 +47,7 @@ export async function anonymizeParsedMessage(
error: String(error),
type: isObject(event) ? event.type : undefined,
})
+ SessionRecordingIngesterMetrics.incrementMlAnonymizeFailed('ts')
return { failed: true }
}
eventCount++
@@ -58,6 +60,8 @@ export async function anonymizeParsedMessage(
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),
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/anonymize/config.ts b/nodejs/src/ingestion/pipelines/sessionreplay/anonymize/config.ts
index e7939214b022..12de1e7be1b4 100644
--- a/nodejs/src/ingestion/pipelines/sessionreplay/anonymize/config.ts
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/anonymize/config.ts
@@ -26,6 +26,7 @@ export interface ScrubContext {
blurCache?: BlurCache
/** Optional diagnostic timing accumulator (see {@link ScrubTiming}). */
timing?: ScrubTiming
+ useRustAnonymizer?: boolean
}
/** Shared non-null-object type guard used across the scrubbers. */
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/anonymize/shared-fixtures.test.ts b/nodejs/src/ingestion/pipelines/sessionreplay/anonymize/shared-fixtures.test.ts
new file mode 100644
index 000000000000..68da7e45f535
--- /dev/null
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/anonymize/shared-fixtures.test.ts
@@ -0,0 +1,212 @@
+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 { 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 {
+ scrubAuthority?: boolean
+}
+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) => {
+ expect(scrubUrl(ctxOf(c.allow), c.input, { scrubAuthority: c.scrubAuthority }).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)
+ })
+ })
+
+ 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)
+ }
+ })
+
+ // 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('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/kafka/types.ts b/nodejs/src/ingestion/pipelines/sessionreplay/kafka/types.ts
index 438cd471c036..9b8c72af6b2a 100644
--- a/nodejs/src/ingestion/pipelines/sessionreplay/kafka/types.ts
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/kafka/types.ts
@@ -53,6 +53,28 @@ export const EventSchema = z.object({
properties: EventPropertiesSchema,
})
+// Ready-to-write JSONL lines plus per-event metadata from the native anonymizer.
+
+// Per-event flag bits, mirroring `rust/replay-anonymizer-node/src/snapshot.rs` (EVENT_FLAG_*).
+export const PRE_SERIALIZED_FLAG_ACTIVE = 1
+export const PRE_SERIALIZED_FLAG_CLICK = 2
+export const PRE_SERIALIZED_FLAG_KEYPRESS = 4
+export const PRE_SERIALIZED_FLAG_MOUSE_ACTIVITY = 8
+
+export const PreSerializedEventMetaSchema = z.object({
+ ts: z.number(),
+ flags: z.number(),
+ href: z.string().optional(),
+})
+
+export const PreSerializedEventsSchema = z.object({
+ lines: z.instanceof(Buffer),
+ events: z.array(PreSerializedEventMetaSchema),
+ consoleLogCount: z.number(),
+ consoleWarnCount: z.number(),
+ consoleErrorCount: z.number(),
+})
+
export const ParsedMessageDataSchema = z.object({
distinct_id: z.string(),
session_id: z.string(),
@@ -62,8 +84,11 @@ export const ParsedMessageDataSchema = z.object({
snapshot_source: z.string().nullable(),
snapshot_library: z.string().nullable(),
metadata: MessageMetadataSchema,
+ preSerialized: PreSerializedEventsSchema.optional(),
})
export type Event = z.infer<typeof EventSchema>
export type SnapshotEvent = z.infer<typeof SnapshotEventSchema>
+export type PreSerializedEventMeta = z.infer<typeof PreSerializedEventMetaSchema>
+export type PreSerializedEvents = z.infer<typeof PreSerializedEventsSchema>
export type ParsedMessageData = z.infer<typeof ParsedMessageDataSchema>
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/metrics.ts b/nodejs/src/ingestion/pipelines/sessionreplay/metrics.ts
index 2743eadc8202..dc5fbcd78bca 100644
--- a/nodejs/src/ingestion/pipelines/sessionreplay/metrics.ts
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/metrics.ts
@@ -2,6 +2,11 @@ import { Counter, Gauge, Histogram, Summary } from 'prom-client'
const BUCKETS_KB_WRITTEN = [0, 128, 512, 1024, 5120, 10240, 20480, 51200, 102400, 204800, Infinity]
+/** Which anonymizer produced the output; the label makes the flag rollout a direct A/B. */
+export type MlAnonymizeImpl = 'rust' | 'ts'
+/** Rust engine that produced the output (tree = the parse fallback fired). `''` when not applicable. */
+export type MlAnonymizeRoute = 'stream' | 'tree' | ''
+
export class SessionRecordingIngesterMetrics {
private static readonly sessionsHandled = new Gauge({
name: 'recording_blob_ingestion_v2_session_manager_count',
@@ -53,6 +58,19 @@ export class SessionRecordingIngesterMetrics {
labelNames: ['content_encoding'],
})
+ private static readonly mlAnonymizeDuration = new Histogram({
+ name: 'recording_blob_ingestion_v2_ml_anonymize_duration_ms',
+ help: 'Per-message ML mirror anonymize time in ms, by implementation and route',
+ labelNames: ['impl', 'route'],
+ buckets: [0, 1, 2, 5, 10, 25, 50, 100, 250, 500, 1000, 2500, 5000, 10000, Infinity],
+ })
+
+ private static readonly mlAnonymizeFailed = new Counter({
+ name: 'recording_blob_ingestion_v2_ml_anonymize_failed',
+ help: 'Messages dropped because ML mirror anonymization failed (fail-closed), by implementation',
+ labelNames: ['impl'],
+ })
+
public static incrementMessageReceived(partition: number): void {
this.messageReceived.labels(partition.toString()).inc()
}
@@ -88,4 +106,12 @@ export class SessionRecordingIngesterMetrics {
public static observeKafkaBatchSizeKb(sizeKb: number): void {
this.kafkaBatchSizeKb.observe(sizeKb)
}
+
+ public static observeMlAnonymizeDuration(impl: MlAnonymizeImpl, ms: number, route: MlAnonymizeRoute = ''): void {
+ this.mlAnonymizeDuration.labels(impl, route).observe(ms)
+ }
+
+ public static incrementMlAnonymizeFailed(impl: MlAnonymizeImpl): void {
+ this.mlAnonymizeFailed.labels(impl).inc()
+ }
}
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/config.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/config.ts
index 3d7bcc833856..bdb78883a1bc 100644
--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/config.ts
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/config.ts
@@ -36,6 +36,8 @@ 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`); off → the TS scrubbers. */
+ SESSION_RECORDING_ML_RUST_ANONYMIZER: boolean
}
export function getDefaultMlMirrorConfig(): MlMirrorConfig {
@@ -61,5 +63,6 @@ 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: false,
}
}
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 d466ef99665c..e2eda3170579 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
@@ -15,6 +15,7 @@ import {
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 { createRecordSessionEventStep } from '~/ingestion/pipelines/sessionreplay/record-session-event-step'
import { createResolveRetentionStep } from '~/ingestion/pipelines/sessionreplay/session-batch-resolve-retention-step'
@@ -87,41 +88,50 @@ export function createMlMirrorReplayPipeline(
b
.teamAware((b) =>
b
- .sequentially((b) =>
- b
- .pipe(
- topHogWrapper(createParseMessageStep(), [
- timer('parse_time_ms_by_session_id', (input) => ({
- token: input.headers.token ?? 'unknown',
- session_id: input.headers.session_id ?? 'unknown',
- })),
- ])
- )
- // Anonymize before recording so derived metadata is scrubbed too.
- .pipe(createAnonymizeStep({ scrubContext }))
- .pipe(
- topHogWrapper(
- createRecordSessionEventStep({
- sessionBatchManager,
- isDebugLoggingEnabled,
- }),
- [
- sum(
- 'message_size_by_session_id',
- (input) => ({
- token: input.parsedMessage.token ?? 'unknown',
- session_id: input.parsedMessage.session_id,
- }),
- (input) => input.parsedMessage.metadata.rawSize
- ),
- timer('consume_time_ms_by_session_id', (input) => ({
+ .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 }))
+ return parsed.pipe(
+ topHogWrapper(
+ createRecordSessionEventStep({
+ sessionBatchManager,
+ isDebugLoggingEnabled,
+ }),
+ [
+ sum(
+ 'message_size_by_session_id',
+ (input) => ({
token: input.parsedMessage.token ?? 'unknown',
session_id: input.parsedMessage.session_id,
- })),
- ]
- )
+ }),
+ (input) => input.parsedMessage.metadata.rawSize
+ ),
+ timer('consume_time_ms_by_session_id', (input) => ({
+ token: input.parsedMessage.token ?? 'unknown',
+ session_id: input.parsedMessage.session_id,
+ })),
+ ]
)
- )
+ )
+ })
.gather()
)
.handleIngestionWarnings(outputs)
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/parse-and-anonymize-step.test.ts b/nodejs/src/ingestion/pipelines/sessionreplay/parse-and-anonymize-step.test.ts
new file mode 100644
index 000000000000..57068bdc2144
--- /dev/null
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/parse-and-anonymize-step.test.ts
@@ -0,0 +1,162 @@
+import { Message } from 'node-rdkafka'
+import { promisify } from 'node:util'
+import { gzip } from 'zlib'
+
+import { PipelineResultType } from '~/ingestion/framework/results'
+
+import { createParseAndAnonymizeMessageStep } from './parse-and-anonymize-step'
+import { SessionReplayHeaders } from './validate-headers-step'
+
+const compressWithGzip = promisify(gzip)
+
+// The native addon is the mocked boundary: these tests pin the TS side of the fused step — failure
+// classification (dlq vs drop), the timestamp window, header/body agreement, and the ParsedMessageData
+// assembly — not the scrub itself (that's covered by the Rust suite + shared fixtures).
+const mockAnonymizeKafkaPayload = jest.fn()
+jest.mock('@posthog/replay-anonymizer', () => ({
+ anonymizeKafkaPayload: (payload: Buffer, contentEncoding?: string | null) =>
+ mockAnonymizeKafkaPayload(payload, contentEncoding),
+}))
+
+describe('createParseAndAnonymizeMessageStep', () => {
+ const step = createParseAndAnonymizeMessageStep()
+ const now = Date.now()
+
+ const headers: SessionReplayHeaders = {
+ token: 'token-1',
+ distinct_id: 'user-1',
+ session_id: 'session-1',
+ } as SessionReplayHeaders
+
+ function kafkaMessage(value: Buffer | null = Buffer.from('{}')): Message {
+ return {
+ value,
+ timestamp: now,
+ partition: 3,
+ topic: 'snapshots',
+ offset: 42,
+ size: value?.length ?? 0,
+ } as Message
+ }
+
+ function addonSuccess(metaOverrides: Record<string, unknown> = {}): void {
+ mockAnonymizeKafkaPayload.mockResolvedValue({
+ failed: false,
+ reason: null,
+ error: null,
+ lines: Buffer.from('["window-1",{"type":3,"timestamp":' + now + '}]\n'),
+ meta: JSON.stringify({
+ distinctId: 'user-1',
+ sessionId: 'session-1',
+ windowId: 'window-1',
+ snapshotSource: 'web',
+ snapshotLibrary: 'posthog-js',
+ startTs: now,
+ endTs: now + 1000,
+ consoleLogCount: 1,
+ consoleWarnCount: 2,
+ consoleErrorCount: 3,
+ events: [{ ts: now, flags: 5 }],
+ ...metaOverrides,
+ }),
+ })
+ }
+
+ beforeEach(() => {
+ mockAnonymizeKafkaPayload.mockReset()
+ })
+
+ it('assembles a pre-serialized ParsedMessageData from the addon output', async () => {
+ addonSuccess()
+ const result = await step({ message: kafkaMessage(), headers })
+
+ expect(result.type).toBe(PipelineResultType.OK)
+ const parsed = (result as any).value.parsedMessage
+ expect(parsed.session_id).toBe('session-1')
+ expect(parsed.distinct_id).toBe('user-1')
+ expect(parsed.token).toBe('token-1')
+ expect(parsed.eventsByWindowId).toEqual({})
+ expect(parsed.preSerialized.lines.toString()).toContain('"window-1"')
+ expect(parsed.preSerialized.events).toEqual([{ ts: now, flags: 5 }])
+ expect(parsed.preSerialized.consoleWarnCount).toBe(2)
+ expect(parsed.eventsRange.start.toMillis()).toBe(now)
+ expect(parsed.eventsRange.end.toMillis()).toBe(now + 1000)
+ expect(parsed.snapshot_source).toBe('web')
+ expect(parsed.snapshot_library).toBe('posthog-js')
+ expect(parsed.metadata).toEqual({ partition: 3, topic: 'snapshots', rawSize: 2, offset: 42, timestamp: now })
+ })
+
+ it('normalizes a UUID session id before comparing against the header', async () => {
+ const upper = '019539D9-6B23-7E26-B0E3-3C8D3E2AD068'
+ addonSuccess({ sessionId: upper })
+ const result = await step({
+ message: kafkaMessage(),
+ headers: { ...headers, session_id: upper.toLowerCase() },
+ })
+ expect(result.type).toBe(PipelineResultType.OK)
+ expect((result as any).value.parsedMessage.session_id).toBe(upper.toLowerCase())
+ })
+
+ it('hands the addon the raw bytes and content encoding (decompression lives in Rust)', async () => {
+ addonSuccess()
+ const raw = Buffer.from(JSON.stringify({ distinct_id: 'user-1', data: '{}' }))
+ const zipped = await compressWithGzip(raw)
+ await step({ message: kafkaMessage(zipped), headers })
+ expect(mockAnonymizeKafkaPayload).toHaveBeenCalledWith(zipped, null)
+
+ mockAnonymizeKafkaPayload.mockClear()
+ addonSuccess()
+ const lz4Message = kafkaMessage(raw)
+ lz4Message.headers = [{ 'content-encoding': Buffer.from('lz4') }]
+ await step({ message: lz4Message, headers })
+ expect(mockAnonymizeKafkaPayload).toHaveBeenCalledWith(raw, 'lz4')
+ })
+
+ test.each([
+ ['invalid_compressed_data', PipelineResultType.DLQ],
+ ['invalid_json', PipelineResultType.DLQ],
+ ['invalid_message_payload', PipelineResultType.DLQ],
+ ['received_non_snapshot_message', PipelineResultType.DLQ],
+ ['message_contained_no_valid_rrweb_events', PipelineResultType.DROP],
+ ['anonymize_failed', PipelineResultType.DROP],
+ ])('maps the addon failure reason %s to %s', async (reason, expectedType) => {
+ mockAnonymizeKafkaPayload.mockResolvedValue({
+ failed: true,
+ reason,
+ error: 'detail',
+ lines: null,
+ meta: null,
+ })
+ const result = await step({ message: kafkaMessage(), headers })
+ expect(result.type).toBe(expectedType)
+ expect((result as any).reason).toBe(reason)
+ })
+
+ it('fails closed when the addon promise rejects', async () => {
+ mockAnonymizeKafkaPayload.mockRejectedValue(new Error('native panic'))
+ const result = await step({ message: kafkaMessage(), headers })
+ expect(result).toMatchObject({ type: PipelineResultType.DROP, reason: 'anonymize_failed' })
+ })
+
+ it('drops messages whose timestamps are too far from now', async () => {
+ const monthAgo = now - 30 * 24 * 60 * 60 * 1000
+ addonSuccess({ startTs: monthAgo, endTs: monthAgo + 1000 })
+ const result = await step({ message: kafkaMessage(), headers })
+ expect(result).toMatchObject({ type: PipelineResultType.DROP, reason: 'message_timestamp_diff_too_large' })
+ })
+
+ test.each([
+ ['session_id', { sessionId: 'other-session' }, 'session_id_header_body_mismatch'],
+ ['distinct_id', { distinctId: 'other-user' }, 'distinct_id_header_body_mismatch'],
+ ])('dlqs on a %s header/body mismatch', async (_field, metaOverrides, reason) => {
+ addonSuccess(metaOverrides)
+ const result = await step({ message: kafkaMessage(), headers })
+ expect(result).toMatchObject({ type: PipelineResultType.DLQ, reason })
+ })
+
+ it('dlqs when the message value is empty', async () => {
+ const result = await step({ message: kafkaMessage(null), headers })
+ expect(result).toMatchObject({ type: PipelineResultType.DLQ, reason: 'message_value_or_timestamp_is_empty' })
+ expect(mockAnonymizeKafkaPayload).not.toHaveBeenCalled()
+ })
+})
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/parse-and-anonymize-step.ts b/nodejs/src/ingestion/pipelines/sessionreplay/parse-and-anonymize-step.ts
new file mode 100644
index 000000000000..e1663a1a6b62
--- /dev/null
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/parse-and-anonymize-step.ts
@@ -0,0 +1,171 @@
+import { DateTime } from 'luxon'
+
+import type { AnonymizeMeta } from '@posthog/replay-anonymizer'
+
+import { parseJSON } from '~/common/utils/json-parse'
+import { logger } from '~/common/utils/logger'
+import { normalizeSessionId } from '~/common/utils/utils'
+import { dlq, drop, ok } from '~/ingestion/framework/results'
+import { ProcessingStep } from '~/ingestion/framework/steps'
+import { ParsedMessageData } from '~/ingestion/pipelines/sessionreplay/kafka/types'
+import { SessionRecordingIngesterMetrics } from '~/ingestion/pipelines/sessionreplay/metrics'
+
+import { ParseMessageStepInput, ParseMessageStepOutput, getContentEncoding, isGzipped } from './parse-message-step'
+
+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
+// missing addon only breaks the native path, not every import of this module).
+type RustAnonymizer = typeof import('@posthog/replay-anonymizer')
+let rustAnonymizer: RustAnonymizer | undefined
+function getRustAnonymizer(): RustAnonymizer {
+ if (!rustAnonymizer) {
+ rustAnonymizer = require('@posthog/replay-anonymizer') as RustAnonymizer
+ }
+ return rustAnonymizer
+}
+
+// Addon failure reasons that map to a DLQ (mirroring the TS parse step's classifications).
+const DLQ_REASONS = new Set([
+ 'invalid_compressed_data',
+ 'invalid_json',
+ 'invalid_message_payload',
+ 'received_non_snapshot_message',
+])
+
+/**
+ * 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.
+ *
+ * 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
+ * ingestion warnings are unchanged.
+ */
+export function createParseAndAnonymizeMessageStep<T extends ParseMessageStepInput>(): ProcessingStep<
+ T,
+ T & ParseMessageStepOutput
+> {
+ return async function parseAndAnonymizeMessageStep(input) {
+ const { message, headers } = input
+
+ if (!message.value || !message.timestamp) {
+ return dlq('message_value_or_timestamp_is_empty')
+ }
+
+ // Decompression happens inside the addon, off the event loop (gunzipSync here would block
+ // it); the encoding metric only needs the header and the magic bytes.
+ const contentEncoding = getContentEncoding(message.headers)
+ SessionRecordingIngesterMetrics.incrementMessagesByEncoding(
+ contentEncoding ?? (isGzipped(message.value) ? 'gzip' : 'none')
+ )
+
+ const t0 = performance.now()
+ let result
+ try {
+ result = await getRustAnonymizer().anonymizeKafkaPayload(message.value, contentEncoding)
+ } catch (error) {
+ // A rejected promise (native panic, addon load failure) must fail closed.
+ logger.warn('🙈', 'anonymize_event_failed', { error: String(error) })
+ SessionRecordingIngesterMetrics.incrementMlAnonymizeFailed('rust')
+ return drop('anonymize_failed')
+ }
+ SessionRecordingIngesterMetrics.observeMlAnonymizeDuration('rust', performance.now() - t0, result.route ?? '')
+
+ if (result.failed) {
+ if (result.reason && DLQ_REASONS.has(result.reason)) {
+ return dlq(result.reason, new Error(result.error ?? result.reason))
+ }
+ if (result.reason === 'message_contained_no_valid_rrweb_events') {
+ return drop(
+ 'message_contained_no_valid_rrweb_events',
+ [],
+ [
+ {
+ type: 'message_contained_no_valid_rrweb_events',
+ details: {},
+ },
+ ]
+ )
+ }
+ // anonymize_failed (or anything unclassified): fail closed.
+ logger.warn('🙈', 'anonymize_event_failed', { error: result.error ?? 'rust anonymizer failed' })
+ SessionRecordingIngesterMetrics.incrementMlAnonymizeFailed('rust')
+ return drop('anonymize_failed')
+ }
+
+ let meta: AnonymizeMeta
+ try {
+ meta = parseJSON(result.meta!) as AnonymizeMeta
+ } catch (error) {
+ // Fail closed: an uncaught throw here poisons the pipeline instead of dropping one message.
+ logger.warn('🙈', 'anonymize_event_failed', { error: String(error) })
+ SessionRecordingIngesterMetrics.incrementMlAnonymizeFailed('rust')
+ return drop('anonymize_failed')
+ }
+
+ const startDateTime = DateTime.fromMillis(meta.startTs)
+ const endDateTime = DateTime.fromMillis(meta.endTs)
+ const startDiff = Math.abs(startDateTime.diffNow('day').days)
+ const endDiff = Math.abs(endDateTime.diffNow('day').days)
+ if (startDiff >= MESSAGE_TIMESTAMP_DIFF_THRESHOLD_DAYS || endDiff >= MESSAGE_TIMESTAMP_DIFF_THRESHOLD_DAYS) {
+ return drop(
+ 'message_timestamp_diff_too_large',
+ [],
+ [
+ {
+ type: 'message_timestamp_diff_too_large',
+ details: {
+ startDiffDays: startDiff,
+ endDiffDays: endDiff,
+ thresholdDays: MESSAGE_TIMESTAMP_DIFF_THRESHOLD_DAYS,
+ },
+ },
+ ]
+ )
+ }
+
+ const sessionId = normalizeSessionId(meta.sessionId)
+
+ // session_id and distinct_id are carried both in the headers (set by capture) and in the
+ // message body; they must agree — a mismatch means the message is corrupt or mis-routed.
+ if (headers.session_id !== sessionId) {
+ return dlq('session_id_header_body_mismatch')
+ }
+ if (headers.distinct_id !== meta.distinctId) {
+ return dlq('distinct_id_header_body_mismatch')
+ }
+
+ const parsedMessage: ParsedMessageData = {
+ metadata: {
+ partition: message.partition,
+ topic: message.topic,
+ rawSize: message.size,
+ offset: message.offset,
+ timestamp: message.timestamp,
+ },
+ distinct_id: meta.distinctId,
+ session_id: sessionId,
+ token: headers.token,
+ // Events live in `preSerialized` — consumers use its lines + per-event metadata.
+ eventsByWindowId: {},
+ preSerialized: {
+ lines: result.lines!,
+ events: meta.events,
+ consoleLogCount: meta.consoleLogCount,
+ consoleWarnCount: meta.consoleWarnCount,
+ consoleErrorCount: meta.consoleErrorCount,
+ },
+ eventsRange: {
+ start: startDateTime,
+ end: endDateTime,
+ },
+ snapshot_source: meta.snapshotSource,
+ snapshot_library: meta.snapshotLibrary,
+ }
+
+ return ok({ ...input, parsedMessage })
+ }
+}
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/parse-message-step.test.ts b/nodejs/src/ingestion/pipelines/sessionreplay/parse-message-step.test.ts
index d64d9d7b8178..2c77f3a8a9d7 100644
--- a/nodejs/src/ingestion/pipelines/sessionreplay/parse-message-step.test.ts
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/parse-message-step.test.ts
@@ -4,7 +4,7 @@ import { gzip } from 'zlib'
import { PipelineResultType } from '~/ingestion/framework/results'
-import { ParseMessageStepInput, createParseMessageStep } from './parse-message-step'
+import { ParseMessageStepInput, createParseMessageStep, decompressMessageValue } from './parse-message-step'
import { SessionReplayHeaders } from './validate-headers-step'
const compressWithGzip = promisify(gzip)
@@ -593,4 +593,40 @@ describe('createParseMessageStep', () => {
expect(result.value.parsedMessage.session_id).toBe(expectedSessionId)
}
})
+
+ describe('decompressMessageValue lz4 hardening', () => {
+ const lz4 = require('lz4')
+
+ function lz4Message(value: Buffer): Message {
+ return {
+ value,
+ headers: [{ 'content-encoding': Buffer.from('lz4') }],
+ } as unknown as Message
+ }
+
+ function lz4Frame(payload: Buffer, claimedSize?: number): Buffer {
+ const compressed = Buffer.alloc(lz4.encodeBound(payload.length))
+ const n = lz4.encodeBlock(payload, compressed)
+ const prefix = Buffer.alloc(4)
+ prefix.writeUInt32LE(claimedSize ?? payload.length, 0)
+ return Buffer.concat([prefix, compressed.subarray(0, n)])
+ }
+
+ it('round-trips a valid block', () => {
+ const payload = Buffer.from('{"distinct_id":"d","data":"x"}'.repeat(10))
+ expect(decompressMessageValue(lz4Message(lz4Frame(payload)))).toEqual(payload)
+ })
+
+ it('rejects a size prefix beyond the decompression cap instead of allocating it', () => {
+ const payload = Buffer.from('small')
+ const bomb = lz4Frame(payload, 0xffffffff)
+ expect(() => decompressMessageValue(lz4Message(bomb))).toThrow(/exceeds/)
+ })
+
+ it('rejects a size prefix that does not match the decoded length', () => {
+ const payload = Buffer.from('0123456789'.repeat(20))
+ const lying = lz4Frame(payload, payload.length + 512)
+ expect(() => decompressMessageValue(lz4Message(lying))).toThrow(/decoded/)
+ })
+ })
})
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/parse-message-step.ts b/nodejs/src/ingestion/pipelines/sessionreplay/parse-message-step.ts
index abb40f391cd4..9a5447709147 100644
--- a/nodejs/src/ingestion/pipelines/sessionreplay/parse-message-step.ts
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/parse-message-step.ts
@@ -21,6 +21,9 @@ const lz4: { decodeBlock(input: Buffer, output: Buffer): number } = require('lz4
const MESSAGE_TIMESTAMP_DIFF_THRESHOLD_DAYS = 7
const GZIP_HEADER = Uint8Array.from([0x1f, 0x8b, 0x08, 0x00])
+// Compression-bomb cap (mirrors the Rust addon): ~6x the 10 MB largest payload in a production
+// sample; exceeding it DLQs instead of risking an unclassifiable OOM.
+const MAX_DECOMPRESSED_BYTES = 64 * 1024 * 1024
export interface ParseMessageStepInput {
message: Message
@@ -31,11 +34,11 @@ export interface ParseMessageStepOutput {
parsedMessage: ParsedMessageData
}
-function isGzipped(buffer: Buffer): boolean {
+export function isGzipped(buffer: Buffer): boolean {
return buffer.subarray(0, GZIP_HEADER.length).equals(GZIP_HEADER)
}
-function getContentEncoding(headers: MessageHeader[] | undefined): string | null {
+export function getContentEncoding(headers: MessageHeader[] | undefined): string | null {
if (!headers) {
return null
}
@@ -48,6 +51,34 @@ function getContentEncoding(headers: MessageHeader[] | undefined): string | null
return null
}
+/**
+ * Decompress a Kafka message's value (lz4 via the content-encoding header, gzip via its magic bytes,
+ * else as-is) and record the encoding metric. Throws on corrupt compressed data — callers dlq with
+ * `invalid_compressed_data`. Shared by the parse step and the fused native parse+anonymize step.
+ */
+export function decompressMessageValue(message: Message): Buffer {
+ const value = message.value!
+ const contentEncoding = getContentEncoding(message.headers)
+ let messageUnzipped = value
+ if (contentEncoding === 'lz4') {
+ const uncompressedSize = value.readUInt32LE(0)
+ if (uncompressedSize > MAX_DECOMPRESSED_BYTES) {
+ throw new Error(`lz4 uncompressed size ${uncompressedSize} exceeds the decompression cap`)
+ }
+ const output = Buffer.allocUnsafe(uncompressedSize)
+ const decodedLength = lz4.decodeBlock(value.subarray(4), output)
+ // Without this check an inflated prefix leaks the uninitialized tail of `output`.
+ if (decodedLength !== uncompressedSize) {
+ throw new Error(`lz4 decoded ${decodedLength} bytes but the size prefix claimed ${uncompressedSize}`)
+ }
+ messageUnzipped = output
+ } else if (isGzipped(value)) {
+ messageUnzipped = gunzipSync(value, { maxOutputLength: MAX_DECOMPRESSED_BYTES })
+ }
+ SessionRecordingIngesterMetrics.incrementMessagesByEncoding(contentEncoding ?? (isGzipped(value) ? 'gzip' : 'none'))
+ return messageUnzipped
+}
+
function getValidEvents(events: unknown[]): {
validEvents: SnapshotEvent[]
startDateTime: DateTime
@@ -107,23 +138,12 @@ export function createParseMessageStep<T extends ParseMessageStepInput>(): Proce
return dlq('message_value_or_timestamp_is_empty')
}
- let messageUnzipped = message.value
- const contentEncoding = getContentEncoding(message.headers)
+ let messageUnzipped: Buffer
try {
- if (contentEncoding === 'lz4') {
- const uncompressedSize = message.value.readUInt32LE(0)
- const output = Buffer.allocUnsafe(uncompressedSize)
- lz4.decodeBlock(message.value.subarray(4), output)
- messageUnzipped = output
- } else if (isGzipped(message.value)) {
- messageUnzipped = gunzipSync(message.value)
- }
+ messageUnzipped = decompressMessageValue(message)
} catch (error) {
return dlq('invalid_compressed_data', error)
}
- SessionRecordingIngesterMetrics.incrementMessagesByEncoding(
- contentEncoding ?? (isGzipped(message.value) ? 'gzip' : 'none')
- )
let rawPayload: unknown
try {
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/sessions/session-batch-recorder.test.ts b/nodejs/src/ingestion/pipelines/sessionreplay/sessions/session-batch-recorder.test.ts
index 914cfea05905..6b2dc8687a29 100644
--- a/nodejs/src/ingestion/pipelines/sessionreplay/sessions/session-batch-recorder.test.ts
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/sessions/session-batch-recorder.test.ts
@@ -16,6 +16,7 @@ import { SessionBatchFileStorage, SessionBatchFileWriter } from './session-batch
import { SessionBatchRecorder } from './session-batch-recorder'
import { SessionConsoleLogRecorder } from './session-console-log-recorder'
import { SessionConsoleLogStore } from './session-console-log-store'
+import { SessionFeatureRecorder } from './session-feature-recorder'
import { SessionFilter } from './session-filter'
import { SessionTracker } from './session-tracker'
import { EndResult, SnappySessionRecorder } from './snappy-session-recorder'
@@ -347,6 +348,23 @@ describe('SessionBatchRecorder', () => {
})
describe('recording and writing', () => {
+ it('skips the feature recorder for pre-serialized (native-anonymizer) messages', async () => {
+ // The feature recorder throws on pre-serialized input; calling it per message would
+ // spam Sentry and stop feature blocks. The call site must skip it instead.
+ const message = createMessage('session1', [])
+ message.message.eventsByWindowId = {}
+ message.message.preSerialized = {
+ lines: Buffer.from('["window1",{"type":3,"timestamp":1000}]\n'),
+ events: [{ ts: 1000, flags: 0 }],
+ consoleLogCount: 0,
+ consoleWarnCount: 0,
+ consoleErrorCount: 0,
+ }
+ await record(message)
+ const featureRecorder = jest.mocked(SessionFeatureRecorder).mock.results[0].value
+ expect(featureRecorder.recordMessage).not.toHaveBeenCalled()
+ })
+
it('should write events in correct format', async () => {
const message = createMessage('session1', [
{
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/sessions/session-batch-recorder.ts b/nodejs/src/ingestion/pipelines/sessionreplay/sessions/session-batch-recorder.ts
index 8ea340a9a31b..d834cdab7466 100644
--- a/nodejs/src/ingestion/pipelines/sessionreplay/sessions/session-batch-recorder.ts
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/sessions/session-batch-recorder.ts
@@ -224,17 +224,21 @@ export class SessionBatchRecorder {
const { sessionBlockRecorder, consoleLogRecorder, featureRecorder } = this.sessions.get(teamId, sessionId)!
const bytesWritten = sessionBlockRecorder.recordMessage(message.message)
await consoleLogRecorder.recordMessage(message)
- try {
- featureRecorder.recordMessage(message.message)
- } catch (e) {
- logger.warn('🔁', 'session_feature_recorder_error', {
- error: String(e),
- sessionId,
- teamId,
- partition,
- batchId: this.batchId,
- })
- captureException(e, { tags: { sessionId, teamId: String(teamId), partition: String(partition) } })
+ // Features derive from `eventsByWindowId`, which is empty on native-anonymizer messages —
+ // skip the recorder (which throws on pre-serialized input) rather than catch it per message.
+ if (!message.message.preSerialized) {
+ try {
+ featureRecorder.recordMessage(message.message)
+ } catch (e) {
+ logger.warn('🔁', 'session_feature_recorder_error', {
+ error: String(e),
+ sessionId,
+ teamId,
+ partition,
+ batchId: this.batchId,
+ })
+ captureException(e, { tags: { sessionId, teamId: String(teamId), partition: String(partition) } })
+ }
}
const currentPartitionSize = this.partitionSizes.get(partition)!
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/sessions/session-console-log-recorder.test.ts b/nodejs/src/ingestion/pipelines/sessionreplay/sessions/session-console-log-recorder.test.ts
index e1ff051c1e55..fe6d232bc825 100644
--- a/nodejs/src/ingestion/pipelines/sessionreplay/sessions/session-console-log-recorder.test.ts
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/sessions/session-console-log-recorder.test.ts
@@ -73,6 +73,25 @@ describe('SessionConsoleLogRecorder', () => {
})
describe('Console log counting', () => {
+ it('uses the metadata counts for pre-serialized messages without storing entries', async () => {
+ const message = createMessage('window1', [])
+ message.message.eventsByWindowId = {}
+ message.message.preSerialized = {
+ lines: Buffer.from(''),
+ events: [],
+ consoleLogCount: 2,
+ consoleWarnCount: 1,
+ consoleErrorCount: 3,
+ }
+
+ await recorder.recordMessage(message)
+ const result = recorder.end()
+
+ expect(result).toEqual({ consoleLogCount: 2, consoleWarnCount: 1, consoleErrorCount: 3 })
+ // The ml-mirror console-log store is disabled; the counts only feed block metadata.
+ expect(mockConsoleLogStore.storeSessionConsoleLogs).not.toHaveBeenCalled()
+ })
+
it('should count console log events', async () => {
const events = [
createConsoleLogEvent({
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/sessions/session-console-log-recorder.ts b/nodejs/src/ingestion/pipelines/sessionreplay/sessions/session-console-log-recorder.ts
index 13a957d4dcb4..5f2ccb607ead 100644
--- a/nodejs/src/ingestion/pipelines/sessionreplay/sessions/session-console-log-recorder.ts
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/sessions/session-console-log-recorder.ts
@@ -98,6 +98,17 @@ export class SessionConsoleLogRecorder {
return
}
+ // Pre-serialized messages (native ml-mirror anonymizer) carry level counts in their metadata;
+ // no log entries are collected for storage — the ml-mirror console-log store is disabled, the
+ // counts only feed the block metadata.
+ if (message.message.preSerialized) {
+ const { consoleLogCount, consoleWarnCount, consoleErrorCount } = message.message.preSerialized
+ this.consoleLogCount += consoleLogCount
+ this.consoleWarnCount += consoleWarnCount
+ this.consoleErrorCount += consoleErrorCount
+ return
+ }
+
const logsToStore: ConsoleLogEntry[] = []
for (const events of Object.values(message.message.eventsByWindowId)) {
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/sessions/session-feature-recorder.ts b/nodejs/src/ingestion/pipelines/sessionreplay/sessions/session-feature-recorder.ts
index b2097dffbe0c..6c862951f17d 100644
--- a/nodejs/src/ingestion/pipelines/sessionreplay/sessions/session-feature-recorder.ts
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/sessions/session-feature-recorder.ts
@@ -353,6 +353,12 @@ export class SessionFeatureRecorder {
throw new Error('Cannot record message after end() has been called')
}
+ // `eventsByWindowId` is empty on pre-serialized messages, so this would silently emit
+ // zeroed feature blocks; the native path must keep features off.
+ if (message.preSerialized) {
+ throw new Error('SessionFeatureRecorder cannot process pre-serialized messages')
+ }
+
if (!this._distinctId) {
this._distinctId = message.distinct_id
}
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/sessions/session-rate-limiter.test.ts b/nodejs/src/ingestion/pipelines/sessionreplay/sessions/session-rate-limiter.test.ts
index 8d9c6cc4feab..50c7a9b31662 100644
--- a/nodejs/src/ingestion/pipelines/sessionreplay/sessions/session-rate-limiter.test.ts
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/sessions/session-rate-limiter.test.ts
@@ -32,6 +32,27 @@ describe('SessionRateLimiter', () => {
expect(limiter.getEventCount(...session)).toBe(3)
})
+ it('counts pre-serialized events against the limit', () => {
+ // Pre-serialized messages have an empty eventsByWindowId; the count must come from the
+ // per-event metadata or rate limiting silently stops applying on the native path.
+ const limiter = new SessionRateLimiter(3)
+ const session: [number, string] = [123, 'session456']
+ const preSerialized = {
+ eventsByWindowId: {},
+ preSerialized: {
+ lines: Buffer.from(''),
+ events: [
+ { ts: 1, flags: 0 },
+ { ts: 2, flags: 0 },
+ ],
+ },
+ } as any as ParsedMessageData
+
+ expect(limiter.handleMessage(...session, 1, preSerialized)).toBe(true)
+ expect(limiter.getEventCount(...session)).toBe(2)
+ expect(limiter.handleMessage(...session, 1, preSerialized)).toBe(false)
+ })
+
it('should block messages after limit is exceeded', () => {
const limiter = new SessionRateLimiter(2)
const session: [number, string] = [123, 'session456']
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/sessions/session-rate-limiter.ts b/nodejs/src/ingestion/pipelines/sessionreplay/sessions/session-rate-limiter.ts
index 5c00861c986c..61fa6f0578b8 100644
--- a/nodejs/src/ingestion/pipelines/sessionreplay/sessions/session-rate-limiter.ts
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/sessions/session-rate-limiter.ts
@@ -26,8 +26,12 @@ export class SessionRateLimiter {
// Count total events in the message across all windows
let eventCount = 0
- for (const events of Object.values(message.eventsByWindowId)) {
- eventCount += events.length
+ if (message.preSerialized) {
+ eventCount = message.preSerialized.events.length
+ } else {
+ for (const events of Object.values(message.eventsByWindowId)) {
+ eventCount += events.length
+ }
}
const newCount = (this.eventCounts.get(key) ?? 0) + eventCount
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/sessions/snappy-session-recorder.test.ts b/nodejs/src/ingestion/pipelines/sessionreplay/sessions/snappy-session-recorder.test.ts
index 451b4459741b..79fb8a2d6568 100644
--- a/nodejs/src/ingestion/pipelines/sessionreplay/sessions/snappy-session-recorder.test.ts
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/sessions/snappy-session-recorder.test.ts
@@ -1119,4 +1119,49 @@ describe('SnappySessionRecorder', () => {
expect(result.activeMilliseconds).toEqual(2000)
})
})
+
+ describe('Pre-serialized messages (native anonymizer fast path)', () => {
+ it('appends the block lines verbatim and derives counts from the per-event metadata', async () => {
+ // Flag bits mirror rust/replay-anonymizer-node `snapshot.rs`: 1=active 2=click 4=keypress 8=mouse.
+ const t0 = DateTime.fromISO('2025-01-01T01:00:00Z').toMillis()
+ const lines = Buffer.from(
+ `["w1",{"type":4,"timestamp":${t0},"data":{"href":"https://example.com/[redacted]"}}]\n` +
+ `["w1",{"type":3,"timestamp":${t0 + 1000},"data":{"source":2,"type":2}}]\n` +
+ `["w1",{"type":3,"timestamp":${t0 + 2000},"data":{"source":5,"text":"****"}}]\n`
+ )
+ const message: ParsedMessageData = {
+ ...createMessage('w1', []),
+ eventsByWindowId: {},
+ eventsRange: { start: DateTime.fromMillis(t0), end: DateTime.fromMillis(t0 + 2000) },
+ preSerialized: {
+ lines,
+ events: [
+ { ts: t0, flags: 0, href: 'https://example.com/[redacted]' },
+ { ts: t0 + 1000, flags: 1 | 2 | 8 }, // click: active + click + mouse
+ { ts: t0 + 2000, flags: 1 | 4 }, // input: active + keypress
+ ],
+ consoleLogCount: 0,
+ consoleWarnCount: 0,
+ consoleErrorCount: 0,
+ },
+ }
+
+ const rawBytesWritten = recorder.recordMessage(message)
+ expect(rawBytesWritten).toBe(lines.length)
+
+ const result = await recorder.end()
+ expect(await readSnappyBuffer(result.buffer)).toBe(lines.toString())
+ expect(result.eventCount).toBe(3)
+ expect(result.clickCount).toBe(1)
+ expect(result.keypressCount).toBe(1)
+ expect(result.mouseActivityCount).toBe(1)
+ expect(result.firstUrl).toBe('https://example.com/[redacted]')
+ expect(result.urls).toEqual(['https://example.com/[redacted]'])
+ expect(result.size).toBe(lines.length)
+ // Two active events 1s apart, then activity times out: one 1000ms active segment.
+ expect(result.activeMilliseconds).toBe(1000)
+ expect(result.startDateTime.toMillis()).toBe(t0)
+ expect(result.endDateTime.toMillis()).toBe(t0 + 2000)
+ })
+ })
})
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/sessions/snappy-session-recorder.ts b/nodejs/src/ingestion/pipelines/sessionreplay/sessions/snappy-session-recorder.ts
index 2bf8c6dbbada..cf931c788985 100644
--- a/nodejs/src/ingestion/pipelines/sessionreplay/sessions/snappy-session-recorder.ts
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/sessions/snappy-session-recorder.ts
@@ -2,7 +2,13 @@ import { DateTime } from 'luxon'
import snappy from 'snappy'
import { logger } from '~/common/utils/logger'
-import { ParsedMessageData } from '~/ingestion/pipelines/sessionreplay/kafka/types'
+import {
+ PRE_SERIALIZED_FLAG_ACTIVE,
+ PRE_SERIALIZED_FLAG_CLICK,
+ PRE_SERIALIZED_FLAG_KEYPRESS,
+ PRE_SERIALIZED_FLAG_MOUSE_ACTIVITY,
+ ParsedMessageData,
+} from '~/ingestion/pipelines/sessionreplay/kafka/types'
import { hrefFrom, isClick, isKeypress, isMouseActivity } from '~/ingestion/pipelines/sessionreplay/rrweb-types'
import {
SegmentationEvent,
@@ -134,6 +140,10 @@ export class SnappySessionRecorder {
this.endDateTime = message.eventsRange.end
}
+ if (message.preSerialized) {
+ return this.recordPreSerialized(message)
+ }
+
for (const [windowId, events] of Object.entries(message.eventsByWindowId)) {
for (const event of events) {
const serializedLine = JSON.stringify([windowId, event]) + '\n'
@@ -170,6 +180,39 @@ export class SnappySessionRecorder {
return rawBytesWritten
}
+ /**
+ * Fast path for messages the native anonymizer already serialized: the JSONL block lines are
+ * appended as one chunk, and the counts/segmentation/urls come from the per-event metadata
+ * instead of walking parsed events.
+ */
+ private recordPreSerialized(message: ParsedMessageData): number {
+ const { lines, events } = message.preSerialized!
+
+ this.uncompressedChunks.push(lines)
+ for (const event of events) {
+ this.segmentationEvents.push({
+ timestamp: event.ts,
+ isActive: (event.flags & PRE_SERIALIZED_FLAG_ACTIVE) !== 0,
+ })
+ if (event.href) {
+ this.addUrl(event.href)
+ }
+ if (event.flags & PRE_SERIALIZED_FLAG_CLICK) {
+ this.clickCount += 1
+ }
+ if (event.flags & PRE_SERIALIZED_FLAG_KEYPRESS) {
+ this.keypressCount += 1
+ }
+ if (event.flags & PRE_SERIALIZED_FLAG_MOUSE_ACTIVITY) {
+ this.mouseActivityCount += 1
+ }
+ this.eventCount++
+ }
+ this.size += lines.length
+ this.messageCount += 1
+ return lines.length
+ }
+
private addUrl(url: string): void {
if (!url) {
return
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 ae2b2f86ae89..e9789b245374 100644
--- a/nodejs/src/servers/ingestion-session-replay-ml-mirror-server.ts
+++ b/nodejs/src/servers/ingestion-session-replay-ml-mirror-server.ts
@@ -5,6 +5,7 @@ import { defaultConfig, overrideConfigWithEnv } from '~/common/config/config'
import { KafkaProducerRegistry } from '~/common/outputs/kafka-producer-registry'
import { PostgresRouter } from '~/common/utils/db/postgres'
import { parseJSON } from '~/common/utils/json-parse'
+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'
@@ -63,6 +64,23 @@ export function buildMlMirrorServerConfig(
}
}
+/** Boot-time smoke test so a broken addon crashes startup instead of dropping all traffic later. */
+async function assertAnonymizerHealthy(anonymizer: typeof import('@posthog/replay-anonymizer')): Promise<void> {
+ const inner = JSON.stringify({
+ event: '$snapshot_items',
+ properties: {
+ $session_id: 's',
+ $window_id: 'w',
+ $snapshot_items: [{ type: 3, timestamp: Date.now(), data: { source: 5, id: 1, text: 'health check' } }],
+ },
+ })
+ const payload = Buffer.from(JSON.stringify({ distinct_id: 'd', data: inner }))
+ const result = await anonymizer.anonymizeKafkaPayload(payload)
+ if (result.failed) {
+ throw new Error(`replay-anonymizer startup self-test failed: ${result.reason ?? 'unknown'}`)
+ }
+}
+
export class IngestionSessionReplayMlMirrorServer implements NodeServer {
readonly lifecycle: ServerLifecycle
private config: IngestionSessionReplayMlMirrorServerConfig
@@ -110,9 +128,19 @@ export class IngestionSessionReplayMlMirrorServer implements NodeServer {
? new S3SessionBatchFileStorage(s3Client, bucket, prefix, this.config.SESSION_RECORDING_V2_S3_TIMEOUT_MS)
: new BlackholeSessionBatchFileStorage()
- const scrubContext: ScrubContext = {
- allow: await loadAllowLists(this.buildAllowListFetcher(s3Client, bucket)),
+ 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 }
// Block metadata is produced to Kafka; the dedicated Parquet-sink deployment writes it to the ML bucket.
const metadataStore = new MlBlockMetadataSink(outputs, pseudonymSecret)
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 4cc982c9d839..e17b9059f973 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -1484,6 +1484,9 @@ importers:
'@posthog/hogvm-node':
specifier: workspace:*
version: link:../rust/common/hogvm/node
+ '@posthog/replay-anonymizer':
+ specifier: workspace:*
+ version: link:../rust/replay-anonymizer-node
'@posthog/replay-headless':
specifier: workspace:*
version: link:../common/replay-headless
@@ -4405,6 +4408,18 @@ importers:
specifier: ^7.3.0
version: 7.3.0
+ rust/replay-anonymizer-node:
+ devDependencies:
+ '@types/node':
+ specifier: 22.15.17
+ version: 22.15.17
+ typescript:
+ specifier: 6.0.3
+ version: 6.0.3
+ undici-types:
+ specifier: ^7.3.0
+ version: 7.3.0
+
services/agent-proxy:
dependencies:
'@hono/node-server':
diff --git a/pnpm-workspace.yaml b/pnpm-workspace.yaml
index 6165aeb61d1e..b686d1a2f2ac 100644
--- a/pnpm-workspace.yaml
+++ b/pnpm-workspace.yaml
@@ -26,6 +26,7 @@ packages:
- '!tools/hedgebox-dummy'
- rust/cyclotron-node
- rust/common/hogvm/node
+ - rust/replay-anonymizer-node
blockExoticSubdeps: true
trustPolicy: no-downgrade
diff --git a/rust/Cargo.lock b/rust/Cargo.lock
index 860cf3807382..6669d88fec54 100644
--- a/rust/Cargo.lock
+++ b/rust/Cargo.lock
@@ -1707,6 +1707,12 @@ version = "1.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1fd0f2584146f6f2ef48085050886acf353beff7305ebd1ae69500e27c67f64b"
+[[package]]
+name = "byteorder-lite"
+version = "0.1.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8f1fe948ff07f4bd06c30984e69f5b4899c516a3ef74f34df92a2df2ab535495"
+
[[package]]
name = "bytes"
version = "1.11.1"
@@ -2219,6 +2225,12 @@ dependencies = [
"uuid",
]
+[[package]]
+name = "color_quant"
+version = "1.1.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "3d7b894f5411737b7867f4827955924d7c254fc9f4d91a6aad6b097804b1018b"
+
[[package]]
name = "colorchoice"
version = "1.0.4"
@@ -3593,6 +3605,15 @@ version = "2.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "37909eebbb50d72f9059c3b6d82c0463f2ff062c9e95845c43a6c9c0355411be"
+[[package]]
+name = "fdeflate"
+version = "0.3.7"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1e6853b52649d4ac5c0bd02320cddc5ba956bdb407c4b75a2c6b75bf51500f8c"
+dependencies = [
+ "simd-adler32",
+]
+
[[package]]
name = "feature-flags"
version = "0.1.0"
@@ -3789,6 +3810,15 @@ dependencies = [
"zlib-rs",
]
+[[package]]
+name = "float-cmp"
+version = "0.10.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b09cf3155332e944990140d967ff5eceb70df778b34f77d8075db46e4704e6d8"
+dependencies = [
+ "num-traits",
+]
+
[[package]]
name = "flume"
version = "0.11.1"
@@ -4169,6 +4199,16 @@ dependencies = [
"wasip3",
]
+[[package]]
+name = "gif"
+version = "0.14.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ee8cfcc411d9adbbaba82fb72661cc1bcca13e8bba98b364e62b2dba8f960159"
+dependencies = [
+ "color_quant",
+ "weezl",
+]
+
[[package]]
name = "gimli"
version = "0.32.3"
@@ -4350,6 +4390,16 @@ dependencies = [
"zerocopy",
]
+[[package]]
+name = "halfbrown"
+version = "0.3.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "aa2c385c6df70fd180bbb673d93039dbd2cd34e41d782600bdf6e1ca7bce39aa"
+dependencies = [
+ "hashbrown 0.15.5",
+ "serde",
+]
+
[[package]]
name = "hashbrown"
version = "0.12.3"
@@ -5025,6 +5075,34 @@ version = "1.0.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cd62e6b5e86ea8eeeb8db1de02880a6abc01a397b2ebb64b5d74ac255318f5cb"
+[[package]]
+name = "image"
+version = "0.25.10"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "85ab80394333c02fe689eaf900ab500fbd0c2213da414687ebf995a65d5a6104"
+dependencies = [
+ "bytemuck",
+ "byteorder-lite",
+ "color_quant",
+ "gif",
+ "image-webp",
+ "moxcms",
+ "num-traits",
+ "png",
+ "zune-core",
+ "zune-jpeg",
+]
+
+[[package]]
+name = "image-webp"
+version = "0.2.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "525e9ff3e1a4be2fbea1fdf0e98686a6d98b4d8f937e1bf7402245af1909e8c3"
+dependencies = [
+ "byteorder-lite",
+ "quick-error 2.0.1",
+]
+
[[package]]
name = "indent_write"
version = "2.2.0"
@@ -5801,6 +5879,24 @@ version = "0.2.186"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "68ab91017fe16c622486840e4c83c9a37afeff978bd239b5293d61ece587de66"
+[[package]]
+name = "libdeflate-sys"
+version = "1.25.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "72753e0008ea87963d2f0770042d0df7abe51fafbb8dcaf618ac440f2f1fec0a"
+dependencies = [
+ "cc",
+]
+
+[[package]]
+name = "libdeflater"
+version = "1.25.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d1ee41cf6fb1bb6030dfb59ffb7bc01ab26aade44142084c87f0fc7a1658fe71"
+dependencies = [
+ "libdeflate-sys",
+]
+
[[package]]
name = "libflate"
version = "1.4.0"
@@ -6323,6 +6419,16 @@ dependencies = [
"uuid",
]
+[[package]]
+name = "moxcms"
+version = "0.8.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "bb85c154ba489f01b25c0d36ae69a87e4a1c73a72631fc6c0eb6dde34a73e44b"
+dependencies = [
+ "num-traits",
+ "pxfm",
+]
+
[[package]]
name = "msvc-demangler"
version = "0.11.0"
@@ -7687,6 +7793,19 @@ dependencies = [
"plotters-backend",
]
+[[package]]
+name = "png"
+version = "0.18.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "60769b8b31b2a9f263dae2776c37b1b28ae246943cf719eb6946a1db05128a61"
+dependencies = [
+ "bitflags 2.11.0",
+ "crc32fast",
+ "fdeflate",
+ "flate2",
+ "miniz_oxide",
+]
+
[[package]]
name = "polling"
version = "3.11.0"
@@ -8248,6 +8367,12 @@ dependencies = [
"pulldown-cmark",
]
+[[package]]
+name = "pxfm"
+version = "0.1.29"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e0c5ccf5294c6ccd63a74f1565028353830a9c2f5eb0c682c355c471726a6e3f"
+
[[package]]
name = "pyo3"
version = "0.22.6"
@@ -8383,6 +8508,12 @@ version = "1.2.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a1d01941d82fa2ab50be1e79e6714289dd7cde78eba4c074bc5a4374f650dfe0"
+[[package]]
+name = "quick-error"
+version = "2.0.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a993555f31e5a609f617c12db6250dedcac1b0a85076912c436e6fc9b2c8e6a3"
+
[[package]]
name = "quick-xml"
version = "0.26.0"
@@ -8785,6 +8916,25 @@ version = "0.1.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "51743d3e274e2b18df81c4dc6caf8a5b8e15dbe799e0dca05c7617380094e884"
+[[package]]
+name = "replay-anonymizer-node"
+version = "0.0.1"
+dependencies = [
+ "ahash 0.8.12",
+ "anyhow",
+ "base64 0.22.1",
+ "flate2",
+ "image",
+ "libdeflater",
+ "lz4",
+ "memchr",
+ "neon",
+ "serde",
+ "serde_json",
+ "simd-json",
+ "zstd",
+]
+
[[package]]
name = "reqwest"
version = "0.11.27"
@@ -9274,7 +9424,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cc6bf79ff24e648f6da1f8d1f011e9cac26491b619e6b9280f2b47f1774e6ee2"
dependencies = [
"fnv",
- "quick-error",
+ "quick-error 1.2.3",
"tempfile",
"wait-timeout",
]
@@ -9779,6 +9929,21 @@ version = "0.3.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e320a6c5ad31d271ad523dcf3ad13e2767ad8b1cb8f047f75a8aeaf8da139da2"
+[[package]]
+name = "simd-json"
+version = "0.15.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c962f626b54771990066e5435ec8331d1462576cd2d1e62f24076ae014f92112"
+dependencies = [
+ "getrandom 0.3.4",
+ "halfbrown",
+ "ref-cast",
+ "serde",
+ "serde_json",
+ "simdutf8",
+ "value-trait",
+]
+
[[package]]
name = "simd_cesu8"
version = "1.1.1"
@@ -11675,6 +11840,18 @@ version = "1.12.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7ba6f5989077681266825251a52748b8c1d8a4ad098cc37e440103d0ea717fc0"
+[[package]]
+name = "value-trait"
+version = "0.11.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "0508fce11ad19e0aab49ce20b6bec7f8f82902ded31df1c9fc61b90f0eb396b8"
+dependencies = [
+ "float-cmp",
+ "halfbrown",
+ "itoa",
+ "ryu",
+]
+
[[package]]
name = "vcpkg"
version = "0.2.15"
@@ -11938,6 +12115,12 @@ dependencies = [
"rustls-pki-types",
]
+[[package]]
+name = "weezl"
+version = "0.1.12"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a28ac98ddc8b9274cb41bb4d9d4d5c425b6020c50c46f25559911905610b4a88"
+
[[package]]
name = "which"
version = "4.4.2"
@@ -12566,6 +12749,21 @@ dependencies = [
"pkg-config",
]
+[[package]]
+name = "zune-core"
+version = "0.5.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "cb8a0807f7c01457d0379ba880ba6322660448ddebc890ce29bb64da71fb40f9"
+
+[[package]]
+name = "zune-jpeg"
+version = "0.5.15"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "27bc9d5b815bc103f142aa054f561d9187d191692ec7c2d1e2b4737f8dbd7296"
+dependencies = [
+ "zune-core",
+]
+
[[patch.unused]]
name = "js-source-scopes"
version = "0.6.0"
diff --git a/rust/Cargo.toml b/rust/Cargo.toml
index 7a9299d20b88..6aed93fb2fe5 100644
--- a/rust/Cargo.toml
+++ b/rust/Cargo.toml
@@ -38,6 +38,7 @@ members = [
"cyclotron-core",
"cyclotron-node",
"cyclotron-janitor",
+ "replay-anonymizer-node",
"cymbal",
"cymbal-proto",
"embedding-worker",
@@ -129,6 +130,7 @@ mockito = "1"
hyper = { version = "1.9.0", features = ["server", "http1", "http2"] }
hyper-util = { version = "0.1.20", features = ["server", "server-graceful", "tokio", "http1", "http2"] }
itoa = "1.0.15"
+libdeflater = "1"
lru = "0.12"
metrics = "0.22.0"
metrics-exporter-prometheus = "0.14.0"
@@ -172,6 +174,7 @@ tracing-opentelemetry = "0.23.0"
tracing-subscriber = { version = "0.3.23", features = ["env-filter", "json"] }
url = "2.5.0"
uuid = { version = "1.23.0", features = ["v4", "v5", "v7", "serde"] }
+zstd = "0.13"
neon = "1"
quick_cache = "0.6.21"
ahash = "0.8.11"
diff --git a/rust/replay-anonymizer-node/.gitignore b/rust/replay-anonymizer-node/.gitignore
new file mode 100644
index 000000000000..d15049d90e52
--- /dev/null
+++ b/rust/replay-anonymizer-node/.gitignore
@@ -0,0 +1,3 @@
+index.node
+cargo.log
+dist/
diff --git a/rust/replay-anonymizer-node/Cargo.toml b/rust/replay-anonymizer-node/Cargo.toml
new file mode 100644
index 000000000000..cedabf421d2f
--- /dev/null
+++ b/rust/replay-anonymizer-node/Cargo.toml
@@ -0,0 +1,33 @@
+[package]
+name = "replay-anonymizer-node"
+version = "0.0.1"
+edition = "2021"
+exclude = ["index.node"]
+publish = false
+
+[lib]
+# `cdylib` for the Neon `index.node` addon; `rlib` so `cargo test` can exercise the scrub logic.
+crate-type = ["cdylib", "rlib"]
+
+[dependencies]
+ahash = { workspace = true }
+anyhow = { workspace = true }
+base64 = { workspace = true }
+libdeflater = { workspace = true }
+lz4 = { workspace = true }
+memchr = "2"
+image = { version = "0.25", default-features = false, features = ["png", "jpeg", "gif", "webp", "bmp"] }
+# `external-buffers`: the JSONL lines cross the FFI as an externally-backed Buffer (no copy).
+# Safe here: the addon only runs in PostHog's Node ingestion workers, never in V8
+# sandboxed-pointer environments (Electron), where external buffers abort the VM.
+neon = { workspace = true, features = ["external-buffers"] }
+serde = { workspace = true }
+serde_json = { workspace = true }
+simd-json = { version = "0.15", features = ["serde_impl"] }
+zstd = { workspace = true }
+
+[dev-dependencies]
+# flate2: tests verify reference gzip streams with an independent codec (not libdeflate), so a
+# codec regression can't hide by round-tripping through itself.
+flate2 = { workspace = true }
+serde_json = { workspace = true }
diff --git a/rust/replay-anonymizer-node/package.json b/rust/replay-anonymizer-node/package.json
new file mode 100644
index 000000000000..b4728fea2c80
--- /dev/null
+++ b/rust/replay-anonymizer-node/package.json
@@ -0,0 +1,31 @@
+{
+ "name": "@posthog/replay-anonymizer",
+ "version": "0.0.1",
+ "description": "Node bindings for the session-replay anonymizer",
+ "main": "dist/index.js",
+ "types": "dist/index.d.ts",
+ "scripts": {
+ "test": "cargo test -p replay-anonymizer-node",
+ "build": "pnpm run build:cargo --release && pnpm run build:move-lib && pnpm run build:typescript",
+ "build:dev": "pnpm run build:cargo && pnpm run build:move-lib:dev && pnpm run build:typescript",
+ "build:move-lib": "TARGET_DIR=${CARGO_TARGET_DIR:-../target} && cp \"$TARGET_DIR/release/libreplay_anonymizer_node.dylib\" index.node 2>/dev/null || cp \"$TARGET_DIR/release/libreplay_anonymizer_node.so\" index.node || (echo \"No valid library file found in $TARGET_DIR/release/\" && exit 1)",
+ "build:move-lib:dev": "TARGET_DIR=${CARGO_TARGET_DIR:-../target} && cp \"$TARGET_DIR/debug/libreplay_anonymizer_node.dylib\" index.node 2>/dev/null || cp \"$TARGET_DIR/debug/libreplay_anonymizer_node.so\" index.node || (echo \"No valid library file found in $TARGET_DIR/debug/\" && exit 1)",
+ "build:cargo": "cargo build -p replay-anonymizer-node --message-format=json > cargo.log",
+ "build:cargo:debug": "pnpm run build:cargo",
+ "build:typescript": "tsc",
+ "typecheck": "tsc --noEmit",
+ "clean": "rm -rf index.node dist",
+ "package": "NODE_ENV=development pnpm --filter=@posthog/replay-anonymizer run build"
+ },
+ "author": "",
+ "license": "MIT",
+ "devDependencies": {
+ "@types/node": "22.15.17",
+ "typescript": "6.0.3",
+ "undici-types": "^7.3.0"
+ },
+ "files": [
+ "dist",
+ "index.node"
+ ]
+}
diff --git a/rust/replay-anonymizer-node/src/allow_lists.rs b/rust/replay-anonymizer-node/src/allow_lists.rs
new file mode 100644
index 000000000000..e71d0800ac8a
--- /dev/null
+++ b/rust/replay-anonymizer-node/src/allow_lists.rs
@@ -0,0 +1,86 @@
+//! Case-insensitive allow lists of text words and URL path segments kept verbatim by the scrubbers.
+//! Mirrors `anonymize/allow-lists.ts`.
+
+// The lookups run once per word token of every text node; ahash beats SipHash on short strings and
+// the sets are built from operator-controlled config, so hash-DoS resistance buys nothing here.
+use ahash::AHashSet;
+
+fn has_upper_ascii(s: &str) -> bool {
+ s.bytes().any(|b| b.is_ascii_uppercase())
+}
+
+fn ascii_lowercase(s: &str) -> String {
+ // Only ASCII A-Z is folded, exactly like the TS (which does not lowercase non-ASCII).
+ let mut out = String::with_capacity(s.len());
+ for ch in s.chars() {
+ if ch.is_ascii_uppercase() {
+ out.push(ch.to_ascii_lowercase());
+ } else {
+ out.push(ch);
+ }
+ }
+ out
+}
+
+#[derive(Debug, Default)]
+pub struct AllowLists {
+ text: AHashSet<String>,
+ url: AHashSet<String>,
+ /// Bit i set = the text set contains a word of byte length i (lengths >= 63 share bit 63).
+ /// Most redacted tokens miss the mask and skip the hash entirely.
+ text_lens: u64,
+ url_lens: u64,
+}
+
+fn len_bit(s: &str) -> u64 {
+ 1u64 << s.len().min(63)
+}
+
+impl AllowLists {
+ pub fn new<I, J>(text: I, url: J) -> Self
+ where
+ I: IntoIterator,
+ I::Item: AsRef<str>,
+ J: IntoIterator,
+ J::Item: AsRef<str>,
+ {
+ let text: AHashSet<String> = text
+ .into_iter()
+ .map(|w| ascii_lowercase(w.as_ref()))
+ .collect();
+ let url: AHashSet<String> = url
+ .into_iter()
+ .map(|s| ascii_lowercase(s.as_ref()))
+ .collect();
+ let text_lens = text.iter().map(|w| len_bit(w)).fold(0, |a, b| a | b);
+ let url_lens = url.iter().map(|w| len_bit(w)).fold(0, |a, b| a | b);
+ Self {
+ text,
+ url,
+ text_lens,
+ url_lens,
+ }
+ }
+
+ pub fn text_contains(&self, word: &str) -> bool {
+ if self.text_lens & len_bit(word) == 0 {
+ return false;
+ }
+ if has_upper_ascii(word) {
+ self.text.contains(&ascii_lowercase(word))
+ } else {
+ self.text.contains(word)
+ }
+ }
+
+ pub fn url_contains(&self, segment: &str) -> bool {
+ if self.url_lens & len_bit(segment) == 0 {
+ return false;
+ }
+ if has_upper_ascii(segment) {
+ self.url.contains(&ascii_lowercase(segment))
+ } else {
+ self.url.contains(segment)
+ }
+ }
+}
diff --git a/rust/replay-anonymizer-node/src/assets.rs b/rust/replay-anonymizer-node/src/assets.rs
new file mode 100644
index 000000000000..9e6f696ed1ca
--- /dev/null
+++ b/rust/replay-anonymizer-node/src/assets.rs
@@ -0,0 +1,83 @@
+//! Media detection + placeholder/blur dispatch. Mirrors `anonymize/assets.ts`.
+//! Blur runs inline (native), so there is no deferred-job/blank-first dance — the attribute lands on
+//! its final blurred (or placeholder) value directly.
+
+use std::borrow::Cow;
+
+use simd_json::borrowed::{Object, Value};
+
+use crate::blur::{blank_image_data_uri, is_image_data_uri};
+use crate::context::Ctx;
+use crate::json::{as_str, string_value};
+use crate::url::scrub_url_opts;
+
+// rrweb inlines rendered pixels (a `toDataURL()` snapshot) into this attribute.
+pub const INLINE_IMAGE_ATTR: &str = "rr_dataURL";
+
+pub const PLACEHOLDER_SRC: &str = "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>";
+
+pub const MEDIA_SRC_ATTRS: &[&str] = &["src", "srcset", "href", "xlink:href", "poster"];
+
+pub fn is_media_tag(tag: &str) -> bool {
+ matches!(
+ tag.to_ascii_lowercase().as_str(),
+ "img" | "image" | "video" | "audio" | "source" | "track" | "picture"
+ )
+}
+
+pub fn is_media_src_attr(name: &str) -> bool {
+ MEDIA_SRC_ATTRS.contains(&name)
+}
+
+/// True if an attribute map contains any media-source attribute.
+pub fn has_media_src_attr(attrs: &Object<'_>) -> bool {
+ MEDIA_SRC_ATTRS.iter().any(|name| attrs.contains_key(*name))
+}
+
+/// Blur an inlined-image data URI held in an attribute (a `<canvas>`/`<img>` `rr_dataURL`).
+/// Returns whether it acted.
+pub fn blur_inline_image_attr(ctx: &Ctx<'_>, attrs: &mut Object<'_>, name: &str) -> bool {
+ let Some(value) = attrs.get(name).and_then(as_str).map(str::to_string) else {
+ return false;
+ };
+ if !is_image_data_uri(&value) {
+ return false;
+ }
+ let blurred = ctx
+ .blur_data_uri(&value)
+ .unwrap_or_else(blank_image_data_uri);
+ attrs.insert(Cow::Owned(name.to_string()), string_value(blurred));
+ true
+}
+
+/// Replace a media element's source attrs with the blurred image (data URIs) or placeholder (remote
+/// URLs, whose scrubbed original is stashed under a namespaced attr). Returns whether it changed any
+/// attribute — a media tag with no source attrs (e.g. a bare `<img>`) is left untouched.
+pub fn apply_blur(ctx: &Ctx<'_>, attrs: &mut Object<'_>) -> bool {
+ let mut acted = false;
+ for key in MEDIA_SRC_ATTRS {
+ let Some(existing) = attrs.get(*key).and_then(as_str).map(str::to_string) else {
+ continue;
+ };
+ acted = true;
+ if is_image_data_uri(&existing) {
+ let blurred = ctx
+ .blur_data_uri(&existing)
+ .unwrap_or_else(|| PLACEHOLDER_SRC.to_string());
+ attrs.insert(Cow::Borrowed(*key), string_value(blurred));
+ } else {
+ // Host-scrubbed too so a CDN host can't leak; stashed under a namespaced attr that won't
+ // collide with an app `data-original-*`.
+ let scrubbed = scrub_url_opts(ctx.allow, &existing, true).unwrap_or(existing);
+ attrs.insert(
+ Cow::Borrowed(*key),
+ Value::String(Cow::Borrowed(PLACEHOLDER_SRC)),
+ );
+ attrs.insert(
+ Cow::Owned(format!("data-anon-original-{key}")),
+ string_value(scrubbed),
+ );
+ }
+ }
+ acted
+}
diff --git a/rust/replay-anonymizer-node/src/blur.rs b/rust/replay-anonymizer-node/src/blur.rs
new file mode 100644
index 000000000000..6b8d73d90e68
--- /dev/null
+++ b/rust/replay-anonymizer-node/src/blur.rs
@@ -0,0 +1,177 @@
+//! 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.
+
+use base64::Engine;
+use image::{DynamicImage, GenericImageView, RgbaImage};
+
+const DOWNSAMPLE_RATIO: f32 = 0.12;
+const BLUR_SIGMA: f32 = 2.34;
+const MAX_LONG_SIDE: f32 = 96.0;
+
+// Bounds on decoding fully untrusted image bytes: a tiny compressed image can declare huge dimensions
+// (a decompression bomb). Reject those to the blank/placeholder fallback rather than allocating GBs.
+const MAX_IMAGE_SIDE: u32 = 16_384;
+const MAX_IMAGE_ALLOC_BYTES: u64 = 256 * 1024 * 1024;
+
+fn decode_limited(bytes: &[u8]) -> Option<DynamicImage> {
+ let mut limits = image::Limits::default();
+ limits.max_image_width = Some(MAX_IMAGE_SIDE);
+ limits.max_image_height = Some(MAX_IMAGE_SIDE);
+ limits.max_alloc = Some(MAX_IMAGE_ALLOC_BYTES);
+ let reader = image::ImageReader::new(std::io::Cursor::new(bytes))
+ .with_guessed_format()
+ .ok()?;
+ let mut reader = reader;
+ reader.limits(limits);
+ reader.decode().ok()
+}
+
+/// A 1x1 transparent PNG: the fail-safe stand-in used when the real blur can't be produced.
+pub const BLANK_PNG_BASE64: &str =
+ "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNk+M9QDwADhgGAWjR9awAAAABJRU5ErkJggg==";
+
+pub fn blank_image_data_uri() -> String {
+ format!("data:image/png;base64,{BLANK_PNG_BASE64}")
+}
+
+pub fn is_image_data_uri(s: &str) -> bool {
+ s.starts_with("data:image/")
+}
+
+/// Scale to DOWNSAMPLE_RATIO, but never leave the long side above MAX_LONG_SIDE; floored at 1px.
+fn target_dims(width: u32, height: u32) -> (u32, u32) {
+ let w = width.max(1) as f32;
+ let h = height.max(1) as f32;
+ let scale = DOWNSAMPLE_RATIO.min(MAX_LONG_SIDE / w.max(h));
+ (
+ ((w * scale).round() as u32).max(1),
+ ((h * scale).round() as u32).max(1),
+ )
+}
+
+fn encode_png_base64(img: &DynamicImage) -> Option<String> {
+ let mut buf = Vec::new();
+ img.write_to(&mut std::io::Cursor::new(&mut buf), image::ImageFormat::Png)
+ .ok()?;
+ Some(base64::engine::general_purpose::STANDARD.encode(&buf))
+}
+
+/// Downsample a base64 image data URI to a fraction of its size + a blur, as a PNG; None if it can't.
+/// On any failure we return None and the caller blanks the image. This intentionally omits the TS
+/// fallback ladder (plain downsample-without-blur before giving up): failing toward a blank pixel is
+/// strictly safer than emitting an unblurred thumbnail on this unencrypted-bucket path.
+pub fn blur_image_data_uri(s: &str) -> Option<String> {
+ let rest = s.strip_prefix("data:")?;
+ let (meta, payload) = rest.split_once(',')?;
+ if !meta.contains("base64") || !meta.starts_with("image/") {
+ return None;
+ }
+ let bytes = base64::engine::general_purpose::STANDARD
+ .decode(payload.as_bytes())
+ .ok()?;
+ let img = decode_limited(&bytes)?; // can't read the header / exceeds limits -> None
+ let (w, h) = img.dimensions();
+ let (tw, th) = target_dims(w, h);
+ // Downsample (fit: fill) then Gaussian blur, mirroring the TS pipeline order.
+ let out = img
+ .resize_exact(tw, th, image::imageops::FilterType::Triangle)
+ .blur(BLUR_SIGMA);
+ let encoded = encode_png_base64(&out)?;
+ Some(format!("data:image/png;base64,{encoded}"))
+}
+
+/// De-identify raw RGBA pixels: downsample + blur, then scale back to the original W x H, preserving
+/// byte length (`4*W*H`) so it slots back into a `putImageData` ImageData. None if it can't.
+pub fn pixelate_raw_rgba(base64_pixels: &str, width: u32, height: u32) -> Option<String> {
+ let buf = base64::engine::general_purpose::STANDARD
+ .decode(base64_pixels.as_bytes())
+ .ok()?;
+ // `checked_mul`: `w*h*4` on attacker-controlled dims can overflow usize; overflow -> reject.
+ let expected = (width as usize)
+ .checked_mul(height as usize)
+ .and_then(|wh| wh.checked_mul(4))?;
+ if buf.len() != expected {
+ return None;
+ }
+ let img = RgbaImage::from_raw(width, height, buf)?;
+ let dynamic = DynamicImage::ImageRgba8(img);
+ let (sw, sh) = target_dims(width, height);
+ let small = dynamic
+ .resize_exact(sw, sh, image::imageops::FilterType::Triangle)
+ .blur(BLUR_SIGMA);
+ let restored = small.resize_exact(width, height, image::imageops::FilterType::Triangle);
+ let out = restored.to_rgba8().into_raw();
+ if out.len() != expected {
+ return None;
+ }
+ Some(base64::engine::general_purpose::STANDARD.encode(&out))
+}
+
+/// Split a `data:<mime>;...,<base64>` URI into (mime, base64). None if not a data URI.
+pub fn split_data_uri(uri: &str) -> Option<(String, String)> {
+ let rest = uri.strip_prefix("data:")?;
+ let comma = rest.find(',')?;
+ let mime = rest[..comma].split(';').next().unwrap_or("image/png");
+ let mime = if mime.is_empty() { "image/png" } else { mime };
+ Some((mime.to_string(), rest[comma + 1..].to_string()))
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use image::GenericImageView;
+
+ fn png_data_uri(w: u32, h: u32) -> String {
+ let img = image::DynamicImage::ImageRgba8(image::RgbaImage::from_pixel(
+ w,
+ h,
+ image::Rgba([120, 30, 200, 255]),
+ ));
+ let mut buf = Vec::new();
+ img.write_to(&mut std::io::Cursor::new(&mut buf), image::ImageFormat::Png)
+ .unwrap();
+ format!(
+ "data:image/png;base64,{}",
+ base64::engine::general_purpose::STANDARD.encode(&buf)
+ )
+ }
+
+ #[test]
+ fn blur_downsamples_to_target_dims_as_png() {
+ let uri = png_data_uri(100, 50);
+ let out = blur_image_data_uri(&uri).expect("blur should succeed for a valid png");
+ assert!(out.starts_with("data:image/png;base64,"));
+ let (_, b64) = split_data_uri(&out).unwrap();
+ let bytes = base64::engine::general_purpose::STANDARD
+ .decode(&b64)
+ .unwrap();
+ let decoded = image::load_from_memory(&bytes).unwrap();
+ // target_dims(100, 50) with ratio 0.12 -> (12, 6).
+ assert_eq!(decoded.dimensions(), (12, 6));
+ }
+
+ #[test]
+ fn blur_rejects_non_image_data_uri() {
+ assert!(blur_image_data_uri("data:text/plain;base64,aGVsbG8=").is_none());
+ assert!(blur_image_data_uri("not a data uri").is_none());
+ }
+
+ #[test]
+ fn pixelate_preserves_rgba_byte_length() {
+ let (w, h) = (8u32, 8u32);
+ let raw = vec![200u8; (w * h * 4) as usize];
+ let b64 = base64::engine::general_purpose::STANDARD.encode(&raw);
+ let out = pixelate_raw_rgba(&b64, w, h).expect("pixelate should succeed");
+ let out_bytes = base64::engine::general_purpose::STANDARD
+ .decode(&out)
+ .unwrap();
+ assert_eq!(out_bytes.len(), raw.len());
+ }
+
+ #[test]
+ fn pixelate_rejects_wrong_length() {
+ let b64 = base64::engine::general_purpose::STANDARD.encode([0u8; 10]);
+ assert!(pixelate_raw_rgba(&b64, 8, 8).is_none());
+ }
+}
diff --git a/rust/replay-anonymizer-node/src/bytewalk.rs b/rust/replay-anonymizer-node/src/bytewalk.rs
new file mode 100644
index 000000000000..0cfd00e6b418
--- /dev/null
+++ b/rust/replay-anonymizer-node/src/bytewalk.rs
@@ -0,0 +1,1045 @@
+//! Parse-free byte scrub of an event's `data` span: walk the raw JSON,
+//! bulk-copy unchanged values verbatim, and re-emit only the strings a scrubber changes — no tree,
+//! no dedupe pass, no re-serialization of untouched bytes.
+//!
+//! Covers the routes that carry the bulk of replay bytes: uncompressed full snapshots, uncompressed
+//! mutations, and inputs. Everything else — `cv`-compressed payloads, canvas, meta/custom/plugin —
+//! returns `None` and the caller keeps its parse-based path. The scrub *decisions* are shared with
+//! the tree walk (`dom::classify_tag`, the attr predicates, `text::scrub_text`, ...), so the two
+//! implementations can only disagree on traversal mechanics — which the differential tests pin.
+//!
+//! Fail-closed: any escaped key, any duplicate key in any object (a byte walker classifying off the
+//! first occurrence would diverge from JSON.parse's last-wins and could route content past a
+//! scrubber), any object with more keys than the dup check covers, or any structural surprise makes
+//! the whole walk return `None` — the caller falls back to the parse, which resolves those exactly.
+
+use crate::assets::{is_media_src_attr, INLINE_IMAGE_ATTR, MEDIA_SRC_ATTRS, PLACEHOLDER_SRC};
+use crate::blur::{blank_image_data_uri, is_image_data_uri};
+use crate::context::Ctx;
+use crate::css;
+use crate::dom::{
+ classify_tag, data_attr_looks_sensitive, is_data_attr, is_url_attr, is_user_text_attr,
+ ParentKind, TagKind,
+};
+use crate::event::{SOURCE_INPUT, SOURCE_MUTATION, TYPE_FULL_SNAPSHOT, TYPE_INCREMENTAL};
+use crate::scan::{self, Span};
+use crate::text::{redact_emails, scrub_text};
+use crate::url::{scrub_url, scrub_url_opts};
+
+// rrweb NodeType (mirrors dom.rs).
+const NODE_DOCUMENT: u8 = 0;
+const NODE_ELEMENT: u8 = 2;
+const NODE_TEXT: u8 = 3;
+const NODE_CDATA: u8 = 4;
+const NODE_COMMENT: u8 = 5;
+
+/// Per-object duplicate-key coverage; more keys than this falls back (dup safety can't be proven).
+const MAX_OBJECT_KEYS: usize = 32;
+
+/// Marker: this event must be handled by the parse instead.
+struct Fallback;
+
+/// Emit a deferred member's key (with its quotes) plus separators into `out`.
+fn emit_deferred_key(bytes: &[u8], key: Span, emitted: &mut usize, out: &mut Vec<u8>) {
+ if *emitted > 0 {
+ out.push(b',');
+ }
+ *emitted += 1;
+ out.extend_from_slice(&bytes[key.0 - 1..key.1 + 1]);
+ out.push(b':');
+}
+
+/// First 8 bytes of a key as a comparable word (shorter keys zero-padded).
+#[inline]
+fn key_prefix(key: &[u8]) -> u64 {
+ let mut buf = [0u8; 8];
+ let n = key.len().min(8);
+ buf[..n].copy_from_slice(&key[..n]);
+ u64::from_le_bytes(buf)
+}
+
+/// Recursion bound for the walk (one count per nested container; real DOM nesting is ~25). Beyond
+/// this the event declines to the parse path, whose own span-local depth guard fails it closed —
+/// deliberately far below the parse guard's 1024 because walk frames are larger than parse frames.
+const MAX_WALK_DEPTH: usize = 256;
+
+struct Walker<'c, 'a> {
+ ctx: &'c Ctx<'c>,
+ bytes: &'a [u8],
+ changed: bool,
+ depth: usize,
+ /// Duplicate-key scratch shared across the recursion: each object checks its own frame
+ /// (`base..`), so there is no per-object array to zero.
+ seen: Vec<(Span, u64)>,
+}
+
+type FieldFn<'w, 'c, 'a> =
+ dyn FnMut(&mut Walker<'c, 'a>, Span, usize, &mut Vec<u8>) -> Option<usize> + 'w;
+type ItemFn<'c, 'a> = dyn FnMut(&mut Walker<'c, 'a>, usize, &mut Vec<u8>) -> Option<usize>;
+
+/// Scrub the `data` span of one event into `out`. `Some(changed)` on success; `None` means
+/// "fall back to the parse" — the caller must discard whatever was written.
+pub fn scrub_data_bytes(
+ ctx: &Ctx<'_>,
+ ty: Option<u8>,
+ source: Option<u8>,
+ compressed: bool,
+ bytes: &[u8],
+ data: Span,
+ out: &mut Vec<u8>,
+) -> Option<bool> {
+ if compressed {
+ // Mirrors `route_data`'s cv dispatch: only a snapshot's data string and a mutation's
+ // sub-fields are blob-compressed. Snapshot-with-object-data and input fall through to the
+ // plain walk (the marker changes nothing there); routes the walk doesn't carry decline.
+ match (ty, source) {
+ (Some(TYPE_FULL_SNAPSHOT), _) if bytes.get(data.0) == Some(&b'"') => {
+ return scrub_cv_snapshot_value(ctx, bytes, data, out);
+ }
+ (Some(TYPE_INCREMENTAL), Some(SOURCE_MUTATION)) => {
+ return scrub_cv_mutation_data(ctx, bytes, data, out);
+ }
+ (Some(TYPE_FULL_SNAPSHOT), _) | (Some(TYPE_INCREMENTAL), Some(SOURCE_INPUT)) => {}
+ _ => return None,
+ }
+ }
+ if bytes.get(data.0) != Some(&b'{') {
+ return None;
+ }
+ let mut w = Walker {
+ ctx,
+ bytes,
+ changed: false,
+ depth: 0,
+ seen: Vec::with_capacity(64),
+ };
+ let end = match (ty, source) {
+ (Some(TYPE_FULL_SNAPSHOT), _) => w.walk_object(
+ data.0,
+ out,
+ &mut |w, key, vstart, out| match &w.bytes[key.0..key.1] {
+ b"node" => w.walk_node(vstart, ParentKind::Other, out),
+ _ => w.copy_value(vstart, out),
+ },
+ )?,
+ (Some(TYPE_INCREMENTAL), Some(SOURCE_MUTATION)) => w.walk_object(
+ data.0,
+ out,
+ &mut |w, key, vstart, out| match &w.bytes[key.0..key.1] {
+ b"texts" => w.walk_texts(vstart, out),
+ b"attributes" => w.walk_mutation_attributes(vstart, out),
+ b"adds" => w.walk_adds(vstart, out),
+ _ => w.copy_value(vstart, out),
+ },
+ )?,
+ (Some(TYPE_INCREMENTAL), Some(SOURCE_INPUT)) => w.walk_object(
+ data.0,
+ out,
+ &mut |w, key, vstart, out| match &w.bytes[key.0..key.1] {
+ b"text" => w.scrub_string_value(vstart, out, |w, s| scrub_text(w.ctx.allow, s)),
+ _ => w.copy_value(vstart, out),
+ },
+ )?,
+ _ => return None,
+ };
+ debug_assert_eq!(end, data.1);
+ Some(w.changed)
+}
+
+/// Which gzipped mutation sub-field a decompressed cv payload came from.
+#[derive(Clone, Copy)]
+pub enum CvMutationField {
+ Texts,
+ Attributes,
+ Adds,
+}
+
+/// Scrub a decompressed cv FullSnapshot payload (`bytes` is the whole `data` object) into `out`.
+/// `Some(changed)` on success; `None` means "fall back to the parse path" — `out` then holds a
+/// partial emission the caller must discard.
+pub fn scrub_cv_snapshot(ctx: &Ctx<'_>, bytes: &[u8], out: &mut Vec<u8>) -> Option<bool> {
+ let mut w = Walker {
+ ctx,
+ bytes,
+ changed: false,
+ depth: 0,
+ seen: Vec::with_capacity(64),
+ };
+ let start = scan::skip_ws(bytes, 0);
+ let end = w.walk_object(
+ start,
+ out,
+ &mut |w, key, vstart, out| match &w.bytes[key.0..key.1] {
+ b"node" => w.walk_node(vstart, ParentKind::Other, out),
+ _ => w.copy_value(vstart, out),
+ },
+ )?;
+ (scan::skip_ws(bytes, end) == bytes.len()).then_some(w.changed)
+}
+
+/// Scrub one decompressed cv mutation sub-field (`bytes` is the whole array) into `out`.
+/// `Some(changed)` on success; `None` declines to the parse. A non-`[` payload must decline (the
+/// parse fails non-arrays closed) rather than hit `walk_array`'s copy-verbatim branch.
+pub fn scrub_cv_mutation_field(
+ ctx: &Ctx<'_>,
+ field: CvMutationField,
+ bytes: &[u8],
+ out: &mut Vec<u8>,
+) -> Option<bool> {
+ let start = scan::skip_ws(bytes, 0);
+ if bytes.get(start) != Some(&b'[') {
+ return None;
+ }
+ let mut w = Walker {
+ ctx,
+ bytes,
+ changed: false,
+ depth: 0,
+ seen: Vec::with_capacity(64),
+ };
+ let end = match field {
+ CvMutationField::Texts => w.walk_texts(start, out),
+ CvMutationField::Attributes => w.walk_mutation_attributes(start, out),
+ CvMutationField::Adds => w.walk_adds(start, out),
+ }?;
+ (scan::skip_ws(bytes, end) == bytes.len()).then_some(w.changed)
+}
+
+/// Scrub a cv-compressed FullSnapshot data string from its still-escaped wire span, skipping the
+/// tree path's simd tape and intermediate UTF-8 `String`. Declines (`None`) on anything unexpected;
+/// the parse fallback fails malformed streams closed.
+fn scrub_cv_snapshot_value(
+ ctx: &Ctx<'_>,
+ bytes: &[u8],
+ data: Span,
+ out: &mut Vec<u8>,
+) -> Option<bool> {
+ if data.1 - data.0 < 2 || bytes.get(data.1 - 1) != Some(&b'"') {
+ return None;
+ }
+ let raw = latin1_from_wire(&bytes[data.0 + 1..data.1 - 1])?;
+ let decompressed = ctx.gunzip_cv(&raw).ok()?;
+ let mut walked = Vec::with_capacity(decompressed.len() + 64);
+ // Unchanged payloads re-emit too: the whole output is zstd, never mixed-format blocks.
+ let content = if scrub_cv_snapshot(ctx, &decompressed, &mut walked)? {
+ &walked
+ } else {
+ &decompressed
+ };
+ let zs = crate::gzip::compress_cv(content).ok()?;
+ write_latin1_json_string(&zs, out);
+ Some(true)
+}
+
+/// The mutation counterpart of [`scrub_cv_snapshot_value`]: envelope keys walk plainly, each
+/// gzipped sub-field re-emits per the codec mode.
+fn scrub_cv_mutation_data(
+ ctx: &Ctx<'_>,
+ bytes: &[u8],
+ data: Span,
+ out: &mut Vec<u8>,
+) -> Option<bool> {
+ let mut w = Walker {
+ ctx,
+ bytes,
+ changed: false,
+ depth: 0,
+ seen: Vec::with_capacity(64),
+ };
+ let end = w.walk_object(
+ data.0,
+ out,
+ &mut |w, key, vstart, out| match &w.bytes[key.0..key.1] {
+ b"texts" => w.walk_cv_sub(CvMutationField::Texts, vstart, out),
+ b"attributes" => w.walk_cv_sub(CvMutationField::Attributes, vstart, out),
+ b"adds" => w.walk_cv_sub(CvMutationField::Adds, vstart, out),
+ _ => w.copy_value(vstart, out),
+ },
+ )?;
+ debug_assert_eq!(end, data.1);
+ Some(w.changed)
+}
+
+/// Decode still-escaped JSON-string bytes of a cv value into latin-1 (compressed) bytes — the
+/// wire-side counterpart of `cv::latin1_to_bytes` without the intermediate UTF-8 `String`. `None`
+/// on anything outside latin-1-in-JSON (codepoint > 0xFF, bad escape, raw control): the caller
+/// declines to the parse, which fails malformed streams closed.
+fn latin1_from_wire(wire: &[u8]) -> Option<Vec<u8>> {
+ let mut out = Vec::with_capacity(wire.len());
+ let mut i = 0;
+ while i < wire.len() {
+ match wire[i] {
+ b'\\' => {
+ i += 1;
+ match *wire.get(i)? {
+ b'u' => {
+ let (c, used) = scan::decode_unicode(wire, i + 1).ok()?;
+ let cp = c as u32;
+ if cp > 0xFF {
+ return None;
+ }
+ out.push(cp as u8);
+ i += 1 + used;
+ }
+ b'"' => {
+ out.push(b'"');
+ i += 1;
+ }
+ b'\\' => {
+ out.push(b'\\');
+ i += 1;
+ }
+ b'/' => {
+ out.push(b'/');
+ i += 1;
+ }
+ b'b' => {
+ out.push(0x08);
+ i += 1;
+ }
+ b'f' => {
+ out.push(0x0C);
+ i += 1;
+ }
+ b'n' => {
+ out.push(b'\n');
+ i += 1;
+ }
+ b'r' => {
+ out.push(b'\r');
+ i += 1;
+ }
+ b't' => {
+ out.push(b'\t');
+ i += 1;
+ }
+ _ => return None,
+ }
+ }
+ 0x00..=0x1F => return None,
+ c @ 0x20..=0x7F => {
+ out.push(c);
+ i += 1;
+ }
+ lead @ (0xC2 | 0xC3) => {
+ let cont = *wire.get(i + 1)?;
+ if !(0x80..=0xBF).contains(&cont) {
+ return None;
+ }
+ out.push(((lead & 0x03) << 6) | (cont & 0x3F));
+ i += 2;
+ }
+ _ => return None,
+ }
+ }
+ Some(out)
+}
+
+/// Write-side inverse of [`latin1_from_wire`]: emit compressed bytes as a JSON latin-1 string.
+fn write_latin1_json_string(bytes: &[u8], out: &mut Vec<u8>) {
+ const HEX: &[u8; 16] = b"0123456789abcdef";
+ out.push(b'"');
+ for &b in bytes {
+ match b {
+ b'"' => out.extend_from_slice(b"\\\""),
+ b'\\' => out.extend_from_slice(b"\\\\"),
+ 0x00..=0x1F => {
+ out.extend_from_slice(b"\\u00");
+ out.push(HEX[(b >> 4) as usize]);
+ out.push(HEX[(b & 0xF) as usize]);
+ }
+ 0x20..=0x7F => out.push(b),
+ _ => {
+ out.push(0xC0 | (b >> 6));
+ out.push(0x80 | (b & 0x3F));
+ }
+ }
+ }
+ out.push(b'"');
+}
+
+impl<'c, 'a> Walker<'c, 'a> {
+ /// Emit-walk the object at `start`: keys verbatim, values via `field`. Detects escaped and
+ /// duplicate keys (fallback). Returns the position just past the closing `}`.
+ fn walk_object(
+ &mut self,
+ start: usize,
+ out: &mut Vec<u8>,
+ field: &mut FieldFn<'_, 'c, 'a>,
+ ) -> Option<usize> {
+ if self.depth >= MAX_WALK_DEPTH {
+ return None;
+ }
+ self.depth += 1;
+ let base = self.seen.len();
+ let result = self.walk_object_inner(base, start, out, field);
+ self.seen.truncate(base);
+ self.depth -= 1;
+ result
+ }
+
+ fn walk_object_inner(
+ &mut self,
+ base: usize,
+ start: usize,
+ out: &mut Vec<u8>,
+ field: &mut FieldFn<'_, 'c, 'a>,
+ ) -> Option<usize> {
+ let bytes = self.bytes;
+ if bytes.get(start) != Some(&b'{') {
+ return None;
+ }
+ out.push(b'{');
+ let mut nkeys = 0usize;
+ let mut pos = start + 1;
+ let mut first = true;
+ loop {
+ pos = scan::skip_ws(bytes, pos);
+ if bytes.get(pos) == Some(&b'}') {
+ out.push(b'}');
+ return Some(pos + 1);
+ }
+ if !first {
+ if bytes.get(pos) != Some(&b',') {
+ return None;
+ }
+ pos = scan::skip_ws(bytes, pos + 1);
+ }
+ first = false;
+ if bytes.get(pos) != Some(&b'"') {
+ return None;
+ }
+ let key_end = scan::skip_string(bytes, pos).ok()?;
+ let key = (pos + 1, key_end - 1);
+ let raw_key = &bytes[key.0..key.1];
+ if raw_key.contains(&b'\\') || nkeys >= MAX_OBJECT_KEYS {
+ return None;
+ }
+ // Duplicate detection compares (len, 8-byte prefix) first — rrweb keys are short, so
+ // the full memcmp only runs for same-length same-prefix pairs.
+ let prefix = key_prefix(raw_key);
+ if self.seen[base..].iter().any(|(prior, prior_prefix)| {
+ *prior_prefix == prefix
+ && prior.1 - prior.0 == raw_key.len()
+ && (raw_key.len() <= 8 || &bytes[prior.0..prior.1] == raw_key)
+ }) {
+ return None;
+ }
+ self.seen.push((key, prefix));
+ nkeys += 1;
+ if nkeys > 1 {
+ out.push(b',');
+ }
+ out.extend_from_slice(&bytes[pos..key_end]); // key incl quotes, verbatim
+ out.push(b':');
+ pos = scan::skip_ws(bytes, key_end);
+ if bytes.get(pos) != Some(&b':') {
+ return None;
+ }
+ let vstart = scan::skip_ws(bytes, pos + 1);
+ pos = field(self, key, vstart, out)?;
+ }
+ }
+
+ /// Emit-walk the array at `start`, items via `item`. Returns the position past the `]`.
+ fn walk_array(
+ &mut self,
+ start: usize,
+ out: &mut Vec<u8>,
+ item: &mut ItemFn<'c, 'a>,
+ ) -> Option<usize> {
+ if self.depth >= MAX_WALK_DEPTH {
+ return None;
+ }
+ self.depth += 1;
+ let result = self.walk_array_inner(start, out, item);
+ self.depth -= 1;
+ result
+ }
+
+ fn walk_array_inner(
+ &mut self,
+ start: usize,
+ out: &mut Vec<u8>,
+ item: &mut ItemFn<'c, 'a>,
+ ) -> Option<usize> {
+ let bytes = self.bytes;
+ if bytes.get(start) != Some(&b'[') {
+ // Not an array: the tree walk leaves it untouched.
+ return self.copy_value(start, out);
+ }
+ out.push(b'[');
+ let mut pos = start + 1;
+ let mut first = true;
+ loop {
+ pos = scan::skip_ws(bytes, pos);
+ if bytes.get(pos) == Some(&b']') {
+ out.push(b']');
+ return Some(pos + 1);
+ }
+ if !first {
+ if bytes.get(pos) != Some(&b',') {
+ return None;
+ }
+ out.push(b',');
+ pos = scan::skip_ws(bytes, pos + 1);
+ }
+ first = false;
+ pos = item(self, pos, out)?;
+ }
+ }
+
+ /// Copy the value at `start` verbatim; returns the position past it.
+ fn copy_value(&mut self, start: usize, out: &mut Vec<u8>) -> Option<usize> {
+ let span = scan::locate_value(self.bytes, start).ok()?;
+ out.extend_from_slice(&self.bytes[span.0..span.1]);
+ Some(span.1)
+ }
+
+ /// The value at `start`, if it is a string: unescape, apply `scrub`; changed strings re-emit
+ /// escaped, unchanged strings copy verbatim (original escapes preserved). Non-strings copy
+ /// verbatim (the tree walk only scrubs string values).
+ fn scrub_string_value(
+ &mut self,
+ start: usize,
+ out: &mut Vec<u8>,
+ scrub: impl FnOnce(&Walker<'c, 'a>, &str) -> Option<String>,
+ ) -> Option<usize> {
+ let bytes = self.bytes;
+ if bytes.get(start) != Some(&b'"') {
+ return self.copy_value(start, out);
+ }
+ let end = scan::skip_string(bytes, start).ok()?;
+ let decoded = scan::unescape(bytes, (start, end)).ok()?;
+ match scrub(self, &decoded) {
+ Some(replacement) => {
+ scan::write_json_string(&replacement, out);
+ self.changed = true;
+ }
+ None => out.extend_from_slice(&bytes[start..end]),
+ }
+ Some(end)
+ }
+
+ /// Shallow scan for a member's value span without emitting (order-independent field lookup,
+ /// e.g. `type`/`tagName` before deciding how to walk). First occurrence; duplicate keys make
+ /// the emit-walk fall back before its result could ever be used.
+ ///
+ /// Budgeted: real capture bytes put the routing keys (`type`, `tagName`) ahead of the heavy
+ /// subtrees (JSON.stringify insertion order), so this normally reads a few dozen bytes. A
+ /// producer that reorders keys behind a large container would otherwise make every node's
+ /// pre-scan skip its whole subtree — O(depth x size) — so past the budget the event falls back
+ /// to the parse instead (`Err`), which is merely slower, never wrong.
+ fn find_member(&self, obj_start: usize, name: &[u8]) -> Result<Option<Span>, Fallback> {
+ const PRESCAN_BUDGET: usize = 4096;
+ let bytes = self.bytes;
+ let budget_end = obj_start.saturating_add(PRESCAN_BUDGET);
+ let mut pos = obj_start + 1;
+ let mut first = true;
+ loop {
+ pos = scan::skip_ws(bytes, pos);
+ if bytes.get(pos) == Some(&b'}') {
+ return Ok(None);
+ }
+ if pos >= budget_end {
+ return Err(Fallback);
+ }
+ if !first {
+ if bytes.get(pos) != Some(&b',') {
+ return Ok(None);
+ }
+ pos = scan::skip_ws(bytes, pos + 1);
+ }
+ first = false;
+ if bytes.get(pos) != Some(&b'"') {
+ return Ok(None);
+ }
+ let key_end = scan::skip_string(bytes, pos).map_err(|_| Fallback)?;
+ let key = &bytes[pos + 1..key_end - 1];
+ pos = scan::skip_ws(bytes, key_end);
+ if bytes.get(pos) != Some(&b':') {
+ return Ok(None);
+ }
+ let vspan = scan::locate_value(bytes, pos + 1).map_err(|_| Fallback)?;
+ if key == name {
+ return Ok(Some(vspan));
+ }
+ pos = vspan.1;
+ }
+ }
+
+ /// One serialized rrweb node (mirrors `dom::walk_node`), order-independently: capture's
+ /// serde round-trip alphabetizes keys, putting `tagName`/`type` AFTER the `childNodes` subtree,
+ /// so pre-scanning for them would re-skip every subtree at every level (O(depth x size) — the
+ /// profiled 3x collapse). Instead the walk defers the small order-sensitive members as spans
+ /// (scalars, `textContent`, the `attributes` object) and emits them once the routing fields are
+ /// known — output key order may differ from the input, which the contract (semantic JSON)
+ /// permits. `childNodes` is too big to defer, so children emit optimistically as parent=Other;
+ /// the rare late script/style discovery splices that segment (those subtrees are tiny), and
+ /// shapes the assumptions can't hold for redo the node through the tree scrub locally.
+ fn walk_node(&mut self, start: usize, parent: ParentKind, out: &mut Vec<u8>) -> Option<usize> {
+ let bytes = self.bytes;
+ if bytes.get(start) != Some(&b'{') {
+ // Non-object nodes are left untouched by the tree walk.
+ return self.copy_value(start, out);
+ }
+ if self.depth >= MAX_WALK_DEPTH {
+ return None;
+ }
+ self.depth += 1;
+ let base = self.seen.len();
+ let node_mark = out.len();
+ let changed_before = self.changed;
+ let result = self.walk_node_inner(base, start, parent, node_mark, changed_before, out);
+ self.seen.truncate(base);
+ self.depth -= 1;
+ result
+ }
+
+ #[allow(clippy::too_many_arguments)]
+ fn walk_node_inner(
+ &mut self,
+ base: usize,
+ start: usize,
+ parent: ParentKind,
+ node_mark: usize,
+ changed_before: bool,
+ out: &mut Vec<u8>,
+ ) -> Option<usize> {
+ let bytes = self.bytes;
+ out.push(b'{');
+ let mut emitted = 0usize;
+ // Deferred member spans (key span, value span).
+ let mut ty_m: Option<(Span, Span)> = None;
+ let mut tag_m: Option<(Span, Span)> = None;
+ let mut is_style_m: Option<(Span, Span)> = None;
+ let mut text_m: Option<(Span, Span)> = None;
+ let mut attrs_m: Option<(Span, Span)> = None;
+ // childNodes: emitted range in `out` + source span, for the rare late splice.
+ let mut children: Option<((usize, usize), Span, Span)> = None;
+
+ let mut pos = start + 1;
+ let mut first = true;
+ let end = loop {
+ pos = scan::skip_ws(bytes, pos);
+ if bytes.get(pos) == Some(&b'}') {
+ break pos + 1;
+ }
+ if !first {
+ if bytes.get(pos) != Some(&b',') {
+ return None;
+ }
+ pos = scan::skip_ws(bytes, pos + 1);
+ }
+ first = false;
+ if bytes.get(pos) != Some(&b'"') {
+ return None;
+ }
+ let key_end = scan::skip_string(bytes, pos).ok()?;
+ let key = (pos + 1, key_end - 1);
+ let raw_key = &bytes[key.0..key.1];
+ // The key cap bounds the per-key duplicate scan below (quadratic in keys otherwise).
+ if raw_key.contains(&b'\\') || self.seen.len() - base >= MAX_OBJECT_KEYS {
+ return None;
+ }
+ let prefix = key_prefix(raw_key);
+ if self.seen[base..].iter().any(|(prior, prior_prefix)| {
+ *prior_prefix == prefix
+ && prior.1 - prior.0 == raw_key.len()
+ && (raw_key.len() <= 8 || &bytes[prior.0..prior.1] == raw_key)
+ }) {
+ return None;
+ }
+ self.seen.push((key, prefix));
+ pos = scan::skip_ws(bytes, key_end);
+ if bytes.get(pos) != Some(&b':') {
+ return None;
+ }
+ let vstart = scan::skip_ws(bytes, pos + 1);
+ match raw_key {
+ b"type" | b"tagName" | b"isStyle" | b"textContent" | b"attributes" => {
+ let vspan = scan::locate_value(bytes, vstart).ok()?;
+ let slot = match raw_key {
+ b"type" => &mut ty_m,
+ b"tagName" => &mut tag_m,
+ b"isStyle" => &mut is_style_m,
+ b"textContent" => &mut text_m,
+ _ => &mut attrs_m,
+ };
+ *slot = Some((key, vspan));
+ pos = vspan.1;
+ }
+ b"childNodes" if bytes.get(vstart) == Some(&b'[') => {
+ if emitted > 0 {
+ out.push(b',');
+ }
+ emitted += 1;
+ out.extend_from_slice(&bytes[key.0 - 1..key_end]);
+ out.push(b':');
+ let seg_start = out.len();
+ let vend = self.walk_array(vstart, out, &mut |w, p, o| {
+ w.walk_node(p, ParentKind::Other, o)
+ })?;
+ children = Some(((seg_start, out.len()), (key.0 - 1, key_end), (vstart, vend)));
+ pos = vend;
+ }
+ _ => {
+ if emitted > 0 {
+ out.push(b',');
+ }
+ emitted += 1;
+ out.extend_from_slice(&bytes[key.0 - 1..key_end]);
+ out.push(b':');
+ pos = self.copy_value(vstart, out)?;
+ }
+ }
+ };
+
+ // Routing fields resolved; decide how the deferred members are treated.
+ let ty = ty_m.and_then(|(_, v)| {
+ scan::parse_number(bytes, v)
+ .and_then(|n| (n.fract() == 0.0 && (0.0..=255.0).contains(&n)).then_some(n as u8))
+ });
+ let kind = match tag_m {
+ Some((_, v)) if scan::is_string(bytes, v) => {
+ classify_tag(&scan::unescape(bytes, v).ok()?)
+ }
+ _ => classify_tag(""),
+ };
+ let node_changed = self.changed != changed_before;
+
+ match ty {
+ Some(NODE_ELEMENT) => {
+ if let (TagKind::Script, Some((seg, _, src))) = (kind, children) {
+ // Script content is code — the tree leaves the children untouched.
+ let verbatim = &bytes[src.0..src.1];
+ out.splice(seg.0..seg.1, verbatim.iter().copied());
+ }
+ if let (TagKind::Style, Some((seg, _, src))) = (kind, children) {
+ // Style children are CSS text: rebuild that segment with the style parent.
+ let mut tmp = Vec::with_capacity(src.1 - src.0);
+ self.walk_array(src.0, &mut tmp, &mut |w, p, o| {
+ w.walk_node(p, ParentKind::Style, o)
+ })?;
+ out.splice(seg.0..seg.1, tmp.iter().copied());
+ }
+ // Attributes with the real tag kind (media blur vs plain scrubs).
+ if let Some((key, v)) = attrs_m {
+ emit_deferred_key(bytes, key, &mut emitted, out);
+ self.walk_attrs(v.0, kind, out)?;
+ }
+ for (key, v) in [ty_m, tag_m, is_style_m, text_m].into_iter().flatten() {
+ emit_deferred_key(bytes, key, &mut emitted, out);
+ out.extend_from_slice(&bytes[v.0..v.1]);
+ }
+ }
+ Some(NODE_TEXT) if parent == ParentKind::Script => {
+ // The tree never touches script text nodes: undo and re-emit verbatim.
+ out.truncate(node_mark);
+ out.extend_from_slice(&bytes[start..end]);
+ self.changed = changed_before;
+ return Some(end);
+ }
+ Some(NODE_TEXT) | Some(NODE_COMMENT) | Some(NODE_CDATA) => {
+ if children.map(|(seg, ..)| seg.0 != seg.1).unwrap_or(false) && node_changed {
+ // A text-ish node with scrubbed childNodes has no tree equivalent: redo.
+ return self.redo_node(start, end, parent, node_mark, out);
+ }
+ let styled = ty == Some(NODE_TEXT)
+ && (parent == ParentKind::Style
+ || is_style_m
+ .map(|(_, v)| bytes.get(v.0..v.1) == Some(b"true"))
+ .unwrap_or(false));
+ if let Some((key, v)) = text_m {
+ emit_deferred_key(bytes, key, &mut emitted, out);
+ if styled {
+ self.scrub_string_value(v.0, out, |w, s| css::rewrite(w.ctx, s))?;
+ } else {
+ self.scrub_string_value(v.0, out, |w, s| scrub_text(w.ctx.allow, s))?;
+ }
+ }
+ for (key, v) in [ty_m, tag_m, is_style_m, attrs_m].into_iter().flatten() {
+ emit_deferred_key(bytes, key, &mut emitted, out);
+ out.extend_from_slice(&bytes[v.0..v.1]);
+ }
+ }
+ Some(NODE_DOCUMENT) => {
+ if attrs_m.is_some() {
+ // The tree ignores document attributes but still scrubs the children — no
+ // optimistic emission matches that; let the tree do this node.
+ return self.redo_node(start, end, parent, node_mark, out);
+ }
+ // Children stay as walked (documents parent as Other); scalars verbatim.
+ for (key, v) in [ty_m, tag_m, is_style_m, text_m].into_iter().flatten() {
+ emit_deferred_key(bytes, key, &mut emitted, out);
+ out.extend_from_slice(&bytes[v.0..v.1]);
+ }
+ }
+ // DocumentType/unknown/incompatible shapes: the tree scrubs nothing here. If the
+ // optimistic walk changed anything, put the original bytes back; the deferred members
+ // re-emit verbatim either way.
+ _ => {
+ out.truncate(node_mark);
+ out.extend_from_slice(&bytes[start..end]);
+ self.changed = changed_before;
+ return Some(end);
+ }
+ }
+ out.push(b'}');
+ Some(end)
+ }
+
+ /// Node-local tree fallback: parse just this node's span, scrub it with the real parent kind,
+ /// and serialize it over whatever the optimistic walk emitted. Rare (odd node shapes).
+ fn redo_node(
+ &mut self,
+ start: usize,
+ end: usize,
+ parent: ParentKind,
+ node_mark: usize,
+ out: &mut Vec<u8>,
+ ) -> Option<usize> {
+ use simd_json::prelude::Writable;
+ out.truncate(node_mark);
+ let span = &self.bytes[start..end];
+ crate::json::reject_if_too_deep(span, "node").ok()?;
+ let mut scratch = span.to_vec();
+ let mut value = crate::json::parse_untrusted(&mut scratch).ok()?;
+ let changed = crate::dom::walk_node(self.ctx, &mut value, parent);
+ self.changed |= changed;
+ let mut serialized = Vec::with_capacity(span.len());
+ value.write(&mut serialized).ok()?;
+ out.extend_from_slice(&serialized);
+ Some(end)
+ }
+
+ /// An element's `attributes` object (mirrors `dom::scrub_attrs`, including the media blur).
+ /// Stash attrs (`data-anon-original-*`) are appended before the closing brace; the tree path
+ /// inserts them into the map instead, which is the same object semantically.
+ fn walk_attrs(&mut self, start: usize, kind: TagKind, out: &mut Vec<u8>) -> Option<usize> {
+ if self.bytes.get(start) != Some(&b'{') {
+ return self.copy_value(start, out);
+ }
+ let mut stashes: Vec<(String, String)> = Vec::new();
+ let end = {
+ let stashes = &mut stashes;
+ self.walk_object(start, out, &mut |w, key, vstart, out| {
+ let name = std::str::from_utf8(&w.bytes[key.0..key.1]).ok()?;
+ if kind == TagKind::Media && is_media_src_attr(name) {
+ return w.blur_media_src(name, vstart, out, stashes);
+ }
+ if name == INLINE_IMAGE_ATTR {
+ return w.scrub_string_value(vstart, out, |w, s| {
+ if !is_image_data_uri(s) {
+ return None;
+ }
+ Some(w.ctx.blur_data_uri(s).unwrap_or_else(blank_image_data_uri))
+ });
+ }
+ if name == "style" {
+ return w.scrub_string_value(vstart, out, |w, s| css::rewrite(w.ctx, s));
+ }
+ if is_url_attr(name) {
+ return w.scrub_string_value(vstart, out, |w, s| scrub_url(w.ctx.allow, s));
+ }
+ if is_user_text_attr(name) {
+ return w.scrub_string_value(vstart, out, |w, s| scrub_text(w.ctx.allow, s));
+ }
+ if is_data_attr(name) {
+ return w.scrub_string_value(vstart, out, |w, s| {
+ if data_attr_looks_sensitive(s) {
+ scrub_text(w.ctx.allow, s)
+ } else {
+ redact_emails(s)
+ }
+ });
+ }
+ w.copy_value(vstart, out)
+ })?
+ };
+ if !stashes.is_empty() {
+ // `end` emission just closed with '}'; reopen to append the stash members.
+ debug_assert_eq!(out.last(), Some(&b'}'));
+ out.pop();
+ for (name, value) in stashes {
+ if out.last() != Some(&b'{') {
+ out.push(b',');
+ }
+ scan::write_json_string(&name, out);
+ out.push(b':');
+ scan::write_json_string(&value, out);
+ }
+ out.push(b'}');
+ }
+ Some(end)
+ }
+
+ /// One media source attribute (mirrors `assets::apply_blur` for a single key): data images are
+ /// blurred; remote URLs become the placeholder with the host-scrubbed original stashed.
+ fn blur_media_src(
+ &mut self,
+ name: &str,
+ vstart: usize,
+ out: &mut Vec<u8>,
+ stashes: &mut Vec<(String, String)>,
+ ) -> Option<usize> {
+ let bytes = self.bytes;
+ if bytes.get(vstart) != Some(&b'"') {
+ // Non-string media source: apply_blur skips it.
+ return self.copy_value(vstart, out);
+ }
+ let end = scan::skip_string(bytes, vstart).ok()?;
+ let existing = scan::unescape(bytes, (vstart, end)).ok()?;
+ if is_image_data_uri(&existing) {
+ let blurred = self
+ .ctx
+ .blur_data_uri(&existing)
+ .unwrap_or_else(|| PLACEHOLDER_SRC.to_string());
+ scan::write_json_string(&blurred, out);
+ } else {
+ let scrubbed = scrub_url_opts(self.ctx.allow, &existing, true)
+ .unwrap_or_else(|| existing.into_owned());
+ scan::write_json_string(PLACEHOLDER_SRC, out);
+ stashes.push((format!("data-anon-original-{name}"), scrubbed));
+ }
+ self.changed = true;
+ Some(end)
+ }
+
+ /// Mutation `texts`: `[{ id, value }]` — scrub each `value` (mirrors `scrub_mutation_texts`).
+ fn walk_texts(&mut self, start: usize, out: &mut Vec<u8>) -> Option<usize> {
+ self.walk_array(start, out, &mut |w, pos, out| {
+ if w.bytes.get(pos) != Some(&b'{') {
+ return w.copy_value(pos, out);
+ }
+ w.walk_object(
+ pos,
+ out,
+ &mut |w, key, vstart, out| match &w.bytes[key.0..key.1] {
+ b"value" => {
+ w.scrub_string_value(vstart, out, |w, s| scrub_text(w.ctx.allow, s))
+ }
+ _ => w.copy_value(vstart, out),
+ },
+ )
+ })
+ }
+
+ /// Mutation `attributes`: `[{ id, attributes: {...} }]` (mirrors `scrub_mutation_attributes` —
+ /// the media decision comes from the attr names, there is no tag here).
+ fn walk_mutation_attributes(&mut self, start: usize, out: &mut Vec<u8>) -> Option<usize> {
+ self.walk_array(start, out, &mut |w, pos, out| {
+ if w.bytes.get(pos) != Some(&b'{') {
+ return w.copy_value(pos, out);
+ }
+ w.walk_object(
+ pos,
+ out,
+ &mut |w, key, vstart, out| match &w.bytes[key.0..key.1] {
+ b"attributes" if w.bytes.get(vstart) == Some(&b'{') => {
+ // `find_member`'s `Err(Fallback)` (prescan budget / structural surprise)
+ // must decline to the parse, not silently classify as non-media.
+ let mut is_media = false;
+ for a in MEDIA_SRC_ATTRS {
+ if w.find_member(vstart, a.as_bytes()).ok()?.is_some() {
+ is_media = true;
+ break;
+ }
+ }
+ let kind = if is_media {
+ TagKind::Media
+ } else {
+ TagKind::Other
+ };
+ w.walk_attrs(vstart, kind, out)
+ }
+ _ => w.copy_value(vstart, out),
+ },
+ )
+ })
+ }
+
+ /// One cv-marked mutation sub-field from the wire: a gzipped string is decoded/walked, a plain
+ /// array walks uncompressed, `null`/empty-string keep verbatim, anything else declines.
+ fn walk_cv_sub(
+ &mut self,
+ field: CvMutationField,
+ vstart: usize,
+ out: &mut Vec<u8>,
+ ) -> Option<usize> {
+ match self.bytes.get(vstart)? {
+ b'[' => match field {
+ CvMutationField::Texts => self.walk_texts(vstart, out),
+ CvMutationField::Attributes => self.walk_mutation_attributes(vstart, out),
+ CvMutationField::Adds => self.walk_adds(vstart, out),
+ },
+ b'n' => self.copy_value(vstart, out),
+ b'"' => {
+ let send = scan::skip_string(self.bytes, vstart).ok()?;
+ let wire = &self.bytes[vstart + 1..send - 1];
+ if wire.is_empty() {
+ out.extend_from_slice(&self.bytes[vstart..send]);
+ return Some(send);
+ }
+ let raw = latin1_from_wire(wire)?;
+ let decompressed = self.ctx.gunzip_cv(&raw).ok()?;
+ let mut walked = Vec::with_capacity(decompressed.len() + 64);
+ let content =
+ if scrub_cv_mutation_field(self.ctx, field, &decompressed, &mut walked)? {
+ &walked
+ } else {
+ &decompressed
+ };
+ let zs = crate::gzip::compress_cv(content).ok()?;
+ write_latin1_json_string(&zs, out);
+ self.changed = true;
+ Some(send)
+ }
+ _ => None,
+ }
+ }
+
+ /// Mutation `adds`: `[{ parentId, nextId, node }]` (mirrors `scrub_mutation_adds`).
+ fn walk_adds(&mut self, start: usize, out: &mut Vec<u8>) -> Option<usize> {
+ self.walk_array(start, out, &mut |w, pos, out| {
+ if w.bytes.get(pos) != Some(&b'{') {
+ return w.copy_value(pos, out);
+ }
+ w.walk_object(
+ pos,
+ out,
+ &mut |w, key, vstart, out| match &w.bytes[key.0..key.1] {
+ b"node" => w.walk_node(vstart, ParentKind::Other, out),
+ _ => w.copy_value(vstart, out),
+ },
+ )
+ })
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::{latin1_from_wire, write_latin1_json_string};
+
+ #[test]
+ fn latin1_wire_codec_round_trips_every_byte() {
+ let all: Vec<u8> = (0..=255).collect();
+ let mut wire = Vec::new();
+ write_latin1_json_string(&all, &mut wire);
+ // Strip the quotes the writer adds; the decoder takes the inner span.
+ let decoded = latin1_from_wire(&wire[1..wire.len() - 1]).expect("own output decodes");
+ assert_eq!(decoded, all);
+ }
+
+ #[test]
+ fn latin1_wire_decoder_declines_non_latin1() {
+ // Codepoint > 0xFF, escaped and raw.
+ assert!(latin1_from_wire(br"\u0100").is_none());
+ assert!(latin1_from_wire("π".as_bytes()).is_none());
+ // Raw control byte: invalid JSON, the parse path must be the one to reject it.
+ assert!(latin1_from_wire(b"\x1f").is_none());
+ // Truncated escape and truncated two-byte sequence.
+ assert!(latin1_from_wire(br"\u00").is_none());
+ assert!(latin1_from_wire(b"\xc2").is_none());
+ }
+}
diff --git a/rust/replay-anonymizer-node/src/canvas.rs b/rust/replay-anonymizer-node/src/canvas.rs
new file mode 100644
index 000000000000..492b4e3ebed1
--- /dev/null
+++ b/rust/replay-anonymizer-node/src/canvas.rs
@@ -0,0 +1,467 @@
+//! 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).
+
+use base64::Engine;
+use simd_json::borrowed::{Object, Value};
+
+use crate::blur::{blank_image_data_uri, is_image_data_uri, split_data_uri, BLANK_PNG_BASE64};
+use crate::context::Ctx;
+use crate::json::{
+ as_array, as_array_mut, as_object, as_object_mut, as_str, as_u32, as_usize, key, string_value,
+};
+use crate::url::scrub_url;
+
+fn b64() -> base64::engine::general_purpose::GeneralPurpose {
+ base64::engine::general_purpose::STANDARD
+}
+
+/// Scrub a CanvasMutation `data` object in place. Returns whether anything changed.
+pub fn scrub_canvas_mutation(ctx: &Ctx<'_>, data: &mut Value<'_>) -> bool {
+ let Some(obj) = as_object_mut(data) else {
+ return false;
+ };
+ let has_commands = matches!(obj.get("commands"), Some(Value::Array(_)));
+ if has_commands {
+ let mut changed = false;
+ let commands = obj.get_mut("commands").and_then(as_array_mut).unwrap();
+ for cmd in commands.iter_mut() {
+ if let Some(c) = as_object_mut(cmd) {
+ changed |= scrub_command(ctx, c);
+ }
+ }
+ changed
+ } else if obj.get("property").and_then(as_str).is_some() {
+ // Flattened single-command form: `data` itself is the command.
+ scrub_command(ctx, obj)
+ } else {
+ false
+ }
+}
+
+// Canvas API calls whose leading string arguments are user-visible text.
+fn is_text_command(property: &str) -> bool {
+ matches!(property, "fillText" | "strokeText")
+}
+
+fn scrub_command(ctx: &Ctx<'_>, cmd: &mut Object<'_>) -> bool {
+ let is_text = cmd
+ .get("property")
+ .and_then(as_str)
+ .map(is_text_command)
+ .unwrap_or(false);
+ let Some(args) = cmd.get_mut("args").and_then(as_array_mut) else {
+ return false;
+ };
+ let mut changed = false;
+
+ // Text drawn onto the canvas: fillText/strokeText take the text as leading string args.
+ if is_text {
+ for a in args.iter_mut() {
+ if let Value::String(s) = a {
+ if let Some(nv) = crate::text::scrub_text(ctx.allow, s) {
+ *a = string_value(nv);
+ changed = true;
+ }
+ }
+ }
+ }
+
+ // Images/snapshots can appear anywhere in the (recursive) arg tree.
+ for a in args.iter_mut() {
+ changed |= blur_canvas_arg(ctx, a);
+ }
+ changed
+}
+
+/// Recursively neutralize+blur image data inside a canvas arg, mutating in place.
+fn blur_canvas_arg(ctx: &Ctx<'_>, value: &mut Value<'_>) -> bool {
+ match value {
+ Value::String(s) => {
+ if is_image_data_uri(s) {
+ let b = ctx.blur_data_uri(s).unwrap_or_else(blank_image_data_uri);
+ *value = string_value(b);
+ return true;
+ }
+ return false;
+ }
+ Value::Array(arr) => {
+ let mut changed = false;
+ for item in arr.iter_mut() {
+ changed |= blur_canvas_arg(ctx, item);
+ }
+ return changed;
+ }
+ _ => {}
+ }
+
+ let Some(obj) = as_object_mut(value) else {
+ 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 let Some(src) = obj.get("src").and_then(as_str).map(str::to_string) {
+ if is_image_data_uri(&src) {
+ let b = ctx.blur_data_uri(&src).unwrap_or_else(blank_image_data_uri);
+ obj.insert(key("src"), string_value(b));
+ return true;
+ }
+ return match scrub_url(ctx.allow, &src) {
+ Some(v) => {
+ obj.insert(key("src"), string_value(v));
+ true
+ }
+ None => false,
+ };
+ }
+
+ let rr_type = obj.get("rr_type").and_then(as_str).map(str::to_string);
+
+ // Encoded image snapshot: { rr_type: 'Blob', type: 'image/...', data: [ {rr_type:'ArrayBuffer', base64} ] }.
+ if rr_type.as_deref() == Some("Blob") {
+ if let Some(t) = obj.get("type").and_then(as_str) {
+ if t.starts_with("image/") {
+ return blur_blob_image(ctx, obj);
+ }
+ }
+ }
+
+ // Raw pixels: { rr_type: 'ImageData', args: [pixels, width, height] } (putImageData).
+ if rr_type.as_deref() == Some("ImageData") {
+ return blur_image_data(ctx, obj);
+ }
+
+ // Otherwise recurse into nested arg/data arrays (ImageBitmap -> Blob, etc.).
+ let mut changed = false;
+ if let Some(args) = obj.get_mut("args").and_then(as_array_mut) {
+ for it in args.iter_mut() {
+ changed |= blur_canvas_arg(ctx, it);
+ }
+ }
+ if let Some(data) = obj.get_mut("data").and_then(as_array_mut) {
+ for it in data.iter_mut() {
+ changed |= blur_canvas_arg(ctx, it);
+ }
+ }
+ changed
+}
+
+/// Blur the encoded image bytes inside an image Blob, neutralizing them first (fail-safe).
+fn blur_blob_image(ctx: &Ctx<'_>, blob: &mut Object<'_>) -> bool {
+ let mime = blob
+ .get("type")
+ .and_then(as_str)
+ .unwrap_or("image/png")
+ .to_string();
+ let Some(idx) = find_array_buffer_index(blob) else {
+ return false;
+ };
+ let base64 = match blob
+ .get("data")
+ .and_then(as_array)
+ .and_then(|d| d.get(idx))
+ .and_then(as_object)
+ .and_then(|o| o.get("base64"))
+ .and_then(as_str)
+ {
+ Some(s) => s.to_string(),
+ None => return false,
+ };
+ let original = format!("data:{mime};base64,{base64}");
+ let (new_b64, new_type) = match ctx
+ .blur_data_uri(&original)
+ .and_then(|b| split_data_uri(&b))
+ {
+ Some((m, b64)) => (b64, m),
+ // Fail-safe: a blank pixel (matches the TS synchronous neutralization).
+ None => (BLANK_PNG_BASE64.to_string(), "image/png".to_string()),
+ };
+ if let Some(ab) = blob
+ .get_mut("data")
+ .and_then(as_array_mut)
+ .and_then(|d| d.get_mut(idx))
+ .and_then(as_object_mut)
+ {
+ ab.insert(key("base64"), string_value(new_b64));
+ }
+ blob.insert(key("type"), string_value(new_type));
+ true
+}
+
+fn find_array_buffer_index(blob: &Object<'_>) -> Option<usize> {
+ blob.get("data").and_then(as_array).and_then(|data| {
+ data.iter().position(|d| {
+ as_object(d)
+ .map(|o| {
+ o.get("rr_type").and_then(as_str) == Some("ArrayBuffer")
+ && o.get("base64").and_then(as_str).is_some()
+ })
+ .unwrap_or(false)
+ })
+ })
+}
+
+/// Pixelate raw ImageData pixels in place (blanked, with the downsampled-and-restored region merged
+/// back in on success). Falls back to blanking every nested ArrayBuffer for an unexpected shape.
+fn blur_image_data<'v>(ctx: &Ctx<'_>, image_data: &mut Object<'v>) -> bool {
+ let width = image_data
+ .get("args")
+ .and_then(as_array)
+ .and_then(|a| a.get(1))
+ .and_then(as_u32);
+ let height = image_data
+ .get("args")
+ .and_then(as_array)
+ .and_then(|a| a.get(2))
+ .and_then(as_u32);
+ if let (Some(w), Some(h)) = (width, height) {
+ if w > 0 && h > 0 && pixelate_image_data_arg(ctx, image_data, w, h) {
+ return true;
+ }
+ }
+ // Unexpected shape — guarantee no raw-pixel leak by blanking every nested ArrayBuffer.
+ let mut v: Value<'v> = Value::Object(Box::new(std::mem::take(image_data)));
+ let changed = blank_array_buffers(&mut v);
+ if let Value::Object(o) = v {
+ *image_data = *o;
+ }
+ changed
+}
+
+/// Locate the RGBA ArrayBuffer behind an ImageData's pixel descriptor (direct or typed-array-wrapped),
+/// blank it and merge the pixelated region back. Returns whether it handled the pixels.
+fn pixelate_image_data_arg(ctx: &Ctx<'_>, image_data: &mut Object<'_>, w: u32, h: u32) -> bool {
+ // `checked_mul`: `w*h*4` on attacker-controlled dims can overflow usize; overflow -> no match.
+ let Some(expected) = (w as usize)
+ .checked_mul(h as usize)
+ .and_then(|wh| wh.checked_mul(4))
+ else {
+ return false;
+ };
+
+ // Shape A: args[0] is the ArrayBuffer directly.
+ let direct = image_data
+ .get("args")
+ .and_then(as_array)
+ .and_then(|a| a.first())
+ .and_then(as_object)
+ .map(|o| {
+ o.get("rr_type").and_then(as_str) == Some("ArrayBuffer")
+ && o.get("base64").and_then(as_str).is_some()
+ })
+ .unwrap_or(false);
+ if direct {
+ if let Some(ab) = image_data
+ .get_mut("args")
+ .and_then(as_array_mut)
+ .and_then(|a| a.first_mut())
+ .and_then(as_object_mut)
+ {
+ return process_raw_buffer(ctx, ab, 0, None, w, h, expected);
+ }
+ }
+
+ // Shape B: typed-array wrapper { args: [ {ArrayBuffer}, byteOffset?, length? ] }.
+ let (start, length_opt, wrapped) = {
+ let inner = image_data
+ .get("args")
+ .and_then(as_array)
+ .and_then(|a| a.first())
+ .and_then(as_object)
+ .and_then(|o| o.get("args"))
+ .and_then(as_array);
+ match inner {
+ Some(args) => {
+ let is_ab = args
+ .first()
+ .and_then(as_object)
+ .map(|o| {
+ o.get("rr_type").and_then(as_str) == Some("ArrayBuffer")
+ && o.get("base64").and_then(as_str).is_some()
+ })
+ .unwrap_or(false);
+ (
+ args.get(1).and_then(as_usize).unwrap_or(0),
+ args.get(2).and_then(as_usize),
+ is_ab,
+ )
+ }
+ None => (0, None, false),
+ }
+ };
+ if wrapped {
+ if let Some(ab) = image_data
+ .get_mut("args")
+ .and_then(as_array_mut)
+ .and_then(|a| a.first_mut())
+ .and_then(as_object_mut)
+ .and_then(|o| o.get_mut("args"))
+ .and_then(as_array_mut)
+ .and_then(|a| a.first_mut())
+ .and_then(as_object_mut)
+ {
+ return process_raw_buffer(ctx, ab, start, length_opt, w, h, expected);
+ }
+ }
+ false
+}
+
+fn process_raw_buffer(
+ ctx: &Ctx<'_>,
+ ab: &mut Object<'_>,
+ start: usize,
+ length_opt: Option<usize>,
+ w: u32,
+ h: u32,
+ expected: usize,
+) -> bool {
+ let Some(base64) = ab.get("base64").and_then(as_str).map(str::to_string) else {
+ return false;
+ };
+ let Ok(full) = b64().decode(base64.as_bytes()) else {
+ return false;
+ };
+ let length = length_opt.unwrap_or_else(|| full.len().saturating_sub(start));
+ // `start`/`length` come from untrusted JSON numbers; guard against overflow (release builds don't
+ // check arithmetic) so a crafted pair can't produce a reversed/out-of-range slice panic.
+ let Some(end) = start.checked_add(length) else {
+ return false;
+ };
+ if length != expected || end > full.len() {
+ return false;
+ }
+ let rgba = b64().encode(&full[start..end]);
+ let mut merged = full.clone();
+ for b in &mut merged[start..end] {
+ *b = 0;
+ }
+ if let Some(pix) = ctx.pixelate_raw(&rgba, w, h) {
+ if let Ok(outbuf) = b64().decode(pix.as_bytes()) {
+ if outbuf.len() == length {
+ merged[start..end].copy_from_slice(&outbuf);
+ }
+ }
+ }
+ ab.insert(key("base64"), string_value(b64().encode(&merged)));
+ true
+}
+
+/// Zero out every nested `{rr_type:'ArrayBuffer', base64}` (same byte length). Last-resort fail-safe.
+fn blank_array_buffers(node: &mut Value<'_>) -> bool {
+ match node {
+ Value::Array(arr) => {
+ let mut changed = false;
+ for item in arr.iter_mut() {
+ changed |= blank_array_buffers(item);
+ }
+ changed
+ }
+ Value::Object(obj) => {
+ if obj.get("rr_type").and_then(as_str) == Some("ArrayBuffer") {
+ if let Some(base64) = obj.get("base64").and_then(as_str) {
+ let len = b64()
+ .decode(base64.as_bytes())
+ .map(|b| b.len())
+ .unwrap_or(0);
+ let zeros = b64().encode(vec![0u8; len]);
+ obj.insert(key("base64"), string_value(zeros));
+ return true;
+ }
+ }
+ let mut changed = false;
+ for (_, val) in obj.iter_mut() {
+ changed |= blank_array_buffers(val);
+ }
+ changed
+ }
+ _ => false,
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use crate::allow_lists::AllowLists;
+ use crate::context::Ctx;
+ use crate::testkit::{png_base64, png_data_uri, rgba_base64};
+ use base64::Engine;
+ use simd_json::prelude::Writable;
+
+ // Scrub a CanvasMutation `data` JSON string and return the result as a serde_json Value.
+ fn scrub(data_json: &str) -> serde_json::Value {
+ let allow = AllowLists::new(Vec::<String>::new(), Vec::<String>::new());
+ let ctx = Ctx::new(&allow);
+ let mut bytes = data_json.as_bytes().to_vec();
+ let mut data = simd_json::to_borrowed_value(&mut bytes).unwrap();
+ scrub_canvas_mutation(&ctx, &mut data);
+ serde_json::from_str(&data.encode()).unwrap()
+ }
+
+ fn decode(b64: &str) -> Vec<u8> {
+ b64_engine().decode(b64).unwrap()
+ }
+ fn b64_engine() -> base64::engine::general_purpose::GeneralPurpose {
+ base64::engine::general_purpose::STANDARD
+ }
+
+ #[test]
+ fn image_element_data_uri_src_is_neutralized() {
+ let uri = png_data_uri(8, 8, [200, 10, 10, 255]);
+ let out = scrub(&format!(
+ r#"{{"source":9,"id":1,"type":0,"commands":[{{"property":"drawImage","args":[{{"rr_type":"HTMLImageElement","src":"{uri}"}}]}}]}}"#
+ ));
+ let src = out["commands"][0]["args"][0]["src"].as_str().unwrap();
+ assert!(src.starts_with("data:image/"), "still an image: {src}");
+ assert_ne!(src, uri, "raw image must not pass through");
+ }
+
+ #[test]
+ fn blob_image_bytes_are_neutralized() {
+ let b64 = png_base64(8, 8, [10, 200, 10, 255]);
+ let out = scrub(&format!(
+ r#"{{"source":9,"id":1,"type":0,"commands":[{{"property":"drawImage","args":[{{"rr_type":"Blob","type":"image/png","data":[{{"rr_type":"ArrayBuffer","base64":"{b64}"}}]}}]}}]}}"#
+ ));
+ let new_b64 = out["commands"][0]["args"][0]["data"][0]["base64"]
+ .as_str()
+ .unwrap();
+ assert_ne!(new_b64, b64, "raw blob bytes must not pass through");
+ }
+
+ #[test]
+ fn image_data_raw_pixels_are_pixelated_preserving_length() {
+ let (w, h) = (8u32, 8u32);
+ let rgba = rgba_base64(w, h);
+ let out = scrub(&format!(
+ r#"{{"source":9,"id":1,"type":0,"commands":[{{"property":"putImageData","args":[{{"rr_type":"ImageData","args":[{{"rr_type":"ArrayBuffer","base64":"{rgba}"}},{w},{h}]}}]}}]}}"#
+ ));
+ let new_b64 = out["commands"][0]["args"][0]["args"][0]["base64"]
+ .as_str()
+ .unwrap();
+ assert_ne!(new_b64, rgba, "raw pixels must not pass through");
+ assert_eq!(
+ decode(new_b64).len(),
+ (w * h * 4) as usize,
+ "byte length preserved"
+ );
+ }
+
+ #[test]
+ fn malformed_image_data_blanks_the_array_buffer() {
+ // 4x4 buffer (64 bytes) but claims 8x8 (256 expected) → the raw-pixel path bails and the
+ // fail-safe zeroes every nested ArrayBuffer rather than shipping the pixels.
+ let rgba = rgba_base64(4, 4);
+ let out = scrub(&format!(
+ r#"{{"source":9,"id":1,"type":0,"commands":[{{"property":"putImageData","args":[{{"rr_type":"ImageData","args":[{{"rr_type":"ArrayBuffer","base64":"{rgba}"}},8,8]}}]}}]}}"#
+ ));
+ let new_b64 = out["commands"][0]["args"][0]["args"][0]["base64"]
+ .as_str()
+ .unwrap();
+ let bytes = decode(new_b64);
+ assert_eq!(bytes.len(), decode(&rgba).len(), "byte length preserved");
+ assert!(
+ bytes.iter().all(|&b| b == 0),
+ "unhandled shape must be blanked"
+ );
+ }
+}
diff --git a/rust/replay-anonymizer-node/src/context.rs b/rust/replay-anonymizer-node/src/context.rs
new file mode 100644
index 000000000000..6ca1a3297972
--- /dev/null
+++ b/rust/replay-anonymizer-node/src/context.rs
@@ -0,0 +1,91 @@
+//! Per-message scrub context: the allow lists plus a blur memo.
+//!
+//! Within one Kafka message the same image often recurs thousands of times (a canvas redrawing one
+//! sprite, a repeated background). Blurring is pure in its input, so we memoize it per message and
+//! collapse that fan-out to a single decode+blur — mirroring the TS `blurCache` (also scoped to one
+//! message). Scope is one `anonymize_message` call; the map is dropped when it returns.
+
+use std::cell::{Cell, RefCell};
+use std::collections::HashMap;
+
+use anyhow::{bail, Result};
+
+use crate::allow_lists::AllowLists;
+use crate::blur::{blur_image_data_uri, pixelate_raw_rgba};
+
+/// Cumulative decompressed-bytes budget across all cv payloads in one message: the per-payload
+/// `gzip::MAX_DECOMPRESSED_BYTES` cap bounds each field, this bounds their sum so many high-ratio
+/// fields can't decompress gigabytes serially. Real messages total under 10 MB.
+const CV_MESSAGE_DECOMPRESSION_BUDGET: usize = 256 * 1024 * 1024;
+
+pub struct Ctx<'a> {
+ pub allow: &'a AllowLists,
+ pub cv_budget: Cell<usize>,
+ // key: the original data URI (data-image blur), or `raw:{w}x{h}:{base64}` (raw RGBA pixelate).
+ // value: the blurred result, or `None` when blurring failed (caller falls back to a blank pixel).
+ blur_cache: RefCell<HashMap<String, Option<String>>>,
+}
+
+impl<'a> Ctx<'a> {
+ pub fn new(allow: &'a AllowLists) -> Self {
+ Self {
+ allow,
+ cv_budget: Cell::new(CV_MESSAGE_DECOMPRESSION_BUDGET),
+ blur_cache: RefCell::new(HashMap::new()),
+ }
+ }
+
+ /// The only budgeted cv decompression path — cv code must not call `gzip::gunzip` directly.
+ pub fn gunzip_cv(&self, raw: &[u8]) -> Result<Vec<u8>> {
+ let out = crate::gzip::gunzip(raw)?;
+ match self.cv_budget.get().checked_sub(out.len()) {
+ Some(rest) => self.cv_budget.set(rest),
+ None => bail!("message exceeds the cumulative cv decompression budget"),
+ }
+ Ok(out)
+ }
+
+ // Borrow discipline: never hold a `blur_cache` borrow across the blur call — the compute runs
+ // borrow-free, so a future blur helper that re-entered `Ctx` still couldn't double-borrow-panic.
+
+ /// Blur a data-image URI, memoized on the URI. `None` → caller falls back to a blank/placeholder.
+ pub fn blur_data_uri(&self, original: &str) -> Option<String> {
+ if let Some(hit) = self.blur_cache.borrow().get(original) {
+ return hit.clone();
+ }
+ let result = blur_image_data_uri(original);
+ self.blur_cache
+ .borrow_mut()
+ .insert(original.to_string(), result.clone());
+ result
+ }
+
+ /// Pixelate raw RGBA pixels, memoized on dimensions + bytes.
+ pub fn pixelate_raw(&self, rgba_base64: &str, width: u32, height: u32) -> Option<String> {
+ let key = format!("raw:{width}x{height}:{rgba_base64}");
+ if let Some(hit) = self.blur_cache.borrow().get(&key) {
+ return hit.clone();
+ }
+ let result = pixelate_raw_rgba(rgba_base64, width, height);
+ self.blur_cache.borrow_mut().insert(key, result.clone());
+ result
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use crate::testkit::png_data_uri;
+
+ #[test]
+ fn blur_memo_is_stable_and_keyed_per_image() {
+ let allow = AllowLists::new(Vec::<String>::new(), Vec::<String>::new());
+ let ctx = Ctx::new(&allow);
+ let a = png_data_uri(100, 50, [10, 20, 30, 255]);
+ let b = png_data_uri(40, 40, [200, 100, 50, 255]);
+ // Same input → same result twice (a cache hit must not return something different).
+ assert_eq!(ctx.blur_data_uri(&a), ctx.blur_data_uri(&a));
+ // Distinct inputs → distinct results (guards against a cache-key collision serving A's blur for B).
+ assert_ne!(ctx.blur_data_uri(&a), ctx.blur_data_uri(&b));
+ }
+}
diff --git a/rust/replay-anonymizer-node/src/css.rs b/rust/replay-anonymizer-node/src/css.rs
new file mode 100644
index 000000000000..6083c65f6765
--- /dev/null
+++ b/rust/replay-anonymizer-node/src/css.rs
@@ -0,0 +1,157 @@
+//! 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".
+
+use std::borrow::Cow;
+
+use simd_json::borrowed::Object;
+
+use crate::blur::{blank_image_data_uri, is_image_data_uri};
+use crate::context::Ctx;
+use crate::json::{as_str, string_value};
+
+/// Scrub `container[key]` if it is a CSS string; returns whether it changed.
+pub fn scrub_css_images(ctx: &Ctx<'_>, container: &mut Object<'_>, key: &str) -> bool {
+ let Some(css) = container.get(key).and_then(as_str).map(str::to_string) else {
+ return false;
+ };
+ match rewrite(ctx, &css) {
+ Some(v) => {
+ container.insert(Cow::Owned(key.to_string()), string_value(v));
+ true
+ }
+ None => false,
+ }
+}
+
+pub(crate) fn rewrite(ctx: &Ctx<'_>, css: &str) -> Option<String> {
+ let bytes = css.as_bytes();
+ let mut out = String::new();
+ let mut last = 0usize;
+ let mut i = 0usize;
+ let mut changed = false;
+ while let Some(start) = find_url_open(bytes, i) {
+ if let Some(m) = parse_url_data_image(bytes, start) {
+ out.push_str(&css[last..start]);
+ // Blur (or fall back to a blank pixel) and re-wrap; no async placeholder needed since we
+ // resolve the image inline, so the final string matches the TS post-blur state.
+ let replacement = ctx
+ .blur_data_uri(&css[m.data_start..m.data_end])
+ .unwrap_or_else(blank_image_data_uri);
+ out.push_str("url(");
+ if let Some(q) = m.quote {
+ out.push(q as char);
+ }
+ out.push_str(&replacement);
+ if let Some(q) = m.quote {
+ out.push(q as char);
+ }
+ out.push(')');
+ last = m.end;
+ i = m.end;
+ changed = true;
+ } else {
+ i = start + 1;
+ }
+ }
+ if !changed {
+ return None;
+ }
+ out.push_str(&css[last..]);
+ Some(out)
+}
+
+struct Match {
+ end: usize,
+ quote: Option<u8>,
+ data_start: usize,
+ data_end: usize,
+}
+
+fn find_url_open(bytes: &[u8], from: usize) -> Option<usize> {
+ let mut i = from;
+ while i + 4 <= bytes.len() {
+ if bytes[i].eq_ignore_ascii_case(&b'u')
+ && bytes[i + 1].eq_ignore_ascii_case(&b'r')
+ && bytes[i + 2].eq_ignore_ascii_case(&b'l')
+ && bytes[i + 3] == b'('
+ {
+ return Some(i);
+ }
+ i += 1;
+ }
+ None
+}
+
+fn parse_url_data_image(bytes: &[u8], start: usize) -> Option<Match> {
+ let mut pos = start + 4; // past "url("
+ skip_ws(bytes, &mut pos);
+ let quote = match bytes.get(pos) {
+ Some(&c) if c == b'\'' || c == b'"' => {
+ pos += 1;
+ Some(c)
+ }
+ _ => None,
+ };
+ let data_start = pos;
+ if !starts_with_ci(bytes, pos, b"data:image/") {
+ return None;
+ }
+ pos += b"data:image/".len();
+ // subtype: [a-z0-9.+-]+ (case-insensitive)
+ let subtype_start = pos;
+ while matches!(bytes.get(pos), Some(&c) if c.is_ascii_alphanumeric() || matches!(c, b'.' | b'+' | b'-'))
+ {
+ pos += 1;
+ }
+ if pos == subtype_start {
+ return None;
+ }
+ if !starts_with_ci(bytes, pos, b";base64,") {
+ return None;
+ }
+ pos += b";base64,".len();
+ // base64 body: [A-Za-z0-9+/=]+
+ let b64_start = pos;
+ while matches!(bytes.get(pos), Some(&c) if c.is_ascii_alphanumeric() || matches!(c, b'+' | b'/' | b'='))
+ {
+ pos += 1;
+ }
+ if pos == b64_start {
+ return None;
+ }
+ let data_end = pos;
+ if let Some(q) = quote {
+ if bytes.get(pos) != Some(&q) {
+ return None;
+ }
+ pos += 1;
+ }
+ skip_ws(bytes, &mut pos);
+ if bytes.get(pos) != Some(&b')') {
+ return None;
+ }
+ pos += 1;
+ // Only images (data URIs); guaranteed by the `data:image/` prefix above.
+ debug_assert!(is_image_data_uri(
+ std::str::from_utf8(&bytes[data_start..data_end]).unwrap_or("")
+ ));
+ Some(Match {
+ end: pos,
+ quote,
+ data_start,
+ data_end,
+ })
+}
+
+fn skip_ws(bytes: &[u8], pos: &mut usize) {
+ while matches!(bytes.get(*pos), Some(&c) if c.is_ascii_whitespace() || c == 0x0b) {
+ *pos += 1;
+ }
+}
+
+fn starts_with_ci(bytes: &[u8], pos: usize, needle: &[u8]) -> bool {
+ bytes
+ .get(pos..pos + needle.len())
+ .is_some_and(|s| s.eq_ignore_ascii_case(needle))
+}
diff --git a/rust/replay-anonymizer-node/src/cv.rs b/rust/replay-anonymizer-node/src/cv.rs
new file mode 100644
index 000000000000..251f2fe0a192
--- /dev/null
+++ b/rust/replay-anonymizer-node/src/cv.rs
@@ -0,0 +1,392 @@
+//! 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};
+use simd_json::prelude::Writable;
+use simd_json::StaticNode;
+
+use crate::bytewalk;
+use crate::context::Ctx;
+use crate::dom::{
+ scrub_full_snapshot, scrub_mutation_adds, scrub_mutation_attributes, scrub_mutation_texts,
+};
+use crate::gzip;
+use crate::json::{as_array_mut, key, parse_untrusted, reject_if_too_deep, string_value};
+
+/// PostHog wire format: each gzip byte stored as its U+00XX codepoint (latin-1). Per-char is
+/// deliberate — a hand-rolled byte loop measured slower than `chars()` on high-entropy gzip bytes.
+/// The structural win is decoding off the escaped wire span (`bytewalk::latin1_from_wire`) instead.
+fn latin1_to_bytes(s: &str) -> Result<Vec<u8>> {
+ let mut out = Vec::with_capacity(s.len());
+ for c in s.chars() {
+ let cp = c as u32;
+ if cp > 0xFF {
+ bail!("codepoint U+{cp:04X} > 0xFF in latin-1 gzip stream");
+ }
+ out.push(cp as u8);
+ }
+ Ok(out)
+}
+
+fn bytes_to_latin1(bytes: &[u8]) -> String {
+ // Exact presize: one two-byte UTF-8 sequence per byte >= 0x80 (the count pass vectorizes).
+ let extra = bytes.iter().filter(|&&b| b >= 0x80).count();
+ let mut out = String::with_capacity(bytes.len() + extra);
+ for &b in bytes {
+ out.push(b as char);
+ }
+ out
+}
+
+/// Not depth-guarded: the byte walk that consumes the result self-bounds its recursion, so the
+/// whole-buffer depth scan (~6% of the pipeline) runs only in front of the parse fallbacks below.
+fn decompress_string(ctx: &Ctx<'_>, s: &str) -> Result<Vec<u8>> {
+ let raw = latin1_to_bytes(s)?;
+ ctx.gunzip_cv(&raw).context("gunzip cv data")
+}
+
+fn compress_bytes(json: &[u8]) -> Result<String> {
+ Ok(bytes_to_latin1(
+ &gzip::compress_cv(json).context("compress cv payload")?,
+ ))
+}
+
+fn compress_value(value: &Value<'_>) -> Result<String> {
+ compress_bytes(value.encode().as_bytes())
+}
+
+/// Scrub a `cv`-compressed FullSnapshot `data` value (a gzipped latin-1 string) in place. Returns
+/// whether it changed. The caller has already checked the value is a string; non-string data routes
+/// through the plain scrub instead.
+pub fn scrub_compressed_full_snapshot(ctx: &Ctx<'_>, data: &mut Value<'_>) -> Result<bool> {
+ let Value::String(s) = &*data else {
+ bail!("compressed full snapshot data is not a string");
+ };
+ let mut scratch = decompress_string(ctx, s)?;
+ // Byte-walk first; fall through to the parse below on decline.
+ let mut walked = Vec::with_capacity(scratch.len() + 64);
+ match bytewalk::scrub_cv_snapshot(ctx, &scratch, &mut walked) {
+ // Unchanged payloads re-emit too: the whole output is zstd, never mixed-format blocks.
+ Some(false) => {
+ *data = string_value(compress_bytes(&scratch)?);
+ return Ok(true);
+ }
+ Some(true) => {
+ *data = string_value(compress_bytes(&walked)?);
+ return Ok(true);
+ }
+ None => {}
+ }
+ // The parse/tree path below recurses (the walk self-guarded), so guard here — a stack overflow
+ // aborts the worker, which catch_unwind can't contain.
+ reject_if_too_deep(&scratch, "cv payload")?;
+ let mut payload = parse_untrusted(&mut scratch).context("parse cv payload")?;
+ scrub_full_snapshot(ctx, &mut payload);
+ let recompressed = compress_value(&payload)?;
+ *data = string_value(recompressed);
+ Ok(true)
+}
+
+fn scrub_sub(ctx: &Ctx<'_>, sub_key: &str, arr: &mut Vec<Value<'_>>) -> bool {
+ match sub_key {
+ "texts" => scrub_mutation_texts(ctx, arr),
+ "attributes" => scrub_mutation_attributes(ctx, arr),
+ "adds" => scrub_mutation_adds(ctx, arr),
+ _ => unreachable!("unknown cv mutation sub-field"),
+ }
+}
+
+/// Scrub a `cv`-compressed Mutation `data` object in place. Returns whether it changed. Sub-fields
+/// arrive as gzipped strings or plain arrays; gzipped ones always re-emit as zstd (never
+/// mixed-format blocks), plain arrays scrub in place.
+pub fn scrub_compressed_mutation(ctx: &Ctx<'_>, data: &mut Object<'_>) -> Result<bool> {
+ const KEYS: [(&str, bytewalk::CvMutationField); 3] = [
+ ("texts", bytewalk::CvMutationField::Texts),
+ ("attributes", bytewalk::CvMutationField::Attributes),
+ ("adds", bytewalk::CvMutationField::Adds),
+ ];
+
+ let mut changed = false;
+ // Changed gzipped sub-fields: (key, scrubbed JSON bytes) to re-compress and write back below.
+ let mut recompress: Vec<(&'static str, Vec<u8>)> = Vec::new();
+
+ for (sub_key, field) in KEYS {
+ match data.get_mut(sub_key) {
+ None => {} // absent -> leave absent
+ Some(Value::Static(StaticNode::Null)) => {} // null -> keep verbatim
+ Some(Value::String(s)) if s.is_empty() => {} // empty string -> keep verbatim
+ Some(Value::String(s)) => {
+ let mut scratch = decompress_string(ctx, s)?;
+ let mut walked = Vec::with_capacity(scratch.len() + 64);
+ changed = true;
+ match bytewalk::scrub_cv_mutation_field(ctx, field, &scratch, &mut walked) {
+ Some(false) => recompress.push((sub_key, scratch)),
+ Some(true) => recompress.push((sub_key, walked)),
+ None => {
+ // As in the full-snapshot fallback: the parse recurses, the walk didn't.
+ reject_if_too_deep(&scratch, "cv mutation sub-field")?;
+ let mut decoded =
+ parse_untrusted(&mut scratch).context("parse cv mutation sub-field")?;
+ let Some(arr) = as_array_mut(&mut decoded) else {
+ // Fail closed: a decodable-but-non-array sub-field is malformed.
+ bail!("cv mutation sub-field did not decode to an array");
+ };
+ scrub_sub(ctx, sub_key, arr);
+ recompress.push((sub_key, decoded.encode().into_bytes()));
+ }
+ }
+ }
+ Some(v @ Value::Array(_)) => {
+ let arr = as_array_mut(v).expect("matched array");
+ changed |= scrub_sub(ctx, sub_key, arr);
+ }
+ Some(_) => bail!("cv mutation sub-field is neither a gzipped string nor an array"),
+ }
+ }
+
+ for (sub_key, json) in recompress {
+ data.insert(key(sub_key), string_value(compress_bytes(&json)?));
+ }
+
+ Ok(changed)
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use crate::allow_lists::AllowLists;
+ use crate::context::Ctx;
+ use crate::json::{as_array, as_object, as_str};
+ use std::borrow::Cow;
+
+ fn parse(json: &'static [u8]) -> Value<'static> {
+ simd_json::to_borrowed_value(Vec::leak(json.to_vec())).unwrap()
+ }
+
+ // Test inputs model what the SDK sends, which is always gzip.
+ fn compress_json(json: &[u8]) -> String {
+ bytes_to_latin1(&gzip::gzip(json).unwrap())
+ }
+
+ // Outputs are always zstd frames; assert the magic (the loader's dispatch contract) on decode.
+ fn decompress_value(s: &str) -> serde_json::Value {
+ let raw = latin1_to_bytes(s).unwrap();
+ assert_eq!(
+ &raw[..4],
+ &[0x28, 0xb5, 0x2f, 0xfd],
+ "output is a zstd frame"
+ );
+ serde_json::from_slice(&zstd::bulk::decompress(&raw, 1 << 24).unwrap()).unwrap()
+ }
+
+ #[test]
+ fn compressed_mutation_scrubs_and_re_compresses_subfields() {
+ let allow = AllowLists::new(["keep"], Vec::<String>::new());
+ let texts_gz = compress_json(br#"[{"id":5,"value":"keep secret"}]"#);
+
+ let mut data = Object::default();
+ data.insert(Cow::Borrowed("source"), Value::Static(StaticNode::U64(0)));
+ data.insert(Cow::Borrowed("texts"), string_value(texts_gz));
+
+ let ctx = Ctx::new(&allow);
+ let changed = scrub_compressed_mutation(&ctx, &mut data).unwrap();
+ assert!(changed);
+
+ let decoded = decompress_value(as_str(data.get("texts").unwrap()).unwrap());
+ assert_eq!(decoded[0]["value"], "keep ******");
+ // Absent sub-fields stay absent (not resurrected as empty).
+ assert!(!data.contains_key("attributes"));
+ assert!(!data.contains_key("adds"));
+ }
+
+ #[test]
+ fn compressed_full_snapshot_round_trips_and_scrubs() {
+ let allow = AllowLists::new(["keep"], Vec::<String>::new());
+ let ctx = Ctx::new(&allow);
+ let gz = compress_json(
+ br#"{"node":{"type":0,"childNodes":[{"type":3,"textContent":"keep secret"}]},"initialOffset":{"top":0,"left":0}}"#,
+ );
+ let mut data = string_value(gz);
+
+ assert!(scrub_compressed_full_snapshot(&ctx, &mut data).unwrap());
+
+ let decoded = decompress_value(as_str(&data).unwrap());
+ assert_eq!(
+ decoded["node"]["childNodes"][0]["textContent"],
+ "keep ******"
+ );
+ }
+
+ #[test]
+ fn every_gzipped_field_reemits_as_zstd() {
+ let allow = AllowLists::new(["keep"], Vec::<String>::new());
+ let ctx = Ctx::new(&allow);
+ let texts_gz = compress_json(br#"[{"id":5,"value":"keep secret"}]"#);
+ let adds_json = br#"[{"parentId":1,"nextId":null,"node":{"id":9,"type":2}}]"#;
+
+ let mut data = Object::default();
+ data.insert(Cow::Borrowed("source"), Value::Static(StaticNode::U64(0)));
+ data.insert(Cow::Borrowed("texts"), string_value(texts_gz));
+ data.insert(
+ Cow::Borrowed("adds"),
+ string_value(compress_json(adds_json)),
+ );
+
+ assert!(scrub_compressed_mutation(&ctx, &mut data).unwrap());
+
+ let unzstd = |key: &str| -> Vec<u8> {
+ let raw = latin1_to_bytes(as_str(data.get(key).unwrap()).unwrap()).unwrap();
+ // Single-format: every sub-field re-emits zstd, scrubbed or not.
+ assert_eq!(
+ &raw[..4],
+ &[0x28, 0xb5, 0x2f, 0xfd],
+ "{key} is a zstd frame"
+ );
+ zstd::bulk::decompress(&raw, 1 << 20).unwrap()
+ };
+ let texts: serde_json::Value = serde_json::from_slice(&unzstd("texts")).unwrap();
+ assert_eq!(texts[0]["value"], "keep ******");
+ // The untouched sub-field carries its original content, re-coded.
+ assert_eq!(unzstd("adds"), adds_json);
+ }
+
+ #[test]
+ fn compressed_mutation_with_escaped_keys_scrubs_via_parse_fallback() {
+ let allow = AllowLists::new(Vec::<String>::new(), Vec::<String>::new());
+ let ctx = Ctx::new(&allow);
+ // The `value` key's first byte is a \u escape: the byte walker declines escaped keys,
+ // so this only scrubs if the parse fallback still runs behind it.
+ let texts_gz = compress_json(br#"[{"id":5,"\u0076alue":"topsecret stuff"}]"#);
+
+ let mut data = Object::default();
+ data.insert(Cow::Borrowed("source"), Value::Static(StaticNode::U64(0)));
+ data.insert(Cow::Borrowed("texts"), string_value(texts_gz));
+
+ assert!(scrub_compressed_mutation(&ctx, &mut data).unwrap());
+ let texts = decompress_value(as_str(data.get("texts").unwrap()).unwrap());
+ assert_eq!(texts[0]["value"], "********* *****");
+ }
+
+ #[test]
+ fn compressed_full_snapshot_with_escaped_keys_scrubs_via_parse_fallback() {
+ let allow = AllowLists::new(Vec::<String>::new(), Vec::<String>::new());
+ let ctx = Ctx::new(&allow);
+ // The `textContent` key's first byte is a \u escape (see the mutation fallback test
+ // above).
+ let gz = compress_json(
+ br#"{"node":{"type":3,"\u0074extContent":"topsecret stuff"},"initialOffset":{"top":0,"left":0}}"#,
+ );
+ let mut data = string_value(gz);
+
+ assert!(scrub_compressed_full_snapshot(&ctx, &mut data).unwrap());
+ let decoded = decompress_value(as_str(&data).unwrap());
+ assert_eq!(decoded["node"]["textContent"], "********* *****");
+ }
+
+ #[test]
+ fn compressed_mutation_handles_a_plain_array_subfield() {
+ let allow = AllowLists::new(["keep"], Vec::<String>::new());
+ let ctx = Ctx::new(&allow);
+ let mut data = Object::default();
+ data.insert(Cow::Borrowed("source"), Value::Static(StaticNode::U64(0)));
+ // Sub-field arrives as a plain array (not gzipped) — scrub in place, keep it an array.
+ data.insert(
+ Cow::Borrowed("texts"),
+ parse(br#"[{"id":5,"value":"keep secret"}]"#),
+ );
+
+ assert!(scrub_compressed_mutation(&ctx, &mut data).unwrap());
+
+ let texts = data.get("texts").unwrap();
+ assert!(matches!(texts, Value::Array(_)), "stays a plain array");
+ let value = as_str(
+ as_object(&as_array(texts).unwrap()[0])
+ .unwrap()
+ .get("value")
+ .unwrap(),
+ )
+ .unwrap();
+ assert_eq!(value, "keep ******");
+ }
+
+ #[test]
+ fn compressed_mutation_restores_null_and_empty_subfields() {
+ let allow = AllowLists::new(Vec::<String>::new(), Vec::<String>::new());
+ let ctx = Ctx::new(&allow);
+ let mut data = Object::default();
+ data.insert(Cow::Borrowed("source"), Value::Static(StaticNode::U64(0)));
+ data.insert(Cow::Borrowed("texts"), Value::Static(StaticNode::Null));
+ data.insert(Cow::Borrowed("attributes"), string_value(String::new()));
+
+ scrub_compressed_mutation(&ctx, &mut data).unwrap();
+
+ assert!(matches!(
+ data.get("texts"),
+ Some(Value::Static(StaticNode::Null))
+ ));
+ assert_eq!(as_str(data.get("attributes").unwrap()).unwrap(), "");
+ }
+
+ #[test]
+ fn compressed_mutation_fails_closed_on_non_array_subfield() {
+ let allow = AllowLists::new(Vec::<String>::new(), Vec::<String>::new());
+ let ctx = Ctx::new(&allow);
+ let mut data = Object::default();
+ data.insert(Cow::Borrowed("source"), Value::Static(StaticNode::U64(0)));
+ data.insert(
+ Cow::Borrowed("texts"),
+ string_value(compress_json(br#"{"a":1}"#)),
+ );
+ assert!(scrub_compressed_mutation(&ctx, &mut data).is_err());
+ }
+
+ #[test]
+ fn compressed_payload_fails_closed_when_nested_too_deep() {
+ let allow = AllowLists::new(Vec::<String>::new(), Vec::<String>::new());
+ let ctx = Ctx::new(&allow);
+ // A tiny gzip whose decompressed JSON nests past MAX_JSON_DEPTH must fail closed (Err), not
+ // overflow the worker-thread stack — a stack overflow aborts the process, which catch_unwind
+ // cannot contain, so it would bypass the fail-closed contract entirely. The payload is a valid,
+ // balanced nested array: without the depth guard it parses fine and returns Ok(false), so this
+ // test only passes because the guard rejects it up front.
+ let n = crate::json::MAX_JSON_DEPTH + 10;
+ let deep = format!("{}{}", "[".repeat(n), "]".repeat(n));
+ let mut data = string_value(compress_json(deep.as_bytes()));
+ assert!(scrub_compressed_full_snapshot(&ctx, &mut data).is_err());
+ }
+
+ #[test]
+ fn cv_decompression_budget_fails_the_message_closed() {
+ let allow = AllowLists::new(Vec::<String>::new(), Vec::<String>::new());
+ let ctx = Ctx::new(&allow);
+ // Two sub-fields, each within the per-payload cap; only their sum busts the budget.
+ let texts = compress_json(br#"[{"id":1,"value":"aaaaaaaaaaaaaaaaaaaaaaaa"}]"#);
+ let adds = compress_json(br#"[{"parentId":1,"nextId":null,"node":{"id":9,"type":2}}]"#);
+ let mut data = Object::default();
+ data.insert(Cow::Borrowed("source"), Value::Static(StaticNode::U64(0)));
+ data.insert(Cow::Borrowed("texts"), string_value(texts));
+ data.insert(Cow::Borrowed("adds"), string_value(adds));
+
+ ctx.cv_budget.set(60);
+ let err = scrub_compressed_mutation(&ctx, &mut data).unwrap_err();
+ assert!(
+ format!("{err:#}").contains("budget"),
+ "must fail closed on the cumulative budget, got: {err:#}"
+ );
+ }
+
+ #[test]
+ fn compressed_mutation_fails_closed_on_non_latin1_stream() {
+ let allow = AllowLists::new(Vec::<String>::new(), Vec::<String>::new());
+ let ctx = Ctx::new(&allow);
+ let mut data = Object::default();
+ data.insert(Cow::Borrowed("source"), Value::Static(StaticNode::U64(0)));
+ // A codepoint > 0xFF can't be a latin-1 gzip byte — must fail closed, not silently pass.
+ data.insert(
+ Cow::Borrowed("texts"),
+ string_value("\u{100}bad".to_string()),
+ );
+ assert!(scrub_compressed_mutation(&ctx, &mut data).is_err());
+ }
+}
diff --git a/rust/replay-anonymizer-node/src/dom.rs b/rust/replay-anonymizer-node/src/dom.rs
new file mode 100644
index 000000000000..860b1cd25c5d
--- /dev/null
+++ b/rust/replay-anonymizer-node/src/dom.rs
@@ -0,0 +1,361 @@
+//! 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.
+
+use simd_json::borrowed::{Object, Value};
+
+use crate::assets::{
+ apply_blur, blur_inline_image_attr, has_media_src_attr, is_media_src_attr, is_media_tag,
+ INLINE_IMAGE_ATTR,
+};
+use crate::context::Ctx;
+use crate::css::scrub_css_images;
+use crate::json::{
+ as_array_mut, as_object_mut, as_small_uint, as_str, is_object, is_true, key, string_value,
+};
+use crate::text::{redact_emails, scrub_text};
+use crate::url::scrub_url;
+
+// rrweb NodeType
+const NODE_DOCUMENT: u8 = 0;
+const NODE_ELEMENT: u8 = 2;
+const NODE_TEXT: u8 = 3;
+const NODE_CDATA: u8 = 4;
+const NODE_COMMENT: u8 = 5;
+
+#[derive(Clone, Copy, PartialEq, Eq)]
+pub(crate) enum ParentKind {
+ Script,
+ Style,
+ Other,
+}
+
+#[derive(Clone, Copy, PartialEq, Eq)]
+pub(crate) enum TagKind {
+ Script,
+ Style,
+ Media,
+ Other,
+}
+
+pub fn scrub_full_snapshot(ctx: &Ctx<'_>, data: &mut Value<'_>) -> bool {
+ let Some(obj) = as_object_mut(data) else {
+ return false;
+ };
+ match obj.get_mut("node") {
+ Some(node) if is_object(node) => walk_node(ctx, node, ParentKind::Other),
+ _ => false,
+ }
+}
+
+pub fn scrub_mutation(ctx: &Ctx<'_>, data: &mut Value<'_>) -> bool {
+ let Some(obj) = as_object_mut(data) else {
+ return false;
+ };
+ let mut changed = false;
+
+ if let Some(texts) = obj.get_mut("texts").and_then(as_array_mut) {
+ changed |= scrub_mutation_texts(ctx, texts);
+ }
+ if let Some(attributes) = obj.get_mut("attributes").and_then(as_array_mut) {
+ changed |= scrub_mutation_attributes(ctx, attributes);
+ }
+ if let Some(adds) = obj.get_mut("adds").and_then(as_array_mut) {
+ changed |= scrub_mutation_adds(ctx, adds);
+ }
+
+ changed
+}
+
+// The three sub-scrubs are exposed separately so the `cv` path can run each decompressed sub-field as
+// its own borrowed tree (each borrows a different scratch buffer).
+
+pub fn scrub_mutation_texts(ctx: &Ctx<'_>, texts: &mut Vec<Value<'_>>) -> bool {
+ let mut changed = false;
+ for t in texts.iter_mut() {
+ if let Some(tobj) = as_object_mut(t) {
+ let cur = tobj.get("value").and_then(as_str);
+ if let Some(v) = cur {
+ if let Some(nv) = scrub_text(ctx.allow, v) {
+ tobj.insert(key("value"), string_value(nv));
+ changed = true;
+ }
+ }
+ }
+ }
+ changed
+}
+
+pub fn scrub_mutation_attributes(ctx: &Ctx<'_>, attributes: &mut Vec<Value<'_>>) -> bool {
+ let mut changed = false;
+ for a in attributes.iter_mut() {
+ if let Some(aobj) = as_object_mut(a) {
+ if let Some(attrs) = aobj.get_mut("attributes").and_then(as_object_mut) {
+ let kind = if has_media_src_attr(attrs) {
+ TagKind::Media
+ } else {
+ TagKind::Other
+ };
+ changed |= scrub_attrs(ctx, attrs, kind);
+ }
+ }
+ }
+ changed
+}
+
+pub fn scrub_mutation_adds(ctx: &Ctx<'_>, adds: &mut Vec<Value<'_>>) -> bool {
+ let mut changed = false;
+ for added in adds.iter_mut() {
+ if let Some(aobj) = as_object_mut(added) {
+ if let Some(node) = aobj.get_mut("node") {
+ if is_object(node) {
+ changed |= walk_node(ctx, node, ParentKind::Other);
+ }
+ }
+ }
+ }
+ changed
+}
+
+pub(crate) fn walk_node(ctx: &Ctx<'_>, node: &mut Value<'_>, parent: ParentKind) -> bool {
+ let Some(obj) = as_object_mut(node) else {
+ return false;
+ };
+ let mut changed = false;
+
+ match obj.get("type").and_then(as_small_uint) {
+ Some(NODE_ELEMENT) => {
+ let kind = classify_tag(obj.get("tagName").and_then(as_str).unwrap_or(""));
+ if let Some(attrs) = obj.get_mut("attributes").and_then(as_object_mut) {
+ changed |= scrub_attrs(ctx, attrs, kind);
+ }
+ let child_parent = match kind {
+ TagKind::Script => ParentKind::Script,
+ TagKind::Style => ParentKind::Style,
+ TagKind::Media | TagKind::Other => ParentKind::Other,
+ };
+ if let Some(children) = obj.get_mut("childNodes").and_then(as_array_mut) {
+ for child in children.iter_mut() {
+ if is_object(child) {
+ changed |= walk_node(ctx, child, child_parent);
+ }
+ }
+ }
+ }
+ Some(NODE_DOCUMENT) => {
+ if let Some(children) = obj.get_mut("childNodes").and_then(as_array_mut) {
+ for child in children.iter_mut() {
+ if is_object(child) {
+ changed |= walk_node(ctx, child, ParentKind::Other);
+ }
+ }
+ }
+ }
+ Some(NODE_TEXT) => {
+ // Script is code — never touch it.
+ if parent == ParentKind::Script {
+ return false;
+ }
+ let is_style = obj.get("isStyle").map(is_true).unwrap_or(false);
+ if parent == ParentKind::Style || is_style {
+ return scrub_css_images(ctx, obj, "textContent");
+ }
+ changed |= scrub_text_content(ctx, obj);
+ }
+ Some(NODE_COMMENT) | Some(NODE_CDATA) => {
+ changed |= scrub_text_content(ctx, obj);
+ }
+ _ => {} // DocumentType or unknown: nothing.
+ }
+
+ changed
+}
+
+fn scrub_text_content(ctx: &Ctx<'_>, obj: &mut Object<'_>) -> bool {
+ let Some(cur) = obj.get("textContent").and_then(as_str) else {
+ return false;
+ };
+ match scrub_text(ctx.allow, cur) {
+ Some(v) => {
+ obj.insert(key("textContent"), string_value(v));
+ true
+ }
+ None => false,
+ }
+}
+
+pub(crate) fn classify_tag(tag: &str) -> TagKind {
+ if tag.eq_ignore_ascii_case("script") {
+ TagKind::Script
+ } else if tag.eq_ignore_ascii_case("style") {
+ TagKind::Style
+ } else if is_media_tag(tag) {
+ TagKind::Media
+ } else {
+ TagKind::Other
+ }
+}
+
+fn scrub_attrs(ctx: &Ctx<'_>, attrs: &mut Object<'_>, kind: TagKind) -> bool {
+ let mut changed = false;
+ // Plain string scrubs mutate values in place while iterating — no per-element key Vec. Only the
+ // helpers that need `&mut Object` (blur inserts sibling keys, css re-reads by key) defer their
+ // attr names, which most elements don't have. Each attr is scrubbed independently, so running
+ // the deferred ones after the loop produces the same result as the original in-order pass.
+ let mut deferred: Vec<String> = Vec::new();
+
+ for (name, value) in attrs.iter_mut() {
+ let name: &str = name.as_ref();
+ if kind == TagKind::Media && is_media_src_attr(name) {
+ continue;
+ }
+ // Inlined rendered pixels (`rr_dataURL`): blur the image, on any tag.
+ if name == INLINE_IMAGE_ATTR || name == "style" {
+ deferred.push(name.to_string());
+ continue;
+ }
+ // Only string attribute values are scrubbed.
+ let Some(current) = as_str(value) else {
+ continue;
+ };
+ let result = if is_url_attr(name) {
+ scrub_url(ctx.allow, current)
+ } else if is_user_text_attr(name) {
+ scrub_text(ctx.allow, current)
+ } else if is_data_attr(name) {
+ if data_attr_looks_sensitive(current) {
+ scrub_text(ctx.allow, current)
+ } else {
+ redact_emails(current)
+ }
+ } else {
+ continue;
+ };
+ if let Some(v) = result {
+ *value = string_value(v);
+ changed = true;
+ }
+ }
+
+ for name in deferred {
+ if name == INLINE_IMAGE_ATTR {
+ changed |= blur_inline_image_attr(ctx, attrs, &name);
+ } else {
+ changed |= scrub_css_images(ctx, attrs, &name);
+ }
+ }
+
+ if kind == TagKind::Media {
+ changed |= apply_blur(ctx, attrs);
+ }
+
+ changed
+}
+
+pub(crate) fn is_user_text_attr(name: &str) -> bool {
+ matches!(
+ name,
+ "alt"
+ | "title"
+ | "placeholder"
+ | "aria-label"
+ | "aria-description"
+ | "aria-roledescription"
+ | "aria-valuetext"
+ | "aria-placeholder"
+ | "value"
+ | "label"
+ | "summary"
+ )
+}
+
+pub(crate) fn is_data_attr(name: &str) -> bool {
+ name.starts_with("data-") && !name.starts_with("data-anon-original-")
+}
+
+pub(crate) fn data_attr_looks_sensitive(value: &str) -> bool {
+ // Free text (whitespace) or an email-ish token — not a single enum/state/id token.
+ value.contains('@') || value.chars().any(char::is_whitespace)
+}
+
+pub(crate) fn is_url_attr(name: &str) -> bool {
+ matches!(
+ name,
+ "href"
+ | "src"
+ | "srcset"
+ | "action"
+ | "formaction"
+ | "cite"
+ | "data"
+ | "poster"
+ | "background"
+ | "xlink:href"
+ | "manifest"
+ | "longdesc"
+ )
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use crate::allow_lists::AllowLists;
+ use crate::context::Ctx;
+ use crate::testkit::png_data_uri;
+ use simd_json::prelude::Writable;
+
+ fn scrub_snapshot(data_json: &str) -> serde_json::Value {
+ let allow = AllowLists::new(Vec::<String>::new(), Vec::<String>::new());
+ let ctx = Ctx::new(&allow);
+ let mut bytes = data_json.as_bytes().to_vec();
+ let mut data = simd_json::to_borrowed_value(&mut bytes).unwrap();
+ scrub_full_snapshot(&ctx, &mut data);
+ serde_json::from_str(&data.encode()).unwrap()
+ }
+
+ #[test]
+ fn inline_rr_dataurl_image_is_neutralized() {
+ let uri = png_data_uri(8, 8, [10, 10, 200, 255]);
+ let data = format!(
+ r#"{{"node":{{"type":0,"childNodes":[{{"type":2,"tagName":"div","attributes":{{"rr_dataURL":"{uri}"}},"childNodes":[]}}]}},"initialOffset":{{"top":0,"left":0}}}}"#
+ );
+ let out = scrub_snapshot(&data);
+ let v = out["node"]["childNodes"][0]["attributes"]["rr_dataURL"]
+ .as_str()
+ .unwrap();
+ assert!(v.starts_with("data:image/"), "still an image: {v}");
+ assert_ne!(v, uri, "raw inline image must not pass through");
+ }
+
+ #[test]
+ fn css_data_image_background_is_neutralized() {
+ let uri = png_data_uri(8, 8, [200, 200, 10, 255]);
+ let style = serde_json::to_string(&format!("background:url({uri})")).unwrap();
+ let data = format!(
+ r#"{{"node":{{"type":0,"childNodes":[{{"type":2,"tagName":"div","attributes":{{"style":{style}}},"childNodes":[]}}]}},"initialOffset":{{"top":0,"left":0}}}}"#
+ );
+ let out = scrub_snapshot(&data);
+ let scrubbed = out["node"]["childNodes"][0]["attributes"]["style"]
+ .as_str()
+ .unwrap();
+ assert!(!scrubbed.contains(&uri), "the original image must be gone");
+ assert!(
+ scrubbed.contains("url(data:image/png"),
+ "replaced with a data image: {scrubbed}"
+ );
+ }
+
+ #[test]
+ fn media_tag_without_source_attrs_is_not_marked_changed() {
+ // A bare <img> (media tag, but no src/href/etc. to blur) must report "unchanged" so the whole
+ // message isn't needlessly re-serialized just because a media element was present.
+ let allow = AllowLists::new(Vec::<String>::new(), Vec::<String>::new());
+ let ctx = Ctx::new(&allow);
+ let mut bytes = br#"{"node":{"type":0,"childNodes":[{"type":2,"tagName":"img","attributes":{"class":"logo"},"childNodes":[]}]},"initialOffset":{"top":0,"left":0}}"#.to_vec();
+ let mut data = simd_json::to_borrowed_value(&mut bytes).unwrap();
+ assert!(
+ !scrub_full_snapshot(&ctx, &mut data),
+ "a media tag with nothing to blur should not count as a change"
+ );
+ }
+}
diff --git a/rust/replay-anonymizer-node/src/event.rs b/rust/replay-anonymizer-node/src/event.rs
new file mode 100644
index 000000000000..3cff598c0d37
--- /dev/null
+++ b/rust/replay-anonymizer-node/src/event.rs
@@ -0,0 +1,247 @@
+//! 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`).
+
+use anyhow::{bail, Context, Result};
+use simd_json::borrowed::{Object, Value};
+use simd_json::prelude::Writable;
+use simd_json::StaticNode;
+
+use crate::allow_lists::AllowLists;
+use crate::canvas::scrub_canvas_mutation;
+use crate::context::Ctx;
+use crate::cv::{scrub_compressed_full_snapshot, scrub_compressed_mutation};
+use crate::dom::{scrub_full_snapshot, scrub_mutation};
+use crate::json::{
+ as_array_mut, as_object, as_object_mut, as_small_uint, as_str, key, parse_untrusted,
+ reject_if_too_deep, string_value,
+};
+use crate::text::scrub_text;
+use crate::url::scrub_url_opts;
+use crate::value::{scrub_console_plugin, scrub_generic_field, scrub_network_plugin};
+
+// RRWebEventType
+pub const TYPE_FULL_SNAPSHOT: u8 = 2;
+pub const TYPE_INCREMENTAL: u8 = 3;
+pub const TYPE_META: u8 = 4;
+pub const TYPE_CUSTOM: u8 = 5;
+pub const TYPE_PLUGIN: u8 = 6;
+
+// RRWebEventSource (incremental)
+pub const SOURCE_MUTATION: u8 = 0;
+pub const SOURCE_INPUT: u8 = 5;
+pub const SOURCE_CANVAS_MUTATION: u8 = 9;
+
+pub const NETWORK_PLUGIN: &str = "rrweb/network@1";
+pub const CONSOLE_PLUGIN: &str = "rrweb/console@1";
+
+/// Anonymizes every event in a parsed message (`{ windowId: Event[] }`) in place. `Ok(None)` means
+/// nothing changed (the caller can keep its original). `Err` means an event could not be anonymized —
+/// fail closed, the caller must drop the message. A single `Ctx` spans the whole message so its blur
+/// memo is shared across every event (an image recurring across events is blurred once).
+pub fn anonymize_message(allow: &AllowLists, json: &mut [u8]) -> Result<Option<String>> {
+ reject_if_too_deep(json, "eventsByWindowId")?;
+ let mut root = parse_untrusted(json).context("parse eventsByWindowId json")?;
+ let Some(obj) = as_object_mut(&mut root) else {
+ bail!("eventsByWindowId is not an object");
+ };
+ let ctx = Ctx::new(allow);
+ let mut changed = false;
+ for (_, events) in obj.iter_mut() {
+ if let Some(arr) = as_array_mut(events) {
+ for event in arr.iter_mut() {
+ changed |= route_event(&ctx, event)?;
+ }
+ }
+ }
+ if !changed {
+ return Ok(None);
+ }
+ Ok(Some(root.encode()))
+}
+
+/// Convenience for tests/callers holding a single event as a JSON string: parse, scrub, re-serialize.
+pub fn anonymize_event_str(allow: &AllowLists, event_json: &str) -> Result<String> {
+ let mut bytes = event_json.as_bytes().to_vec();
+ let mut value = parse_untrusted(&mut bytes).context("parse event json")?;
+ anonymize_event(allow, &mut value)?;
+ Ok(value.encode())
+}
+
+/// Scrubs a single event in place, returning whether it changed. `Err` = "could not anonymize".
+/// Builds its own `Ctx` (single-event scope); the message path uses [`anonymize_message`] instead so
+/// the blur memo is shared across events.
+pub fn anonymize_event(allow: &AllowLists, event: &mut Value<'_>) -> Result<bool> {
+ route_event(&Ctx::new(allow), event)
+}
+
+/// True when the event's `cv` marker means "compressed" (present and non-null).
+pub fn is_compressed_marker(v: Option<&Value<'_>>) -> bool {
+ matches!(v, Some(v) if !matches!(v, Value::Static(StaticNode::Null)))
+}
+
+pub fn route_event(ctx: &Ctx<'_>, event: &mut Value<'_>) -> Result<bool> {
+ let Some(obj) = as_object_mut(event) else {
+ return Ok(false);
+ };
+ let compressed = is_compressed_marker(obj.get("cv"));
+ let ty = obj.get("type").and_then(as_small_uint);
+ let Some(data) = obj.get_mut("data") else {
+ return Ok(false);
+ };
+ route_data(ctx, ty, compressed, data)
+}
+
+/// Scrubs an event's `data` value in place given its routing shape (`type` + `cv` marker). This is the
+/// single routing implementation shared by the tree walk and the streaming span-splice path: everything
+/// the anonymizer changes lives inside `data`, so both paths agree by construction.
+pub fn route_data(
+ ctx: &Ctx<'_>,
+ ty: Option<u8>,
+ compressed: bool,
+ data: &mut Value<'_>,
+) -> Result<bool> {
+ match ty {
+ Some(TYPE_FULL_SNAPSHOT) => {
+ if compressed && matches!(data, Value::String(_)) {
+ scrub_compressed_full_snapshot(ctx, data)
+ } else {
+ // Not actually whole-blob compressed — scrub as a plain object.
+ Ok(scrub_full_snapshot(ctx, data))
+ }
+ }
+ Some(TYPE_INCREMENTAL) => {
+ let source = match as_object(data) {
+ Some(d) => d.get("source").and_then(as_small_uint),
+ None => return Ok(false),
+ };
+ match source {
+ Some(SOURCE_MUTATION) => {
+ if compressed {
+ scrub_compressed_mutation(ctx, as_object_mut(data).unwrap())
+ } else {
+ Ok(scrub_mutation(ctx, data))
+ }
+ }
+ Some(SOURCE_INPUT) => Ok(scrub_text_field(
+ ctx.allow,
+ as_object_mut(data).unwrap(),
+ "text",
+ )),
+ Some(SOURCE_CANVAS_MUTATION) => Ok(scrub_canvas_mutation(ctx, data)),
+ _ => Ok(false),
+ }
+ }
+ Some(TYPE_META) => {
+ // Meta `href` is the page URL — strip the authority and rewrite the host to example.com.
+ let Some(data) = as_object_mut(data) else {
+ return Ok(false);
+ };
+ let Some(href) = data.get("href").and_then(as_str) else {
+ return Ok(false);
+ };
+ match scrub_url_opts(ctx.allow, href, true) {
+ Some(v) => {
+ data.insert(key("href"), string_value(v));
+ Ok(true)
+ }
+ None => Ok(false),
+ }
+ }
+ Some(TYPE_CUSTOM) => match as_object_mut(data) {
+ Some(data) => Ok(scrub_generic_field(ctx.allow, data, "payload")),
+ None => Ok(false),
+ },
+ Some(TYPE_PLUGIN) => {
+ let Some(data) = as_object_mut(data) else {
+ return Ok(false);
+ };
+ let plugin = data.get("plugin").and_then(as_str).map(str::to_string);
+ Ok(match plugin.as_deref() {
+ Some(NETWORK_PLUGIN) => scrub_network_plugin(ctx.allow, data, "payload"),
+ Some(CONSOLE_PLUGIN) => scrub_console_plugin(ctx.allow, data, "payload"),
+ _ => scrub_generic_field(ctx.allow, data, "payload"),
+ })
+ }
+ // DomContentLoaded, Load, unknown types: pass-through.
+ _ => Ok(false),
+ }
+}
+
+fn scrub_text_field(allow: &AllowLists, obj: &mut Object<'_>, field: &'static str) -> bool {
+ let Some(cur) = obj.get(field).and_then(as_str) else {
+ return false;
+ };
+ match scrub_text(allow, cur) {
+ Some(v) => {
+ obj.insert(key(field), string_value(v));
+ true
+ }
+ None => false,
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn message_scrubs_every_window() {
+ let allow = AllowLists::new(["hello", "here"], Vec::<String>::new());
+ let mut json = br#"{"w1":[{"type":3,"data":{"source":5,"id":1,"text":"hello secret","isChecked":false}}],"w2":[{"type":3,"data":{"source":5,"id":2,"text":"world here","isChecked":false}}]}"#.to_vec();
+ let out = anonymize_message(&allow, &mut json)
+ .unwrap()
+ .expect("something changed");
+ let v: serde_json::Value = serde_json::from_str(&out).unwrap();
+ assert_eq!(v["w1"][0]["data"]["text"], "hello ******");
+ assert_eq!(v["w2"][0]["data"]["text"], "***** here");
+ }
+
+ #[test]
+ fn unchanged_message_returns_none() {
+ let allow = AllowLists::new(Vec::<String>::new(), Vec::<String>::new());
+ // A Load event (type 1) is pass-through; the caller keeps its original parse.
+ let mut json = br#"{"w1":[{"type":1,"data":{}}]}"#.to_vec();
+ assert!(anonymize_message(&allow, &mut json).unwrap().is_none());
+ }
+
+ #[test]
+ fn recurring_inline_image_is_neutralized_across_windows() {
+ // An inline image can recur across events/windows in one message (the case the per-message blur
+ // memo targets). Every occurrence must be neutralized to a data-image — never the raw original —
+ // and identical inputs must yield identical output. This drives the real `anonymize_message`
+ // entry (route -> full snapshot -> dom -> blur), which the deterministic JSON fixtures can't
+ // cover (blurred bytes differ from the TS `sharp` output, so image parity is Rust-only).
+ use crate::testkit::png_data_uri;
+ use serde_json::json;
+ let allow = AllowLists::new(Vec::<String>::new(), Vec::<String>::new());
+ let uri = png_data_uri(40, 40, [12, 34, 56, 255]);
+ let snapshot = json!({
+ "type": 2,
+ "data": {
+ "node": { "type": 0, "childNodes": [
+ { "type": 2, "tagName": "div", "attributes": { "rr_dataURL": uri.clone() }, "childNodes": [] }
+ ]},
+ "initialOffset": { "top": 0, "left": 0 }
+ }
+ });
+ let message = json!({ "w1": [snapshot.clone()], "w2": [snapshot] });
+ let mut bytes = serde_json::to_vec(&message).unwrap();
+ let out = anonymize_message(&allow, &mut bytes)
+ .unwrap()
+ .expect("the image should change");
+ let v: serde_json::Value = serde_json::from_str(&out).unwrap();
+ let img = |w: &str| {
+ v[w][0]["data"]["node"]["childNodes"][0]["attributes"]["rr_dataURL"]
+ .as_str()
+ .unwrap()
+ .to_string()
+ };
+ assert!(img("w1").starts_with("data:image/"), "still an image");
+ assert_ne!(img("w1"), uri, "raw inline image must not pass through");
+ assert_eq!(
+ img("w1"),
+ img("w2"),
+ "a recurring image must be neutralized consistently"
+ );
+ }
+}
diff --git a/rust/replay-anonymizer-node/src/gzip.rs b/rust/replay-anonymizer-node/src/gzip.rs
new file mode 100644
index 000000000000..2813a56ec5b4
--- /dev/null
+++ b/rust/replay-anonymizer-node/src/gzip.rs
@@ -0,0 +1,137 @@
+//! One-shot compression codecs: gzip on libdeflate (~2-3x the throughput of the streaming flate2
+//! legs it replaced, at the cost of needing the output size up front — which gzip carries in its
+//! ISIZE footer), plus the zstd leg that re-emits `cv` payloads.
+
+use std::cell::RefCell;
+
+use anyhow::{anyhow, bail, Result};
+use libdeflater::{CompressionLvl, Compressor, Decompressor};
+
+/// Compression-bomb cap: ~6x the 10.3 MB largest payload in a 1000-message production sample.
+/// Exceeding it fails closed as a classified DLQ instead of an unclassifiable OOM crash-loop.
+pub const MAX_DECOMPRESSED_BYTES: usize = 64 * 1024 * 1024;
+
+/// zstd level for re-emitted cv payloads. Counterintuitively negative: raw codec ratio is 20%
+/// worse than level 1 (0.145 vs 0.121 on the real cv corpus), but these bytes are stored
+/// latin-1-in-JSON inside snappy blocks, where entropy-coded output pays twice — high bytes cost
+/// 2 UTF-8 bytes each and are incompressible to the block snappy, while the raw ASCII literals
+/// negative levels leave behind cost 1 byte and snappy still compresses them. Measured end to
+/// end on the corpus, -1 beats 1 on every axis: 3.67 vs 3.88 ms/msg, snappy'd blocks 272.7 vs
+/// 289.2 MB, and the loader-side decompress is ~30% faster. Levels below -1 gain nothing.
+const CV_ZSTD_LEVEL: i32 = -1;
+
+thread_local! {
+ // Reused per thread: each codec state is a one-time ~50-300 KB malloc and cv work runs several
+ // times per event.
+ static DECOMPRESSOR: RefCell<Decompressor> = RefCell::new(Decompressor::new());
+ static COMPRESSOR: RefCell<Compressor> =
+ RefCell::new(Compressor::new(CompressionLvl::default()));
+ static ZSTD_COMPRESSOR: RefCell<zstd::bulk::Compressor<'static>> = RefCell::new(
+ zstd::bulk::Compressor::new(CV_ZSTD_LEVEL).expect("static zstd level is valid"),
+ );
+}
+
+/// Gunzip a single-member stream. The output buffer is sized exactly from the stream's ISIZE
+/// footer (uncompressed length mod 2^32, RFC 1952), so both footer lies fail closed: claiming
+/// more than [`MAX_DECOMPRESSED_BYTES`] is rejected before allocating, and claiming less than the
+/// real size makes libdeflate stop at the buffer end with `InsufficientSpace`.
+pub fn gunzip(raw: &[u8]) -> Result<Vec<u8>> {
+ let Some(footer) = raw.len().checked_sub(4).map(|start| &raw[start..]) else {
+ bail!("gzip stream too short");
+ };
+ let hint = u32::from_le_bytes(footer.try_into().expect("4-byte slice")) as usize;
+ if hint > MAX_DECOMPRESSED_BYTES {
+ bail!("gzip uncompressed size exceeds limit");
+ }
+ let mut out = vec![0u8; hint];
+ let n = DECOMPRESSOR
+ .with(|d| d.borrow_mut().gzip_decompress(raw, &mut out))
+ .map_err(|e| anyhow!("gunzip: {e:?}"))?;
+ out.truncate(n);
+ Ok(out)
+}
+
+/// Gzip `payload` as one default-level (6, matching both flate2's default and the TS pipeline's
+/// pako default) member.
+pub fn gzip(payload: &[u8]) -> Result<Vec<u8>> {
+ COMPRESSOR.with(|c| {
+ let mut c = c.borrow_mut();
+ let mut out = vec![0u8; c.gzip_compress_bound(payload.len())];
+ let n = c
+ .gzip_compress(payload, &mut out)
+ .map_err(|e| anyhow!("gzip: {e:?}"))?;
+ out.truncate(n);
+ Ok(out)
+ })
+}
+
+/// Re-compress a cv payload as zstd. The consumer distinguishes formats by magic bytes alone
+/// (`1f 8b` gzip vs `28 b5 2f fd` zstd), so historical gzip blocks stay readable.
+pub fn compress_cv(payload: &[u8]) -> Result<Vec<u8>> {
+ ZSTD_COMPRESSOR.with(|c| {
+ c.borrow_mut()
+ .compress(payload)
+ .map_err(|e| anyhow!("zstd: {e}"))
+ })
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use std::io::{Read, Write};
+
+ #[test]
+ fn round_trips_through_an_independent_codec() {
+ let payload = b"hello hello hello compression".repeat(50);
+
+ // Ours -> flate2: the member we emit must be a standard gzip stream.
+ let ours = gzip(&payload).unwrap();
+ let mut via_flate2 = Vec::new();
+ flate2::read::GzDecoder::new(&ours[..])
+ .read_to_end(&mut via_flate2)
+ .unwrap();
+ assert_eq!(via_flate2, payload);
+
+ // flate2 -> ours: we must decode members other encoders produced.
+ let mut enc = flate2::write::GzEncoder::new(Vec::new(), flate2::Compression::default());
+ enc.write_all(&payload).unwrap();
+ let theirs = enc.finish().unwrap();
+ assert_eq!(gunzip(&theirs).unwrap(), payload);
+ }
+
+ #[test]
+ fn rejects_a_footer_claiming_more_than_the_cap() {
+ let mut stream = gzip(b"small").unwrap();
+ let n = stream.len();
+ stream[n - 4..].copy_from_slice(&(u32::MAX).to_le_bytes());
+ let err = gunzip(&stream).unwrap_err().to_string();
+ assert!(err.contains("exceeds limit"), "got: {err}");
+ }
+
+ #[test]
+ fn fails_closed_on_a_footer_claiming_less_than_the_real_size() {
+ let payload = b"0123456789".repeat(100);
+ let mut stream = gzip(&payload).unwrap();
+ let n = stream.len();
+ stream[n - 4..].copy_from_slice(&8u32.to_le_bytes());
+ assert!(gunzip(&stream).is_err());
+ }
+
+ #[test]
+ fn rejects_truncated_and_empty_streams() {
+ assert!(gunzip(b"").is_err());
+ assert!(gunzip(&[0x1f, 0x8b, 0x08]).is_err());
+ }
+
+ #[test]
+ fn compress_cv_emits_a_zstd_frame() {
+ // Magic-byte dispatch is the consumer contract, so pin the emitted magic.
+ let payload = b"payload".repeat(20);
+ let zs = compress_cv(&payload).unwrap();
+ assert_eq!(&zs[..4], &[0x28, 0xb5, 0x2f, 0xfd]);
+ assert_eq!(
+ zstd::bulk::decompress(&zs, payload.len() + 64).unwrap(),
+ payload
+ );
+ }
+}
diff --git a/rust/replay-anonymizer-node/src/index.ts b/rust/replay-anonymizer-node/src/index.ts
new file mode 100644
index 000000000000..4897ca6dc9ed
--- /dev/null
+++ b/rust/replay-anonymizer-node/src/index.ts
@@ -0,0 +1,81 @@
+/* eslint-disable @typescript-eslint/no-var-requires */
+// The native addon is built from `src/lib.rs` and copied to `index.node` at the package root.
+const native = require('../index.node')
+
+export interface AllowListsInput {
+ /** Words kept verbatim by the text scrubber (ASCII-case-insensitive). */
+ text: string[]
+ /** URL path segments/params kept verbatim by the URL scrubber. */
+ url: string[]
+}
+
+/** Per emitted JSONL line, in line order. */
+export interface AnonymizeEventMeta {
+ /** The event's `timestamp` (epoch ms; can be fractional). */
+ ts: number
+ /** Bitmask of the FLAG_* bits in `snapshot.rs` (mirrored as PRE_SERIALIZED_FLAG_* in the consumer). */
+ flags: number
+ /** Post-scrub `hrefFrom(event)` (`data.href` / `data.payload.href`, trimmed), when present. */
+ href?: string
+}
+
+/** Envelope + per-event metadata parsed from {@link AnonymizeKafkaPayloadResult.meta}. */
+export interface AnonymizeMeta {
+ distinctId: string
+ /** Raw `$session_id` — normalization stays in TS. */
+ sessionId: string
+ /** `$window_id ?? ''`. */
+ windowId: string
+ snapshotSource: string | null
+ snapshotLibrary: string | null
+ /** Min/max valid-event timestamps (epoch ms). */
+ startTs: number
+ endTs: number
+ /** rrweb/console@1 plugin events by level. */
+ consoleLogCount: number
+ consoleWarnCount: number
+ consoleErrorCount: number
+ events: AnonymizeEventMeta[]
+}
+
+export interface AnonymizeKafkaPayloadResult {
+ /** True if the message could not be anonymized — the caller must drop or DLQ it (fail-closed). */
+ failed: boolean
+ /**
+ * Failure classification when `failed`, matching the TS parse step's dlq/drop reasons:
+ * `invalid_json` | `invalid_message_payload` | `received_non_snapshot_message` |
+ * `message_contained_no_valid_rrweb_events` | `anonymize_failed`.
+ */
+ reason: string | null
+ /** Failure detail when `failed`, else `null`. */
+ error: string | null
+ /** Scrubbed JSONL block lines (`["<windowId>",<event>]\n` per valid event), ready to write. */
+ lines: Buffer | null
+ /** JSON-serialized {@link AnonymizeMeta}. */
+ meta: string | null
+ /**
+ * Which implementation produced the output (differential-tested identical). `tree` means the
+ * whole-message parse fallback fired; the label is an A/B / fallback-rate signal.
+ */
+ route: 'stream' | 'tree' | null
+}
+
+/** Initialize the process-wide allow lists. Call once at startup before {@link anonymizeKafkaPayload}. */
+export function initAnonymizer(allow: AllowListsInput): void {
+ native.initAnonymizer(JSON.stringify(allow))
+}
+
+/**
+ * Anonymize a replay Kafka payload (`{"distinct_id": ..., "data": "<event json>"}`). Rust owns the
+ * decompression (lz4 via the `content-encoding` header, gzip via magic bytes), the parse, the
+ * scrub, and the serialize; only the raw bytes cross the FFI boundary. CPU work — including the
+ * decompression — runs off the Node event loop.
+ *
+ * `cv` payloads re-emit as zstd; the reader dispatches on magic bytes.
+ */
+export function anonymizeKafkaPayload(
+ payload: Buffer,
+ contentEncoding?: string | null
+): Promise<AnonymizeKafkaPayloadResult> {
+ return native.anonymizeKafkaPayload(payload, contentEncoding ?? undefined)
+}
diff --git a/rust/replay-anonymizer-node/src/json.rs b/rust/replay-anonymizer-node/src/json.rs
new file mode 100644
index 000000000000..2380d47f3509
--- /dev/null
+++ b/rust/replay-anonymizer-node/src/json.rs
@@ -0,0 +1,259 @@
+//! Small helpers for mutating `simd_json::BorrowedValue` in place, mirroring the TS scrubbers which
+//! treat every rrweb node as a generic `Record<string, unknown>`. Working on a generic value (not
+//! typed structs) preserves unknown fields exactly on round-trip, matching the TS in-place mutation.
+//! The borrowed tree keeps unchanged strings as zero-copy slices of the input bytes; only scrubbed
+//! values allocate (`Cow::Owned`).
+
+use std::borrow::Cow;
+
+use simd_json::borrowed::{Object, Value};
+use simd_json::StaticNode;
+
+pub fn as_object_mut<'a, 'v>(v: &'a mut Value<'v>) -> Option<&'a mut Object<'v>> {
+ match v {
+ Value::Object(o) => Some(o.as_mut()),
+ _ => None,
+ }
+}
+
+pub fn as_array_mut<'a, 'v>(v: &'a mut Value<'v>) -> Option<&'a mut Vec<Value<'v>>> {
+ match v {
+ Value::Array(a) => Some(a),
+ _ => None,
+ }
+}
+
+pub fn as_object<'a, 'v>(v: &'a Value<'v>) -> Option<&'a Object<'v>> {
+ match v {
+ Value::Object(o) => Some(o.as_ref()),
+ _ => None,
+ }
+}
+
+pub fn as_array<'a, 'v>(v: &'a Value<'v>) -> Option<&'a Vec<Value<'v>>> {
+ match v {
+ Value::Array(a) => Some(a),
+ _ => None,
+ }
+}
+
+pub fn as_str<'a>(v: &'a Value<'_>) -> Option<&'a str> {
+ match v {
+ Value::String(s) => Some(s.as_ref()),
+ _ => None,
+ }
+}
+
+pub fn is_object(v: &Value<'_>) -> bool {
+ matches!(v, Value::Object(_))
+}
+
+/// A JSON number read as `u32` (accepts an integral float, matching JS `typeof x === 'number'`).
+pub fn as_u32(v: &Value<'_>) -> Option<u32> {
+ match v {
+ Value::Static(StaticNode::I64(n)) => u32::try_from(*n).ok(),
+ Value::Static(StaticNode::U64(n)) => u32::try_from(*n).ok(),
+ Value::Static(StaticNode::F64(f))
+ if f.fract() == 0.0 && *f >= 0.0 && *f <= u32::MAX as f64 =>
+ {
+ Some(*f as u32)
+ }
+ _ => None,
+ }
+}
+
+/// A JSON number read as `usize` (accepts an integral non-negative float).
+pub fn as_usize(v: &Value<'_>) -> Option<usize> {
+ match v {
+ Value::Static(StaticNode::I64(n)) => usize::try_from(*n).ok(),
+ Value::Static(StaticNode::U64(n)) => usize::try_from(*n).ok(),
+ Value::Static(StaticNode::F64(f)) if f.fract() == 0.0 && *f >= 0.0 => Some(*f as usize),
+ _ => None,
+ }
+}
+
+/// A JSON number read as `f64` (any numeric representation), matching JS number semantics.
+pub fn as_f64(v: &Value<'_>) -> Option<f64> {
+ match v {
+ Value::Static(StaticNode::I64(n)) => Some(*n as f64),
+ Value::Static(StaticNode::U64(n)) => Some(*n as f64),
+ Value::Static(StaticNode::F64(f)) => Some(*f),
+ _ => None,
+ }
+}
+
+/// Reads a small non-negative integer field (rrweb `type`/`source` enums). Accepts an integral float
+/// too (JS `typeof x === 'number'` matches `2.0`), so a float-encoded discriminant still routes to the
+/// right scrubber rather than silently passing through unscrubbed.
+pub fn as_small_uint(v: &Value<'_>) -> Option<u8> {
+ match v {
+ Value::Static(StaticNode::F64(f))
+ if f.fract() == 0.0 && *f >= 0.0 && *f <= u8::MAX as f64 =>
+ {
+ Some(*f as u8)
+ }
+ Value::Static(StaticNode::I64(n)) => u8::try_from(*n).ok(),
+ Value::Static(StaticNode::U64(n)) => u8::try_from(*n).ok(),
+ _ => None,
+ }
+}
+
+pub fn is_true(v: &Value<'_>) -> bool {
+ matches!(v, Value::Static(StaticNode::Bool(true)))
+}
+
+pub fn string_value(s: String) -> Value<'static> {
+ Value::String(Cow::Owned(s))
+}
+
+/// A `'static` object key, so inserts don't tie the map's lifetime to a local.
+pub fn key(name: &'static str) -> Cow<'static, str> {
+ Cow::Borrowed(name)
+}
+
+/// Restore `JSON.parse` duplicate-key semantics on a parsed tree: simd-json's object builder keeps
+/// *every* entry for a duplicated key (`get` returns the first, serialization emits all of them),
+/// while `JSON.parse` keeps only the last. Left alone, that both diverges from the TS scrubbers and
+/// leaks: the walk would scrub the first copy and re-serialize the raw second copy verbatim. Objects
+/// with duplicates are rebuilt keeping the last occurrence, recursively.
+///
+/// Errs on objects too large to dedupe deterministically: halfbrown switches to hash storage past its
+/// vec threshold, where the original insertion order (and so "last") is unrecoverable — fail closed.
+pub fn dedupe_in_place(v: &mut Value<'_>) -> anyhow::Result<()> {
+ match v {
+ Value::Array(arr) => {
+ for item in arr.iter_mut() {
+ dedupe_in_place(item)?;
+ }
+ }
+ Value::Object(obj) => {
+ if has_duplicate_keys(obj) {
+ // Past halfbrown's vec-mode limit iteration order is no longer insertion order, so
+ // "last occurrence wins" cannot be reproduced — reject rather than guess.
+ if obj.len() > 32 {
+ anyhow::bail!("cannot dedupe duplicate keys in a large object");
+ }
+ let entries: Vec<(Cow<'_, str>, Value<'_>)> =
+ std::mem::take(obj.as_mut()).into_iter().collect();
+ let rebuilt = obj.as_mut();
+ for (k, val) in entries {
+ rebuilt.insert(k, val);
+ }
+ }
+ for (_, val) in obj.iter_mut() {
+ dedupe_in_place(val)?;
+ }
+ }
+ _ => {}
+ }
+ Ok(())
+}
+
+fn has_duplicate_keys(obj: &Object<'_>) -> bool {
+ let n = obj.len();
+ if n < 2 {
+ return false;
+ }
+ if n <= 16 {
+ // Allocation-free quadratic check: this runs for every object in every parsed span, so a
+ // scratch Vec here would dominate the dedupe cost on DOM-sized trees.
+ for (i, key) in obj.keys().enumerate().skip(1) {
+ if obj.keys().take(i).any(|prior| prior == key) {
+ return true;
+ }
+ }
+ false
+ } else {
+ let mut seen = ahash::AHashSet::with_capacity(n);
+ obj.keys().any(|k| !seen.insert(k.as_ref()))
+ }
+}
+
+/// Parse untrusted JSON bytes to a borrowed tree with `JSON.parse` semantics (duplicate keys deduped,
+/// last occurrence wins). All event-content parses must go through this, not `to_borrowed_value`.
+pub fn parse_untrusted<'v>(bytes: &'v mut [u8]) -> anyhow::Result<Value<'v>> {
+ let mut value = simd_json::to_borrowed_value(bytes)?;
+ dedupe_in_place(&mut value)?;
+ Ok(value)
+}
+
+/// [`parse_untrusted`] with caller-owned simd-json scratch buffers, so a loop parsing many small
+/// spans (the streaming per-event path) doesn't re-allocate the parser's internal buffers per call.
+pub fn parse_untrusted_with_buffers<'v>(
+ bytes: &'v mut [u8],
+ buffers: &mut simd_json::Buffers,
+) -> anyhow::Result<Value<'v>> {
+ let mut value = simd_json::value::borrowed::to_value_with_buffers(bytes, buffers)?;
+ dedupe_in_place(&mut value)?;
+ Ok(value)
+}
+
+// Untrusted rrweb can nest arbitrarily deep. Both the simd-json parse and the recursive scrub walk one
+// stack frame per level, so a crafted payload could overflow the worker-thread stack — an abort, which
+// `catch_unwind` cannot contain. Reject over-deep input up front (before parsing). Legitimate DOM/canvas
+// nesting is well under this. Applies to the outer message *and* to every gunzipped `cv` payload.
+pub const MAX_JSON_DEPTH: usize = 1024;
+
+/// Max `{`/`[` nesting depth in raw JSON, ignoring bracket bytes inside strings. Linear, no
+/// recursion; string content (the bulk of replay bytes) is skipped with memchr jumps.
+pub fn max_bracket_depth(json: &[u8]) -> usize {
+ let mut depth = 0usize;
+ let mut max = 0usize;
+ let mut pos = 0usize;
+ while pos < json.len() {
+ match json[pos] {
+ b'"' => {
+ pos += 1;
+ // Bytewise stretches with memchr escalation after 24 clean bytes, same rationale as
+ // `scan::skip_string`: short and escape-dense strings don't amortize memchr's setup.
+ 'stretch: while pos < json.len() {
+ let fast_end = (pos + 24).min(json.len());
+ while pos < fast_end {
+ match json[pos] {
+ b'"' => break 'stretch,
+ b'\\' => {
+ pos += 2;
+ continue 'stretch;
+ }
+ _ => pos += 1,
+ }
+ }
+ if pos >= json.len() {
+ break;
+ }
+ let Some(i) = memchr::memchr2(b'\\', b'"', &json[pos..]) else {
+ pos = json.len();
+ break;
+ };
+ let at = pos + i;
+ if json[at] == b'"' {
+ pos = at;
+ break;
+ }
+ pos = at + 2; // skip the escape and its payload byte
+ }
+ pos += 1;
+ }
+ b'{' | b'[' => {
+ depth += 1;
+ max = max.max(depth);
+ pos += 1;
+ }
+ b'}' | b']' => {
+ depth = depth.saturating_sub(1);
+ pos += 1;
+ }
+ _ => pos += 1,
+ }
+ }
+ max
+}
+
+/// Rejects raw JSON bytes that nest past [`MAX_JSON_DEPTH`], failing closed before any recursive parse.
+pub fn reject_if_too_deep(json: &[u8], context: &str) -> anyhow::Result<()> {
+ let depth = max_bracket_depth(json);
+ if depth > MAX_JSON_DEPTH {
+ anyhow::bail!("{context} nested too deep ({depth} > {MAX_JSON_DEPTH})");
+ }
+ Ok(())
+}
diff --git a/rust/replay-anonymizer-node/src/lib.rs b/rust/replay-anonymizer-node/src/lib.rs
new file mode 100644
index 000000000000..b284e2e9ee88
--- /dev/null
+++ b/rust/replay-anonymizer-node/src/lib.rs
@@ -0,0 +1,201 @@
+//! 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 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
+//! the parse, the scrub, and the serialize, so no JSON crosses the FFI boundary as a string. The
+//! crate builds both an `rlib` (for `cargo test`) and a `cdylib` (the `index.node` addon).
+
+pub mod allow_lists;
+pub mod assets;
+pub mod blur;
+pub mod bytewalk;
+pub mod canvas;
+pub mod context;
+pub mod css;
+pub mod cv;
+pub mod dom;
+pub mod event;
+pub mod gzip;
+pub mod json;
+pub mod scan;
+pub mod snapshot;
+pub mod text;
+pub mod url;
+pub mod value;
+
+pub use allow_lists::AllowLists;
+pub use context::Ctx;
+pub use event::{anonymize_event, anonymize_event_str, anonymize_message};
+pub use snapshot::{
+ anonymize_kafka_payload, anonymize_kafka_payload_opts, AnonymizeOpts, AnonymizedMessage,
+ FailKind, Failure, Route,
+};
+
+/// Shared helpers for the image-neutralization tests across modules.
+#[cfg(test)]
+pub(crate) mod testkit {
+ use base64::Engine;
+
+ fn encode_png(w: u32, h: u32, color: [u8; 4]) -> Vec<u8> {
+ let img =
+ image::DynamicImage::ImageRgba8(image::RgbaImage::from_pixel(w, h, image::Rgba(color)));
+ let mut buf = Vec::new();
+ img.write_to(&mut std::io::Cursor::new(&mut buf), image::ImageFormat::Png)
+ .unwrap();
+ buf
+ }
+
+ /// Base64 of an encoded PNG (no `data:` prefix) — e.g. for a canvas Blob's ArrayBuffer.
+ pub fn png_base64(w: u32, h: u32, color: [u8; 4]) -> String {
+ base64::engine::general_purpose::STANDARD.encode(encode_png(w, h, color))
+ }
+
+ pub fn png_data_uri(w: u32, h: u32, color: [u8; 4]) -> String {
+ format!("data:image/png;base64,{}", png_base64(w, h, color))
+ }
+
+ /// Base64 of `w*h` non-uniform RGBA pixels — e.g. for a canvas `ImageData` ArrayBuffer.
+ pub fn rgba_base64(w: u32, h: u32) -> String {
+ let mut raw = Vec::with_capacity((w * h * 4) as usize);
+ for i in 0..(w * h) {
+ let b = (i % 256) as u8;
+ raw.extend_from_slice(&[b, b.wrapping_add(50), b.wrapping_add(100), 255]);
+ }
+ base64::engine::general_purpose::STANDARD.encode(raw)
+ }
+}
+
+use std::sync::RwLock;
+
+use neon::prelude::*;
+use neon::types::buffer::TypedArray;
+use serde::Deserialize;
+
+// The fail-closed contract depends on `catch_unwind` containing panics on untrusted input. Under
+// `panic = "abort"` that becomes a no-op and one crafted message aborts the whole worker, so fail
+// the build if the workspace release profile ever switches to abort.
+#[cfg(all(panic = "abort", not(test)))]
+compile_error!(
+ "replay-anonymizer-node requires panic=unwind: catch_unwind is the fail-closed guard"
+);
+
+// The allow lists are immutable per process; set once at startup via `initAnonymizer`.
+static ALLOW: RwLock<Option<AllowLists>> = RwLock::new(None);
+
+#[derive(Deserialize)]
+struct AllowInput {
+ #[serde(default)]
+ text: Vec<String>,
+ #[serde(default)]
+ url: Vec<String>,
+}
+
+fn init_anonymizer(mut cx: FunctionContext) -> JsResult<JsNull> {
+ let json = cx.argument::<JsString>(0)?.value(&mut cx);
+ let input: AllowInput = serde_json::from_str(&json)
+ .or_else(|e| cx.throw_error(format!("invalid allow lists json: {e}")))?;
+ let allow = AllowLists::new(input.text, input.url);
+ *ALLOW.write().expect("allow lists lock poisoned") = Some(allow);
+ Ok(cx.null())
+}
+
+/// The off-thread outcome: anonymized output, a classified failure (dlq/drop reason + detail), or an
+/// unclassified error (panic, missing init) that the caller must treat as `anonymize_failed`.
+type TaskOutcome = Result<Result<(Vec<u8>, String, &'static str), (&'static str, String)>, String>;
+
+fn anonymize_kafka_payload_ffi(mut cx: FunctionContext) -> JsResult<JsPromise> {
+ // One copy on the event loop: the buffer's bytes move into the task (they can't be borrowed
+ // across threads, and simd-json needs a mutable scratch anyway). Decompression happens inside
+ // the task too — gunzip of a multi-MB payload has no business on the event loop.
+ let buf = cx.argument::<JsBuffer>(0)?;
+ let raw = buf.as_slice(&cx).to_vec();
+ let content_encoding: Option<String> = cx
+ .argument_opt(1)
+ .and_then(|v| v.downcast::<JsString, _>(&mut cx).ok())
+ .map(|s| s.value(&mut cx));
+ let promise = cx
+ .task(move || -> TaskOutcome {
+ // Contain any panic on untrusted input so it fails closed (the caller drops the message)
+ // rather than risking process abort.
+ std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
+ let guard = ALLOW
+ .read()
+ .map_err(|_| "allow lists lock poisoned".to_string())?;
+ let allow = guard.as_ref().ok_or_else(|| {
+ "anonymizer not initialized (call initAnonymizer first)".to_string()
+ })?;
+ let mut payload =
+ match snapshot::decompress_payload(raw, content_encoding.as_deref()) {
+ Ok(p) => p,
+ Err(f) => return Ok(Err((f.kind.reason(), f.detail))),
+ };
+ match snapshot::anonymize_kafka_payload(allow, &mut payload) {
+ Ok(out) => {
+ let meta = serde_json::to_string(&out.meta)
+ .map_err(|e| format!("serialize meta: {e}"))?;
+ Ok(Ok((out.lines, meta, out.route.as_str())))
+ }
+ Err(f) => Ok(Err((f.kind.reason(), f.detail))),
+ }
+ }))
+ .unwrap_or_else(|_| Err("panic while anonymizing".to_string()))
+ })
+ .promise(|mut cx, result: TaskOutcome| {
+ let obj = cx.empty_object();
+ let set_failure = |cx: &mut TaskContext<'_>,
+ obj: &Handle<'_, JsObject>,
+ reason: &str,
+ detail: String|
+ -> NeonResult<()> {
+ let failed = cx.boolean(true);
+ obj.set(cx, "failed", failed)?;
+ let reason = cx.string(reason);
+ obj.set(cx, "reason", reason)?;
+ let error = cx.string(detail);
+ obj.set(cx, "error", error)?;
+ let null = cx.null();
+ obj.set(cx, "lines", null)?;
+ let null = cx.null();
+ obj.set(cx, "meta", null)?;
+ let null = cx.null();
+ obj.set(cx, "route", null)?;
+ Ok(())
+ };
+ match result {
+ Ok(Ok((lines, meta, route))) => {
+ let failed = cx.boolean(false);
+ obj.set(&mut cx, "failed", failed)?;
+ let null = cx.null();
+ obj.set(&mut cx, "reason", null)?;
+ let null = cx.null();
+ obj.set(&mut cx, "error", null)?;
+ // Externally-backed: the JS Buffer wraps the Vec directly (freed by the GC's
+ // finalizer) instead of copying the whole JSONL block across the boundary.
+ let lines = JsBuffer::external(&mut cx, lines);
+ obj.set(&mut cx, "lines", lines)?;
+ let meta = cx.string(meta);
+ obj.set(&mut cx, "meta", meta)?;
+ let route = cx.string(route);
+ obj.set(&mut cx, "route", route)?;
+ }
+ Ok(Err((reason, detail))) => set_failure(&mut cx, &obj, reason, detail)?,
+ // Fail closed: an unclassified error still drops the message.
+ Err(msg) => set_failure(&mut cx, &obj, FailKind::AnonymizeFailed.reason(), msg)?,
+ }
+ Ok(obj)
+ });
+ Ok(promise)
+}
+
+#[neon::main]
+fn main(mut cx: ModuleContext) -> NeonResult<()> {
+ cx.export_function("initAnonymizer", init_anonymizer)?;
+ cx.export_function("anonymizeKafkaPayload", anonymize_kafka_payload_ffi)?;
+ Ok(())
+}
diff --git a/rust/replay-anonymizer-node/src/scan.rs b/rust/replay-anonymizer-node/src/scan.rs
new file mode 100644
index 000000000000..269c82b7fbc2
--- /dev/null
+++ b/rust/replay-anonymizer-node/src/scan.rs
@@ -0,0 +1,714 @@
+//! Byte-level JSON span scanning: locate values, iterate object entries and array items, and read
+//! scalars without building a tree. Powers the streaming rewrite in [`crate::snapshot`], which memcpys
+//! pass-through spans and parses only the spans it must scrub.
+//!
+//! The scanners assume structurally valid JSON (the payload is re-serialized by capture upstream) and
+//! only report *structural* failures (unbalanced brackets, truncation). They never unescape strings;
+//! callers that need decoded text use [`unescape`], and callers that meet an escaped **key** must fall
+//! back to a real parse — a `\uXXXX` key could alias a routing key, and byte comparison would miss it.
+
+/// Half-open byte range into the scanned buffer.
+pub type Span = (usize, usize);
+
+#[derive(Debug, PartialEq, Eq)]
+pub struct ScanError(pub &'static str);
+
+type Result<T> = std::result::Result<T, ScanError>;
+
+fn is_ws(b: u8) -> bool {
+ matches!(b, b' ' | b'\t' | b'\n' | b'\r')
+}
+
+pub fn skip_ws(bytes: &[u8], mut pos: usize) -> usize {
+ while pos < bytes.len() && is_ws(bytes[pos]) {
+ pos += 1;
+ }
+ pos
+}
+
+/// True when the little-endian 8-byte word contains a `"` or `\` byte (the classic SWAR
+/// zero-byte test), letting scanners consume 8 bytes per step with no memchr per-call setup.
+#[inline]
+fn word_has_quote_or_backslash(word: u64) -> bool {
+ const LO: u64 = 0x0101_0101_0101_0101;
+ const HI: u64 = 0x8080_8080_8080_8080;
+ let q = word ^ (LO * b'"' as u64);
+ let b = word ^ (LO * b'\\' as u64);
+ ((q.wrapping_sub(LO) & !q) | (b.wrapping_sub(LO) & !b)) & HI != 0
+}
+
+#[inline]
+fn word_has_backslash(word: u64) -> bool {
+ const LO: u64 = 0x0101_0101_0101_0101;
+ const HI: u64 = 0x8080_8080_8080_8080;
+ let b = word ^ (LO * b'\\' as u64);
+ b.wrapping_sub(LO) & !b & HI != 0
+}
+
+#[inline]
+fn read_word(bytes: &[u8], pos: usize) -> u64 {
+ u64::from_le_bytes(bytes[pos..pos + 8].try_into().expect("8 bytes"))
+}
+
+/// Position of the next `\` in `bytes[pos..end]`, or `end`. Same SWAR-then-memchr shape as
+/// [`skip_string`], for the unescapers' clean-run scans.
+#[inline]
+fn next_backslash(bytes: &[u8], mut pos: usize, end: usize) -> usize {
+ let mut words = 0u32;
+ while pos + 8 <= end && words < 4 {
+ if word_has_backslash(read_word(bytes, pos)) {
+ while bytes[pos] != b'\\' {
+ pos += 1;
+ }
+ return pos;
+ }
+ pos += 8;
+ words += 1;
+ }
+ if words == 4 {
+ return memchr::memchr(b'\\', &bytes[pos..end]).map_or(end, |j| pos + j);
+ }
+ while pos < end {
+ if bytes[pos] == b'\\' {
+ return pos;
+ }
+ pos += 1;
+ }
+ end
+}
+
+/// `start` must be at an opening quote; returns the position just past the closing quote.
+/// Each stretch is scanned SWAR-first (8-byte words, no per-call setup), escalating to memchr only
+/// after 32 clean bytes: DOM JSON is mostly 5-20 byte strings and JSON-in-JSON has an escape every
+/// ~15 bytes, so memchr-per-hop would be all setup — while long clean runs (blobs, base64 bodies)
+/// still get real SIMD jumps.
+pub fn skip_string(bytes: &[u8], start: usize) -> Result<usize> {
+ debug_assert_eq!(bytes.get(start), Some(&b'"'));
+ let mut pos = start + 1;
+ 'stretch: while pos < bytes.len() {
+ let mut words = 0u32;
+ while pos + 8 <= bytes.len() && words < 4 {
+ if word_has_quote_or_backslash(read_word(bytes, pos)) {
+ let word_end = pos + 8;
+ while pos < word_end {
+ match bytes[pos] {
+ b'"' => return Ok(pos + 1),
+ b'\\' => {
+ pos += 2; // skip the escape and its payload byte
+ continue 'stretch;
+ }
+ _ => pos += 1,
+ }
+ }
+ continue 'stretch;
+ }
+ pos += 8;
+ words += 1;
+ }
+ if words == 4 {
+ // 32 clean bytes: a long run, worth memchr's setup.
+ let Some(i) = memchr::memchr2(b'\\', b'"', &bytes[pos..]) else {
+ break;
+ };
+ let at = pos + i;
+ if bytes[at] == b'"' {
+ return Ok(at + 1);
+ }
+ pos = at + 2;
+ continue 'stretch;
+ }
+ // Tail: fewer than 8 bytes left.
+ while pos < bytes.len() {
+ match bytes[pos] {
+ b'"' => return Ok(pos + 1),
+ b'\\' => pos += 2,
+ _ => pos += 1,
+ }
+ }
+ break;
+ }
+ Err(ScanError("unterminated string"))
+}
+
+/// Matches the parse path's `MAX_JSON_DEPTH` so scan and parse fail closed on the same over-deep
+/// inputs; real DOMs nest to ~25 but some legitimately exceed 64.
+const MAX_BRACKET_NESTING: usize = 1024;
+
+/// `start` must be at `open`; returns the position just past the matching `close`. `open`/`close`
+/// only name the expected top level.
+///
+/// The `stack` bitstack (0 = brace, 1 = bracket) rejects a mismatched closer instead of closing the
+/// wrong container — otherwise `{"a":[}]}` would locate a span at the inner `}` and splice invalid
+/// bytes through verbatim.
+///
+/// Stays bytewise: memchr3 here measured ~20% slower on bracket-dense payloads (the gaps between
+/// strings are too short to amortize its setup).
+pub fn skip_balanced(bytes: &[u8], start: usize, open: u8, close: u8) -> Result<usize> {
+ debug_assert_eq!(bytes.get(start), Some(&open));
+ let _ = close;
+ let mut stack = [0u64; MAX_BRACKET_NESTING / 64];
+ let mut depth: usize = 0;
+ let mut pos = start;
+ while pos < bytes.len() {
+ match bytes[pos] {
+ b'"' => {
+ pos = skip_string(bytes, pos)?;
+ continue;
+ }
+ b'{' | b'[' => {
+ if depth >= MAX_BRACKET_NESTING {
+ return Err(ScanError("bracket nesting too deep"));
+ }
+ if bytes[pos] == b'[' {
+ stack[depth / 64] |= 1 << (depth % 64);
+ } else {
+ stack[depth / 64] &= !(1 << (depth % 64));
+ }
+ depth += 1;
+ }
+ b'}' | b']' => {
+ let Some(next) = depth.checked_sub(1) else {
+ return Err(ScanError("unbalanced brackets"));
+ };
+ let was_bracket = (stack[next / 64] >> (next % 64)) & 1 == 1;
+ if was_bracket != (bytes[pos] == b']') {
+ return Err(ScanError("mismatched brackets"));
+ }
+ depth = next;
+ if depth == 0 {
+ return Ok(pos + 1);
+ }
+ }
+ _ => {}
+ }
+ pos += 1;
+ }
+ Err(ScanError("unbalanced brackets"))
+}
+
+fn skip_scalar(bytes: &[u8], start: usize) -> usize {
+ let mut pos = start;
+ while pos < bytes.len() {
+ let b = bytes[pos];
+ if matches!(b, b',' | b'}' | b']') || is_ws(b) {
+ return pos;
+ }
+ pos += 1;
+ }
+ pos
+}
+
+/// Span of the JSON value starting at (or after whitespace from) `start`.
+pub fn locate_value(bytes: &[u8], start: usize) -> Result<Span> {
+ let start = skip_ws(bytes, start);
+ let end = match bytes.get(start) {
+ Some(b'"') => skip_string(bytes, start)?,
+ Some(b'{') => skip_balanced(bytes, start, b'{', b'}')?,
+ Some(b'[') => skip_balanced(bytes, start, b'[', b']')?,
+ Some(_) => skip_scalar(bytes, start),
+ None => return Err(ScanError("expected a value")),
+ };
+ Ok((start, end))
+}
+
+/// One scanned object entry. `key` excludes the quotes and is *raw* (not unescaped);
+/// `key_escaped` marks a backslash in the raw key — callers must treat such objects as unscannable.
+pub struct Entry {
+ pub key: Span,
+ pub key_escaped: bool,
+ pub value: Span,
+}
+
+/// Iterates the top-level entries of the object whose span is `obj` (must start at `{`).
+pub struct ObjectEntries<'b> {
+ bytes: &'b [u8],
+ pos: usize,
+ end: usize,
+ done: bool,
+ first: bool,
+}
+
+pub fn object_entries<'b>(bytes: &'b [u8], obj: Span) -> Result<ObjectEntries<'b>> {
+ if bytes.get(obj.0) != Some(&b'{') {
+ return Err(ScanError("not an object"));
+ }
+ Ok(ObjectEntries {
+ bytes,
+ pos: obj.0 + 1,
+ end: obj.1,
+ done: false,
+ first: true,
+ })
+}
+
+impl<'b> Iterator for ObjectEntries<'b> {
+ type Item = Result<Entry>;
+
+ fn next(&mut self) -> Option<Self::Item> {
+ if self.done {
+ return None;
+ }
+ let bytes = self.bytes;
+ let mut pos = skip_ws(bytes, self.pos);
+ if pos + 1 == self.end && bytes.get(pos) == Some(&b'}') {
+ self.done = true;
+ return None;
+ }
+ if !self.first {
+ if bytes.get(pos) != Some(&b',') {
+ self.done = true;
+ return Some(Err(ScanError("expected ',' between object entries")));
+ }
+ pos = skip_ws(bytes, pos + 1);
+ }
+ self.first = false;
+ if bytes.get(pos) != Some(&b'"') {
+ self.done = true;
+ return Some(Err(ScanError("expected object key")));
+ }
+ let key_end = match skip_string(bytes, pos) {
+ Ok(e) => e,
+ Err(e) => {
+ self.done = true;
+ return Some(Err(e));
+ }
+ };
+ let key = (pos + 1, key_end - 1);
+ let key_escaped = bytes[key.0..key.1].contains(&b'\\');
+ pos = skip_ws(bytes, key_end);
+ if bytes.get(pos) != Some(&b':') {
+ self.done = true;
+ return Some(Err(ScanError("expected ':' after object key")));
+ }
+ let value = match locate_value(bytes, pos + 1) {
+ Ok(v) => v,
+ Err(e) => {
+ self.done = true;
+ return Some(Err(e));
+ }
+ };
+ self.pos = value.1;
+ Some(Ok(Entry {
+ key,
+ key_escaped,
+ value,
+ }))
+ }
+}
+
+/// Iterates the top-level item spans of the array whose span is `arr` (must start at `[`).
+pub struct ArrayItems<'b> {
+ bytes: &'b [u8],
+ pos: usize,
+ end: usize,
+ done: bool,
+ first: bool,
+}
+
+pub fn array_items<'b>(bytes: &'b [u8], arr: Span) -> Result<ArrayItems<'b>> {
+ if bytes.get(arr.0) != Some(&b'[') {
+ return Err(ScanError("not an array"));
+ }
+ Ok(ArrayItems {
+ bytes,
+ pos: arr.0 + 1,
+ end: arr.1,
+ done: false,
+ first: true,
+ })
+}
+
+impl<'b> Iterator for ArrayItems<'b> {
+ type Item = Result<Span>;
+
+ fn next(&mut self) -> Option<Self::Item> {
+ if self.done {
+ return None;
+ }
+ let bytes = self.bytes;
+ let mut pos = skip_ws(bytes, self.pos);
+ if pos + 1 == self.end && bytes.get(pos) == Some(&b']') {
+ self.done = true;
+ return None;
+ }
+ if !self.first {
+ if bytes.get(pos) != Some(&b',') {
+ self.done = true;
+ return Some(Err(ScanError("expected ',' between array items")));
+ }
+ pos += 1;
+ }
+ self.first = false;
+ let item = match locate_value(bytes, pos) {
+ Ok(v) => v,
+ Err(e) => {
+ self.done = true;
+ return Some(Err(e));
+ }
+ };
+ self.pos = item.1;
+ Some(Ok(item))
+ }
+}
+
+/// Parse a scanned scalar span as a JSON number, mirroring what `JSON.parse` would produce (an f64).
+/// Returns `None` for non-numbers. Accepts the full JSON number grammar (fractions, exponents); the
+/// charset pre-check keeps Rust-isms like `inf`/`NaN` out.
+pub fn parse_number(bytes: &[u8], span: Span) -> Option<f64> {
+ let raw = bytes.get(span.0..span.1)?;
+ let first = *raw.first()?;
+ if first != b'-' && !first.is_ascii_digit() {
+ return None;
+ }
+ if !raw
+ .iter()
+ .all(|b| b.is_ascii_digit() || matches!(b, b'-' | b'+' | b'.' | b'e' | b'E'))
+ {
+ return None;
+ }
+ std::str::from_utf8(raw).ok()?.parse::<f64>().ok()
+}
+
+/// True when the span is exactly the JSON literal `null`.
+pub fn is_null(bytes: &[u8], span: Span) -> bool {
+ bytes.get(span.0..span.1) == Some(b"null")
+}
+
+/// True when the span is a JSON string (starts with a quote).
+pub fn is_string(bytes: &[u8], span: Span) -> bool {
+ bytes.get(span.0) == Some(&b'"')
+}
+
+/// True when the span is a JSON object.
+pub fn is_object(bytes: &[u8], span: Span) -> bool {
+ bytes.get(span.0) == Some(&b'{')
+}
+
+/// True when the span is a JSON array.
+pub fn is_array(bytes: &[u8], span: Span) -> bool {
+ bytes.get(span.0) == Some(&b'[')
+}
+
+/// Decode a JSON string span (including its quotes), handling all JSON escapes including surrogate
+/// pairs. Escape-free strings (the overwhelming majority) borrow the input — zero copy.
+pub fn unescape<'b>(bytes: &'b [u8], span: Span) -> Result<std::borrow::Cow<'b, str>> {
+ let raw = bytes
+ .get(span.0..span.1)
+ .ok_or(ScanError("string span out of range"))?;
+ if raw.len() < 2 || raw[0] != b'"' || raw[raw.len() - 1] != b'"' {
+ return Err(ScanError("not a string span"));
+ }
+ let inner = &raw[1..raw.len() - 1];
+ if !inner.contains(&b'\\') {
+ return std::str::from_utf8(inner)
+ .map(std::borrow::Cow::Borrowed)
+ .map_err(|_| ScanError("invalid utf-8 in string"));
+ }
+ let mut out = Vec::with_capacity(inner.len());
+ let mut i = 0;
+ while i < inner.len() {
+ // Bulk-copy the clean run up to the next escape: one slice push per run, not per byte.
+ let run_start = i;
+ i = next_backslash(inner, i, inner.len());
+ out.extend_from_slice(&inner[run_start..i]);
+ if i >= inner.len() {
+ break;
+ }
+ let esc = *inner.get(i + 1).ok_or(ScanError("truncated escape"))?;
+ i += 2;
+ match esc {
+ b'"' => out.push(b'"'),
+ b'\\' => out.push(b'\\'),
+ b'/' => out.push(b'/'),
+ b'b' => out.push(0x08),
+ b'f' => out.push(0x0c),
+ b'n' => out.push(b'\n'),
+ b'r' => out.push(b'\r'),
+ b't' => out.push(b'\t'),
+ b'u' => {
+ let (ch, consumed) = decode_unicode(inner, i)?;
+ i += consumed;
+ let mut buf = [0u8; 4];
+ out.extend_from_slice(ch.encode_utf8(&mut buf).as_bytes());
+ }
+ _ => return Err(ScanError("bad escape")),
+ }
+ }
+ String::from_utf8(out)
+ .map(std::borrow::Cow::Owned)
+ .map_err(|_| ScanError("invalid utf-8 in string"))
+}
+
+/// Decode the `XXXX` (possibly a surrogate pair `XXXX\uYYYY`) after a `\u`, `at` pointing at the
+/// first hex digit. Returns the char and how many bytes were consumed.
+pub(crate) fn decode_unicode(bytes: &[u8], at: usize) -> Result<(char, usize)> {
+ let cp = hex4(bytes, at)?;
+ if (0xD800..0xDC00).contains(&cp) {
+ // High surrogate: pair it with the following \uXXXX low surrogate.
+ if bytes.get(at + 4) == Some(&b'\\') && bytes.get(at + 5) == Some(&b'u') {
+ let low = hex4(bytes, at + 6)?;
+ if (0xDC00..0xE000).contains(&low) {
+ let c = 0x10000 + ((cp as u32 - 0xD800) << 10) + (low as u32 - 0xDC00);
+ let ch = char::from_u32(c).ok_or(ScanError("invalid surrogate pair"))?;
+ return Ok((ch, 10));
+ }
+ }
+ return Ok((char::REPLACEMENT_CHARACTER, 4));
+ }
+ if (0xDC00..0xE000).contains(&cp) {
+ // Lone low surrogate.
+ return Ok((char::REPLACEMENT_CHARACTER, 4));
+ }
+ char::from_u32(cp as u32)
+ .map(|ch| (ch, 4))
+ .ok_or(ScanError("invalid codepoint"))
+}
+
+/// Unescape a JSON string span (including quotes) *in place*: decoded bytes are written over the
+/// span's own start (an unescaped string is never longer than its escaped form, so the write cursor
+/// trails the read cursor). Returns the decoded byte length, starting at `span.0 + 1`.
+///
+/// The buffer past the decoded bytes is left as scrap — callers must treat the span as consumed.
+/// Returns the decoded length and whether the decoded bytes are pure ASCII — ASCII output needs no
+/// further UTF-8 validation; non-ASCII output does (the second tuple field is `false`).
+pub fn unescape_in_place(bytes: &mut [u8], span: Span) -> Result<(usize, bool)> {
+ let raw_len = span.1.checked_sub(span.0).ok_or(ScanError("bad span"))?;
+ if raw_len < 2 || bytes.get(span.0) != Some(&b'"') || bytes.get(span.1 - 1) != Some(&b'"') {
+ return Err(ScanError("not a string span"));
+ }
+ let (start, end) = (span.0 + 1, span.1 - 1);
+ let Some(first) = memchr::memchr(b'\\', &bytes[start..end]) else {
+ let ascii = is_ascii_fold(&bytes[start..end]);
+ return Ok((end - start, ascii)); // escape-free: the bytes are already in place
+ };
+ let mut ascii = is_ascii_fold(&bytes[start..start + first]);
+ let mut rd = start + first;
+ let mut wr = rd;
+ while rd < end {
+ if bytes[rd] != b'\\' {
+ // Clean run: locate its end, then one copy_within.
+ let run_start = rd;
+ rd = next_backslash(bytes, rd, end);
+ ascii &= is_ascii_fold(&bytes[run_start..rd]);
+ bytes.copy_within(run_start..rd, wr);
+ wr += rd - run_start;
+ continue;
+ }
+ if rd + 1 >= end {
+ return Err(ScanError("truncated escape"));
+ }
+ let esc = bytes[rd + 1];
+ rd += 2;
+ let simple = match esc {
+ b'"' => b'"',
+ b'\\' => b'\\',
+ b'/' => b'/',
+ b'b' => 0x08,
+ b'f' => 0x0c,
+ b'n' => b'\n',
+ b'r' => b'\r',
+ b't' => b'\t',
+ b'u' => {
+ let (ch, consumed) = decode_unicode(&bytes[..end], rd)?;
+ rd += consumed;
+ ascii &= ch.is_ascii();
+ let mut buf = [0u8; 4];
+ let encoded = ch.encode_utf8(&mut buf).as_bytes();
+ bytes[wr..wr + encoded.len()].copy_from_slice(encoded);
+ wr += encoded.len();
+ continue;
+ }
+ _ => return Err(ScanError("bad escape")),
+ };
+ bytes[wr] = simple;
+ wr += 1;
+ }
+ Ok((wr - start, ascii))
+}
+
+/// OR-fold ASCII check (auto-vectorizes; the bytes are cache-warm from the surrounding copy).
+#[inline]
+fn is_ascii_fold(bytes: &[u8]) -> bool {
+ bytes.iter().fold(0u8, |acc, &b| acc | b) < 0x80
+}
+
+fn hex4(bytes: &[u8], at: usize) -> Result<u16> {
+ let mut v: u16 = 0;
+ for k in 0..4 {
+ let d = (*bytes.get(at + k).ok_or(ScanError("truncated \\u escape"))? as char)
+ .to_digit(16)
+ .ok_or(ScanError("bad hex digit"))?;
+ v = (v << 4) | d as u16;
+ }
+ Ok(v)
+}
+
+/// JSON-escape `s` into `out` as a quoted string, matching `JSON.stringify` byte-for-byte for the
+/// escapes it emits (control chars as `\u00xx`, everything else verbatim UTF-8).
+pub fn write_json_string(s: &str, out: &mut Vec<u8>) {
+ const HEX: &[u8; 16] = b"0123456789abcdef";
+ let bytes = s.as_bytes();
+ out.push(b'"');
+ let mut i = 0;
+ while i < bytes.len() {
+ // Bulk-copy the run needing no escape (scrubbed strings are long `*`/`#` runs).
+ let run_start = i;
+ while i < bytes.len() && !matches!(bytes[i], 0x00..=0x1f | b'"' | b'\\') {
+ i += 1;
+ }
+ out.extend_from_slice(&bytes[run_start..i]);
+ if i >= bytes.len() {
+ break;
+ }
+ let b = bytes[i];
+ i += 1;
+ match b {
+ b'"' => out.extend_from_slice(b"\\\""),
+ b'\\' => out.extend_from_slice(b"\\\\"),
+ 0x08 => out.extend_from_slice(b"\\b"),
+ 0x0c => out.extend_from_slice(b"\\f"),
+ b'\n' => out.extend_from_slice(b"\\n"),
+ b'\r' => out.extend_from_slice(b"\\r"),
+ b'\t' => out.extend_from_slice(b"\\t"),
+ _ => out.extend_from_slice(&[
+ b'\\',
+ b'u',
+ b'0',
+ b'0',
+ HEX[(b >> 4) as usize],
+ HEX[(b & 0xf) as usize],
+ ]),
+ }
+ }
+ out.push(b'"');
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn entries(json: &str) -> Vec<(String, String)> {
+ let bytes = json.as_bytes();
+ let span = locate_value(bytes, 0).unwrap();
+ object_entries(bytes, span)
+ .unwrap()
+ .map(|e| {
+ let e = e.unwrap();
+ (
+ String::from_utf8(bytes[e.key.0..e.key.1].to_vec()).unwrap(),
+ String::from_utf8(bytes[e.value.0..e.value.1].to_vec()).unwrap(),
+ )
+ })
+ .collect()
+ }
+
+ #[test]
+ fn object_scan_walks_nested_values_and_strings_with_brackets() {
+ let got = entries(r#"{ "a" : {"x":[1,2,{"y":"}"}]}, "b":"[{", "c": -1.5e3 , "d": null }"#);
+ assert_eq!(
+ got,
+ vec![
+ ("a".into(), r#"{"x":[1,2,{"y":"}"}]}"#.into()),
+ ("b".into(), r#""[{""#.into()),
+ ("c".into(), "-1.5e3".into()),
+ ("d".into(), "null".into()),
+ ]
+ );
+ }
+
+ #[test]
+ fn array_scan_yields_item_spans() {
+ let json = br#"[ {"a":1}, "two", 3, [4], null ]"#;
+ let span = locate_value(json, 0).unwrap();
+ let items: Vec<String> = array_items(json, span)
+ .unwrap()
+ .map(|s| {
+ let s = s.unwrap();
+ String::from_utf8(json[s.0..s.1].to_vec()).unwrap()
+ })
+ .collect();
+ assert_eq!(items, vec![r#"{"a":1}"#, r#""two""#, "3", "[4]", "null"]);
+ }
+
+ #[test]
+ fn malformed_structures_error_rather_than_hang_or_panic() {
+ for bad in [
+ r#"{"a" 1}"#, // missing colon
+ r#"{"a":1 "b":2}"#, // missing comma
+ r#"{"a":"unterminated"#,
+ r#"[1 2]"#,
+ r#"{"a":{"#,
+ ] {
+ let bytes = bad.as_bytes();
+ let Ok(span) = locate_value(bytes, 0) else {
+ continue; // structurally rejected up front is fine too
+ };
+ let result: std::result::Result<(), ScanError> = if bad.starts_with('{') {
+ match object_entries(bytes, span) {
+ Ok(mut it) => it.try_for_each(|r| r.map(|_| ())),
+ Err(e) => Err(e),
+ }
+ } else {
+ match array_items(bytes, span) {
+ Ok(mut it) => it.try_for_each(|r| r.map(|_| ())),
+ Err(e) => Err(e),
+ }
+ };
+ assert!(result.is_err(), "should reject: {bad}");
+ }
+ }
+
+ #[test]
+ fn number_parsing_matches_json_semantics() {
+ let cases: &[(&str, Option<f64>)] = &[
+ ("1234", Some(1234.0)),
+ ("-1.5", Some(-1.5)),
+ ("1.7e12", Some(1.7e12)),
+ ("2E+2", Some(200.0)),
+ ("1e999", Some(f64::INFINITY)), // JSON.parse("1e999") -> Infinity
+ ("\"str\"", None),
+ ("null", None),
+ ("true", None),
+ ("NaN", None),
+ ];
+ for (raw, expected) in cases {
+ let got = parse_number(raw.as_bytes(), (0, raw.len()));
+ assert_eq!(got, *expected, "case: {raw}");
+ }
+ }
+
+ #[test]
+ fn unescape_handles_escapes_and_surrogate_pairs() {
+ let cases: &[(&str, &str)] = &[
+ (r#""plain""#, "plain"),
+ (r#""a\nb\t\"c\"""#, "a\nb\t\"c\""),
+ (r#""é$""#, "é$"),
+ (r#""😀""#, "😀"),
+ (r#""\ud800x""#, "\u{FFFD}x"), // lone high surrogate
+ ];
+ for (raw, expected) in cases {
+ let got = unescape(raw.as_bytes(), (0, raw.len())).unwrap();
+ assert_eq!(&got, expected, "case: {raw}");
+ }
+ }
+
+ #[test]
+ fn write_json_string_round_trips_through_serde() {
+ for s in ["plain", "with \"quotes\" and \\", "ctl\u{1}\n\t", "π😀"] {
+ let mut out = Vec::new();
+ write_json_string(s, &mut out);
+ let parsed: String = serde_json::from_slice(&out).unwrap();
+ assert_eq!(parsed, s);
+ }
+ }
+
+ #[test]
+ fn escaped_keys_are_flagged() {
+ // `data` parses to the key `data`; a byte scanner can't see that, so it must flag the
+ // escape and let the caller fall back to a real parse instead of missing a routing key.
+ let json = br#"{"\u0064ata": 1}"#;
+ let span = locate_value(json, 0).unwrap();
+ let e = object_entries(json, span).unwrap().next().unwrap().unwrap();
+ assert!(e.key_escaped, "escaped key must be flagged for fallback");
+ }
+}
diff --git a/rust/replay-anonymizer-node/src/snapshot.rs b/rust/replay-anonymizer-node/src/snapshot.rs
new file mode 100644
index 000000000000..58f6b9bac35a
--- /dev/null
+++ b/rust/replay-anonymizer-node/src/snapshot.rs
@@ -0,0 +1,1355 @@
+//! Anonymize one decompressed replay Kafka payload end-to-end: Rust owns the parse, the scrub, and
+//! the serialize (the byte-buffer FFI shape). The TS consumer hands over the raw payload bytes and
+//! gets back ready-to-write JSONL block lines plus the envelope/per-event metadata its batching
+//! scaffolding needs — no JSON crosses the FFI boundary as a string in either direction.
+//!
+//! Two implementations produce the output:
+//!
+//! - **Streaming** (`scan_envelope` + `process_event`): scans the payload bytes for the
+//! `$snapshot_items` spans, memcpys pass-through events verbatim, and parses only the `data` span
+//! of scrub-routed events, splicing the rewritten span back between the untouched bytes. This is
+//! the hot path.
+//! - **Tree** (`anonymize_via_tree`): parses the whole payload and walks it. It is the reference the
+//! differential tests check the streaming path against, and the production fallback whenever the
+//! scanner meets something it cannot prove safe (escaped keys, duplicate routing keys) — JSON.parse
+//! semantics like last-duplicate-wins and escape normalization only fall out of a real parse.
+//!
+//! Both paths share `route_data` (the single routing/scrub implementation) and the meta extraction
+//! helpers, so they can only disagree on envelope/iteration mechanics — which is exactly what the
+//! differential tests pin down.
+//!
+//! Fail-closed: any scrub error, or any input the scanner *and* the tree path cannot make sense of,
+//! is an error — the caller drops (or DLQs) the message rather than letting un-anonymized bytes
+//! through.
+
+use serde::Serialize;
+use simd_json::borrowed::Value;
+use simd_json::prelude::Writable;
+
+use crate::allow_lists::AllowLists;
+use crate::context::Ctx;
+use crate::event::{
+ route_data, route_event, SOURCE_CANVAS_MUTATION, SOURCE_INPUT, SOURCE_MUTATION, TYPE_CUSTOM,
+ TYPE_FULL_SNAPSHOT, TYPE_INCREMENTAL, TYPE_META, TYPE_PLUGIN,
+};
+use crate::json::{
+ as_f64, as_object, as_small_uint, as_str, parse_untrusted, parse_untrusted_with_buffers,
+ reject_if_too_deep,
+};
+use crate::scan::{self, Span};
+
+/// Why a payload could not be anonymized; maps onto the TS pipeline's dlq/drop reasons so the fused
+/// step classifies failures exactly like the TS parse step does.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum FailKind {
+ /// The Kafka message value could not be decompressed (dlq `invalid_compressed_data`).
+ InvalidCompressedData,
+ /// The outer Kafka payload is not valid JSON (dlq `invalid_json`).
+ InvalidJson,
+ /// The outer payload parses but lacks `distinct_id`/`data` strings (dlq `invalid_message_payload`).
+ InvalidMessagePayload,
+ /// The inner event is not a `$snapshot_items` message (dlq `received_non_snapshot_message`).
+ NonSnapshotMessage,
+ /// Every event was filtered out (drop `message_contained_no_valid_rrweb_events`).
+ NoValidEvents,
+ /// An event could not be scrubbed — fail closed (drop `anonymize_failed`).
+ AnonymizeFailed,
+}
+
+impl FailKind {
+ pub fn reason(self) -> &'static str {
+ match self {
+ FailKind::InvalidCompressedData => "invalid_compressed_data",
+ FailKind::InvalidJson => "invalid_json",
+ FailKind::InvalidMessagePayload => "invalid_message_payload",
+ FailKind::NonSnapshotMessage => "received_non_snapshot_message",
+ FailKind::NoValidEvents => "message_contained_no_valid_rrweb_events",
+ FailKind::AnonymizeFailed => "anonymize_failed",
+ }
+ }
+}
+
+#[derive(Debug)]
+pub struct Failure {
+ pub kind: FailKind,
+ pub detail: String,
+}
+
+impl Failure {
+ fn new(kind: FailKind, detail: impl Into<String>) -> Self {
+ Self {
+ kind,
+ detail: detail.into(),
+ }
+ }
+}
+
+type SResult<T> = Result<T, Failure>;
+
+// Per-event flags, mirroring `rrweb-types.ts` / `segmentation.ts` predicates.
+pub const FLAG_ACTIVE: u8 = 1;
+pub const FLAG_CLICK: u8 = 2;
+pub const FLAG_KEYPRESS: u8 = 4;
+pub const FLAG_MOUSE_ACTIVITY: u8 = 8;
+
+// `DateTime.fromMillis` validity bound (JS Date range: ±8.64e15 ms).
+const MAX_JS_DATE_MS: f64 = 8.64e15;
+
+/// Per-emitted-line metadata, in line order.
+#[derive(Debug, Clone, Serialize, PartialEq)]
+pub struct EventMeta {
+ /// The event's `timestamp` (epoch ms; can be fractional).
+ pub ts: f64,
+ /// Bitmask of FLAG_ACTIVE / FLAG_CLICK / FLAG_KEYPRESS / FLAG_MOUSE_ACTIVITY.
+ pub flags: u8,
+ /// Post-scrub `hrefFrom(event)` (`data.href` or `data.payload.href`, trimmed, non-empty).
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub href: Option<String>,
+}
+
+/// Message envelope + per-event metadata the TS scaffolding needs for routing/batching.
+#[derive(Debug, Serialize, PartialEq)]
+#[serde(rename_all = "camelCase")]
+pub struct SnapshotMeta {
+ pub distinct_id: String,
+ /// Raw `$session_id` (normalization stays in TS).
+ pub session_id: String,
+ /// `$window_id ?? ''`.
+ pub window_id: String,
+ pub snapshot_source: Option<String>,
+ pub snapshot_library: Option<String>,
+ /// Min/max valid-event timestamps (epoch ms).
+ pub start_ts: f64,
+ pub end_ts: f64,
+ /// rrweb/console@1 plugin events by level, for the console-log block metadata counts.
+ pub console_log_count: u32,
+ pub console_warn_count: u32,
+ pub console_error_count: u32,
+ pub events: Vec<EventMeta>,
+}
+
+/// Which implementation produced the output (tree = the whole-message fallback fired). Both are
+/// differential-tested identical. Deliberately not part of [`SnapshotMeta`]: the differential tests
+/// assert meta equality across paths.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum Route {
+ Stream,
+ Tree,
+}
+
+impl Route {
+ pub fn as_str(self) -> &'static str {
+ match self {
+ Route::Stream => "stream",
+ Route::Tree => "tree",
+ }
+ }
+}
+
+/// Options for the anonymize entry points. `Default` is the production configuration.
+#[derive(Debug, Clone, Copy)]
+pub struct AnonymizeOpts {
+ /// Scrub the bulk routes (snapshots, mutations, inputs) with the parse-free byte walk
+ /// ([`crate::bytewalk`]) instead of a simd-json tree; anything the walk can't prove safe falls
+ /// back to the parse per event. The differential tests pin both engines by toggling this.
+ pub byte_walk: bool,
+}
+
+impl Default for AnonymizeOpts {
+ fn default() -> Self {
+ Self { byte_walk: true }
+ }
+}
+
+#[derive(Debug)]
+pub struct AnonymizedMessage {
+ /// Scrubbed JSONL: one `["<windowId>",<event>]\n` line per valid event, in input order.
+ pub lines: Vec<u8>,
+ pub meta: SnapshotMeta,
+ pub route: Route,
+}
+
+/// Decompressed payloads are capped (shared with the gzip codec's bomb cap) so a forged lz4 size
+/// prefix (a u32, so up to 4 GiB) cannot force the allocation; real replay payloads decompress to
+/// tens of MB at most.
+const MAX_DECOMPRESSED_LEN: usize = crate::gzip::MAX_DECOMPRESSED_BYTES;
+
+const GZIP_MAGIC: &[u8; 4] = &[0x1f, 0x8b, 0x08, 0x00];
+
+/// Decompress a raw Kafka message value the way capture wraps it (mirrors the TS
+/// `decompressMessageValue`): lz4 block with a 4-byte LE uncompressed-size prefix when the
+/// `content-encoding` header says lz4, gzip when the magic bytes say so, else pass through.
+pub fn decompress_payload(raw: Vec<u8>, content_encoding: Option<&str>) -> SResult<Vec<u8>> {
+ let bad = |detail: &str| Failure::new(FailKind::InvalidCompressedData, detail);
+ if content_encoding == Some("lz4") {
+ let size_bytes: [u8; 4] = raw
+ .get(..4)
+ .and_then(|b| b.try_into().ok())
+ .ok_or_else(|| bad("lz4 payload too short for size prefix"))?;
+ let size = u32::from_le_bytes(size_bytes) as usize;
+ if size > MAX_DECOMPRESSED_LEN {
+ return Err(bad("lz4 uncompressed size exceeds limit"));
+ }
+ let out = lz4::block::decompress(&raw[4..], Some(size as i32))
+ .map_err(|e| bad(&format!("lz4 decompress failed: {e}")))?;
+ // Classify a lying size prefix as invalid_compressed_data (matching the TS path) rather
+ // than letting the short/long buffer surface later as invalid_json.
+ if out.len() != size {
+ return Err(bad("lz4 decoded length does not match the size prefix"));
+ }
+ return Ok(out);
+ }
+ if raw.starts_with(GZIP_MAGIC) {
+ return crate::gzip::gunzip(&raw).map_err(|e| bad(&format!("gzip decompress failed: {e}")));
+ }
+ Ok(raw)
+}
+
+/// Anonymize a decompressed replay Kafka payload (`{"distinct_id": ..., "data": "<event json>"}`).
+/// The buffer is scratch space — the fallback parse unescapes strings in place.
+///
+/// The envelope is scanned, not parsed: a full parse funnels the multi-MB `data` string through
+/// simd-json's tape just to unescape it, where the scan locates the two values and unescapes `data`
+/// in one memchr-accelerated pass. Anything the scanner can't prove out (escaped or duplicate keys,
+/// structural surprises) falls back to the parse, which also owns failure classification — so
+/// dlq/drop reasons for malformed payloads come out exactly as before.
+pub fn anonymize_kafka_payload(
+ allow: &AllowLists,
+ payload: &mut [u8],
+) -> SResult<AnonymizedMessage> {
+ anonymize_kafka_payload_opts(allow, payload, AnonymizeOpts::default())
+}
+
+pub fn anonymize_kafka_payload_opts(
+ allow: &AllowLists,
+ payload: &mut [u8],
+ opts: AnonymizeOpts,
+) -> SResult<AnonymizedMessage> {
+ if let Some((distinct_id_span, data_span)) = scan_outer_envelope(payload) {
+ // Resolve distinct_id to an owned string first — the unescape below rewrites the buffer.
+ let Ok(distinct_id) = scan::unescape(payload, distinct_id_span) else {
+ return anonymize_kafka_payload_via_parse(allow, payload, opts);
+ };
+ let distinct_id = distinct_id.into_owned();
+ // Point of no return: the in-place unescape consumes the buffer, so failures past here are
+ // classified directly (as the parse would have: undecodable data -> invalid JSON), never
+ // retried against the now-rewritten bytes.
+ let (len, ascii) = scan::unescape_in_place(payload, data_span)
+ .map_err(|e| Failure::new(FailKind::InvalidJson, format!("data string: {}", e.0)))?;
+ let inner = &mut payload[data_span.0 + 1..data_span.0 + 1 + len];
+ // The parse it replaces validated the whole payload's UTF-8; the scan path must not let
+ // invalid bytes flow through pass-through events into the output. The unescape already
+ // proved ASCII output valid; only non-ASCII output needs the real check.
+ if !ascii && std::str::from_utf8(inner).is_err() {
+ return Err(Failure::new(
+ FailKind::InvalidJson,
+ "invalid utf-8 in data string",
+ ));
+ }
+ return anonymize_snapshot_data_opts(allow, &distinct_id, inner, opts);
+ }
+ anonymize_kafka_payload_via_parse(allow, payload, opts)
+}
+
+/// Locate the `distinct_id` + `data` string spans by scanning the outer object. `None` means "let
+/// the full parse decide": escaped/duplicate/missing keys, non-string values, or any structural
+/// anomaly.
+///
+/// One pass: entries are walked directly (no up-front root-span location, which would scan the
+/// multi-MB `data` value a second time).
+fn scan_outer_envelope(payload: &[u8]) -> Option<(Span, Span)> {
+ let mut pos = scan::skip_ws(payload, 0);
+ if payload.get(pos) != Some(&b'{') {
+ return None;
+ }
+ pos += 1;
+ let mut distinct_id: Option<Span> = None;
+ let mut data: Option<Span> = None;
+ let mut first = true;
+ loop {
+ pos = scan::skip_ws(payload, pos);
+ // At an entry boundary a `}` can only be the object's close (a key must start with `"`).
+ if payload.get(pos) == Some(&b'}') {
+ pos += 1;
+ break;
+ }
+ if !first {
+ if payload.get(pos) != Some(&b',') {
+ return None;
+ }
+ pos = scan::skip_ws(payload, pos + 1);
+ }
+ first = false;
+ if payload.get(pos) != Some(&b'"') {
+ return None;
+ }
+ let key_end = scan::skip_string(payload, pos).ok()?;
+ let key = &payload[pos + 1..key_end - 1];
+ if key.contains(&b'\\') {
+ return None;
+ }
+ pos = scan::skip_ws(payload, key_end);
+ if payload.get(pos) != Some(&b':') {
+ return None;
+ }
+ let value = scan::locate_value(payload, pos + 1).ok()?;
+ match key {
+ // Duplicates bail to the parse so its semantics keep applying.
+ b"distinct_id" => {
+ if distinct_id.replace(value).is_some() {
+ return None;
+ }
+ }
+ b"data" => {
+ if data.replace(value).is_some() {
+ return None;
+ }
+ }
+ _ => {}
+ }
+ pos = value.1;
+ }
+ if scan::skip_ws(payload, pos) != payload.len() {
+ return None;
+ }
+ let (distinct_id, data) = (distinct_id?, data?);
+ if !scan::is_string(payload, distinct_id) || !scan::is_string(payload, data) {
+ return None;
+ }
+ Some((distinct_id, data))
+}
+
+fn anonymize_kafka_payload_via_parse(
+ allow: &AllowLists,
+ payload: &mut [u8],
+ opts: AnonymizeOpts,
+) -> SResult<AnonymizedMessage> {
+ reject_if_too_deep(payload, "kafka payload")
+ .map_err(|e| Failure::new(FailKind::InvalidJson, e.to_string()))?;
+ let outer = simd_json::to_borrowed_value(payload)
+ .map_err(|e| Failure::new(FailKind::InvalidJson, e.to_string()))?;
+ let Some(obj) = as_object(&outer) else {
+ return Err(Failure::new(
+ FailKind::InvalidMessagePayload,
+ "payload is not an object",
+ ));
+ };
+ let Some(distinct_id) = obj.get("distinct_id").and_then(as_str) else {
+ return Err(Failure::new(
+ FailKind::InvalidMessagePayload,
+ "missing distinct_id string",
+ ));
+ };
+ let Some(data) = obj.get("data").and_then(as_str) else {
+ return Err(Failure::new(
+ FailKind::InvalidMessagePayload,
+ "missing data string",
+ ));
+ };
+ // Rare path (the scanner bailed): one owned copy buys the in-place processing a mutable buffer.
+ let mut data_bytes = data.as_bytes().to_vec();
+ anonymize_snapshot_data_opts(allow, distinct_id, &mut data_bytes, opts)
+}
+
+/// Anonymize the inner `$snapshot_items` event JSON (the payload's `data` string). The buffer is
+/// consumed: scrub-routed data spans are parsed in place (each is fully re-serialized from its
+/// tree, so nothing reads a consumed span afterwards).
+pub fn anonymize_snapshot_data(
+ allow: &AllowLists,
+ distinct_id: &str,
+ inner: &mut [u8],
+) -> SResult<AnonymizedMessage> {
+ anonymize_snapshot_data_opts(allow, distinct_id, inner, AnonymizeOpts::default())
+}
+
+pub fn anonymize_snapshot_data_opts(
+ allow: &AllowLists,
+ distinct_id: &str,
+ inner: &mut [u8],
+ opts: AnonymizeOpts,
+) -> SResult<AnonymizedMessage> {
+ // No whole-message depth pre-pass here: the byte walk bounds its own recursion and declines
+ // past its limit, and every recursive parse below is preceded by a span-local
+ // reject_if_too_deep — so the common all-walked path never pays a depth scan at all.
+ let ctx = Ctx::new(allow);
+ match stream_message(&ctx, distinct_id, inner, opts)? {
+ Some(msg) => Ok(msg),
+ // Escaped/duplicate envelope keys: only a real parse resolves them, and nothing was
+ // consumed before the signal, so the tree path re-reads the intact buffer.
+ None => anonymize_via_tree_mut(&ctx, distinct_id, inner),
+ }
+}
+
+const MAX_FAIL_DETAIL: usize = 200;
+
+fn non_snapshot(detail: impl Into<String>) -> Failure {
+ let mut detail: String = detail.into();
+ detail.truncate(MAX_FAIL_DETAIL);
+ Failure::new(FailKind::NonSnapshotMessage, detail)
+}
+
+// ---------------------------------------------------------------------------
+// Streaming path
+// ---------------------------------------------------------------------------
+
+struct ScannedEnvelope {
+ session_id: String,
+ window_id: Option<String>,
+ snapshot_source: Option<String>,
+ snapshot_library: Option<String>,
+}
+
+/// One fused walk over the whole message: envelope fields are captured as they pass, and the
+/// events are processed inline the moment `$snapshot_items` is reached — the array is never
+/// pre-skipped just to finish the envelope first. Because prod key order puts `$window_id` after
+/// the items, events emit prefix-less bodies (`Sink.line_starts`) and `finish` frames them once
+/// the envelope is complete.
+///
+/// Error precedence matches the unfused code (envelope validation used to run before any event):
+/// event failures are stashed while the envelope walk completes, envelope validation errors win,
+/// and only then does a stashed event error surface. Escaped/duplicate envelope keys after events
+/// have consumed the buffer in place cannot fall back to the parse — that combination (multi-MB of
+/// scrub data plus a mangled envelope key behind the items) fails closed instead.
+fn stream_message(
+ ctx: &Ctx<'_>,
+ distinct_id: &str,
+ inner: &mut [u8],
+ opts: AnonymizeOpts,
+) -> SResult<Option<AnonymizedMessage>> {
+ let start = scan::skip_ws(inner, 0);
+ if inner.get(start) != Some(&b'{') {
+ // Preserve the old classification for non-object roots (including trailing-byte checks).
+ let root = scan::locate_value(inner, 0).map_err(|e| non_snapshot(e.0))?;
+ if scan::skip_ws(inner, root.1) != inner.len() {
+ return Err(non_snapshot("trailing bytes after event json"));
+ }
+ return Err(non_snapshot("event json is not an object"));
+ }
+
+ let mut sink = Sink::new(inner.len() - start);
+ let mut event_span: Option<Span> = None;
+ let mut saw_props = false;
+ let mut session_id_span: Option<Span> = None;
+ let mut window_id_span: Option<Span> = None;
+ let mut snapshot_source_span: Option<Span> = None;
+ let mut lib_span: Option<Span> = None;
+ let mut saw_items = false;
+ let mut items_not_array = false;
+ // First event-processing failure; surfaced only after envelope validation passes.
+ let mut deferred: Option<Failure> = None;
+
+ // Escaped or duplicate envelope keys need JSON.parse semantics — the tree run. That is only
+ // possible while the buffer is intact.
+ macro_rules! need_full_parse {
+ () => {{
+ if sink.mutated {
+ return Err(non_snapshot(
+ "envelope key needs a full parse after events were consumed",
+ ));
+ }
+ return Ok(None);
+ }};
+ }
+
+ let mut pos = start + 1;
+ let mut first = true;
+ let root_end = loop {
+ pos = scan::skip_ws(inner, pos);
+ if inner.get(pos) == Some(&b'}') {
+ break pos + 1;
+ }
+ if !first {
+ if inner.get(pos) != Some(&b',') {
+ return Err(non_snapshot("expected ',' between object entries"));
+ }
+ pos = scan::skip_ws(inner, pos + 1);
+ }
+ first = false;
+ if inner.get(pos) != Some(&b'"') {
+ return Err(non_snapshot("expected object key"));
+ }
+ let key_end = scan::skip_string(inner, pos).map_err(|e| non_snapshot(e.0))?;
+ let key_span = (pos + 1, key_end - 1);
+ if inner[key_span.0..key_span.1].contains(&b'\\') {
+ need_full_parse!();
+ }
+ pos = scan::skip_ws(inner, key_end);
+ if inner.get(pos) != Some(&b':') {
+ return Err(non_snapshot("expected ':' after object key"));
+ }
+ pos += 1;
+ let vstart = scan::skip_ws(inner, pos);
+ match &inner[key_span.0..key_span.1] {
+ b"properties" => {
+ if saw_props {
+ need_full_parse!();
+ }
+ saw_props = true;
+ if inner.get(vstart) != Some(&b'{') {
+ // Recorded as present-but-wrong; validation below reports it like before.
+ let vspan = scan::locate_value(inner, vstart).map_err(|e| non_snapshot(e.0))?;
+ pos = vspan.1;
+ session_id_span = None;
+ saw_props = false; // "missing properties object", matching the old filter
+ continue;
+ }
+ // Inline props walk.
+ let mut ppos = vstart + 1;
+ let mut pfirst = true;
+ pos = loop {
+ ppos = scan::skip_ws(inner, ppos);
+ if inner.get(ppos) == Some(&b'}') {
+ break ppos + 1;
+ }
+ if !pfirst {
+ if inner.get(ppos) != Some(&b',') {
+ return Err(non_snapshot("expected ',' between object entries"));
+ }
+ ppos = scan::skip_ws(inner, ppos + 1);
+ }
+ pfirst = false;
+ if inner.get(ppos) != Some(&b'"') {
+ return Err(non_snapshot("expected object key"));
+ }
+ let pkey_end = scan::skip_string(inner, ppos).map_err(|e| non_snapshot(e.0))?;
+ let pkey = (ppos + 1, pkey_end - 1);
+ if inner[pkey.0..pkey.1].contains(&b'\\') {
+ need_full_parse!();
+ }
+ ppos = scan::skip_ws(inner, pkey_end);
+ if inner.get(ppos) != Some(&b':') {
+ return Err(non_snapshot("expected ':' after object key"));
+ }
+ let pvstart = scan::skip_ws(inner, ppos + 1);
+ match &inner[pkey.0..pkey.1] {
+ b"$snapshot_items" => {
+ if saw_items || items_not_array {
+ need_full_parse!();
+ }
+ saw_items = true;
+ if inner.get(pvstart) != Some(&b'[') {
+ items_not_array = true;
+ let vspan = scan::locate_value(inner, pvstart)
+ .map_err(|e| non_snapshot(e.0))?;
+ ppos = vspan.1;
+ continue;
+ }
+ // Stream the events right here. After a deferred failure, the remaining
+ // items are only skipped to find the array's end.
+ let mut ipos = pvstart + 1;
+ let mut ifirst = true;
+ loop {
+ ipos = scan::skip_ws(inner, ipos);
+ if inner.get(ipos) == Some(&b']') {
+ ipos += 1;
+ break;
+ }
+ if !ifirst {
+ if inner.get(ipos) != Some(&b',') {
+ return Err(non_snapshot(
+ "expected ',' between array items",
+ ));
+ }
+ ipos += 1;
+ }
+ ifirst = false;
+ if deferred.is_some() {
+ let span = scan::locate_value(inner, ipos)
+ .map_err(|e| non_snapshot(e.0))?;
+ ipos = span.1;
+ continue;
+ }
+ match process_event_at(ctx, inner, ipos, &mut sink, opts) {
+ Ok(p) => ipos = p,
+ Err(e) => {
+ deferred = Some(e);
+ let span = scan::locate_value(inner, ipos)
+ .map_err(|e| non_snapshot(e.0))?;
+ ipos = span.1;
+ }
+ }
+ }
+ ppos = ipos;
+ }
+ b"$session_id" => {
+ if session_id_span
+ .replace(scan_prop_value(inner, pvstart, &mut ppos)?)
+ .is_some()
+ {
+ need_full_parse!();
+ }
+ }
+ b"$window_id" => {
+ if window_id_span
+ .replace(scan_prop_value(inner, pvstart, &mut ppos)?)
+ .is_some()
+ {
+ need_full_parse!();
+ }
+ }
+ b"$snapshot_source" => {
+ if snapshot_source_span
+ .replace(scan_prop_value(inner, pvstart, &mut ppos)?)
+ .is_some()
+ {
+ need_full_parse!();
+ }
+ }
+ b"$lib" => {
+ if lib_span
+ .replace(scan_prop_value(inner, pvstart, &mut ppos)?)
+ .is_some()
+ {
+ need_full_parse!();
+ }
+ }
+ _ => {
+ let vspan = scan::locate_value(inner, pvstart)
+ .map_err(|e| non_snapshot(e.0))?;
+ ppos = vspan.1;
+ }
+ }
+ };
+ }
+ b"event" => {
+ let vspan = scan::locate_value(inner, vstart).map_err(|e| non_snapshot(e.0))?;
+ if event_span.replace(vspan).is_some() {
+ need_full_parse!();
+ }
+ pos = vspan.1;
+ }
+ _ => {
+ let vspan = scan::locate_value(inner, vstart).map_err(|e| non_snapshot(e.0))?;
+ pos = vspan.1;
+ }
+ }
+ };
+ if scan::skip_ws(inner, root_end) != inner.len() {
+ return Err(non_snapshot("trailing bytes after event json"));
+ }
+
+ // Envelope validation, with the same messages and precedence as when it ran before the events.
+ let Some(event_span) = event_span.filter(|s| scan::is_string(inner, *s)) else {
+ return Err(non_snapshot("missing event name"));
+ };
+ let event_name = scan::unescape(inner, event_span).map_err(|e| non_snapshot(e.0))?;
+ if event_name != "$snapshot_items" {
+ return Err(non_snapshot("not a $snapshot_items event"));
+ }
+ if !saw_props {
+ return Err(non_snapshot("missing properties object"));
+ }
+ if !saw_items {
+ return Err(non_snapshot("missing $snapshot_items"));
+ }
+ if items_not_array {
+ return Err(non_snapshot("$snapshot_items is not an array"));
+ }
+ let session_id = match session_id_span {
+ Some(s) if scan::is_string(inner, s) => {
+ scan::unescape(inner, s).map_err(|e| non_snapshot(e.0))?
+ }
+ Some(_) => return Err(non_snapshot("$session_id is not a string")),
+ None => return Err(non_snapshot("missing $session_id")),
+ };
+ if session_id.is_empty() {
+ return Err(non_snapshot("empty $session_id"));
+ }
+ let opt_string = |span: Option<Span>, name: &str| -> SResult<Option<String>> {
+ match span {
+ None => Ok(None),
+ Some(s) if scan::is_string(inner, s) => scan::unescape(inner, s)
+ .map(|c| Some(c.into_owned()))
+ .map_err(|e| non_snapshot(e.0)),
+ Some(_) => Err(non_snapshot(format!("{name} is not a string"))),
+ }
+ };
+ let env = ScannedEnvelope {
+ session_id: session_id.into_owned(),
+ window_id: opt_string(window_id_span, "$window_id")?,
+ snapshot_source: opt_string(snapshot_source_span, "$snapshot_source")?,
+ snapshot_library: opt_string(lib_span, "$lib")?,
+ };
+
+ if let Some(e) = deferred {
+ return Err(e);
+ }
+ finish(distinct_id, env, sink, Route::Stream).map(Some)
+}
+
+/// Locate a props value span and advance the cursor past it.
+fn scan_prop_value(inner: &[u8], vstart: usize, ppos: &mut usize) -> SResult<Span> {
+ let vspan = scan::locate_value(inner, vstart).map_err(|e| non_snapshot(e.0))?;
+ *ppos = vspan.1;
+ Ok(vspan)
+}
+
+/// Shared per-message accumulation state. Lines accumulate as prefix-less event bodies with their
+/// start offsets recorded; `finish` frames them (`["<windowId>",` ... `]\n`) once the envelope —
+/// which may complete after the events in prod key order — is known.
+struct Sink {
+ lines: Vec<u8>,
+ /// Start offset of each emitted body in `lines` (one per entry in `events`).
+ line_starts: Vec<usize>,
+ events: Vec<EventMeta>,
+ console: [u32; 3], // info, warn, error
+ /// simd-json scratch reused across the per-event parses.
+ buffers: simd_json::Buffers,
+ /// Whether an in-place parse has consumed a span yet — the tree fallback is only sound while
+ /// the buffer is intact.
+ mutated: bool,
+ /// Copy-parse budget for early scrub events: keeping the buffer intact through them preserves
+ /// the tree fallback for escaped/duplicate envelope keys discovered later in the walk. Small
+ /// events parse from `scratch` until the budget runs out; everything after parses in place.
+ scratch_budget: usize,
+ scratch: Vec<u8>,
+}
+
+impl Sink {
+ fn new(capacity_hint: usize) -> Self {
+ Self {
+ lines: Vec::with_capacity(capacity_hint + capacity_hint / 8),
+ line_starts: Vec::new(),
+ events: Vec::new(),
+ console: [0; 3],
+ buffers: simd_json::Buffers::default(),
+ mutated: false,
+ scratch_budget: SCRATCH_BUDGET,
+ scratch: Vec::new(),
+ }
+ }
+
+ /// Record that a body was emitted starting at `start` — call only once the emission is final
+ /// (declined attempts truncate `lines` and must leave no marker behind).
+ fn open_line_at(&mut self, start: usize) {
+ self.line_starts.push(start);
+ }
+}
+
+fn finish(
+ distinct_id: &str,
+ env: ScannedEnvelope,
+ sink: Sink,
+ route: Route,
+) -> SResult<AnonymizedMessage> {
+ if sink.events.is_empty() {
+ return Err(Failure::new(
+ FailKind::NoValidEvents,
+ "message contained no valid rrweb events",
+ ));
+ }
+ let start_ts = sink.events.iter().map(|e| e.ts).fold(f64::MAX, f64::min);
+ let end_ts = sink.events.iter().map(|e| e.ts).fold(f64::MIN, f64::max);
+ // Frame the prefix-less bodies into `["<windowId>",<event>]\n` lines.
+ let window_id_str = env.window_id.clone().unwrap_or_default();
+ let mut prefix = Vec::with_capacity(window_id_str.len() + 4);
+ prefix.push(b'[');
+ scan::write_json_string(&window_id_str, &mut prefix);
+ prefix.push(b',');
+ let n = sink.line_starts.len();
+ // An unpaired body/event mis-frames every later line, so fail closed rather than emit misaligned
+ // output (hard error, not a debug_assert).
+ if n != sink.events.len() {
+ return Err(Failure::new(
+ FailKind::AnonymizeFailed,
+ "internal: line/event count mismatch",
+ ));
+ }
+ let mut lines = Vec::with_capacity(sink.lines.len() + n * (prefix.len() + 2));
+ for i in 0..n {
+ let body_end = sink
+ .line_starts
+ .get(i + 1)
+ .copied()
+ .unwrap_or(sink.lines.len());
+ lines.extend_from_slice(&prefix);
+ lines.extend_from_slice(&sink.lines[sink.line_starts[i]..body_end]);
+ lines.extend_from_slice(b"]\n");
+ }
+ Ok(AnonymizedMessage {
+ lines,
+ route,
+ meta: SnapshotMeta {
+ distinct_id: distinct_id.to_string(),
+ session_id: env.session_id,
+ window_id: env.window_id.unwrap_or_default(),
+ snapshot_source: env.snapshot_source,
+ snapshot_library: env.snapshot_library,
+ start_ts,
+ end_ts,
+ console_log_count: sink.console[0],
+ console_warn_count: sink.console[1],
+ console_error_count: sink.console[2],
+ events: sink.events,
+ },
+ })
+}
+
+/// `SnapshotEventSchema` validity: an object with a numeric, positive, in-JS-`Date`-range timestamp.
+fn valid_timestamp(ts: Option<f64>) -> Option<f64> {
+ ts.filter(|t| *t > 0.0 && *t <= MAX_JS_DATE_MS)
+}
+
+fn to_small_uint(n: f64) -> Option<u8> {
+ (n.fract() == 0.0 && (0.0..=u8::MAX as f64).contains(&n)).then_some(n as u8)
+}
+
+/// Everything the router and the meta need from one event, captured in a single walk.
+#[derive(Default)]
+struct EventScan {
+ ty: Option<Span>,
+ ts: Option<Span>,
+ data: Option<Span>,
+ cv: Option<Span>,
+ data_is_object: bool,
+ // Depth-1 spans inside `data` (only set when `data_is_object`).
+ source: Option<Span>,
+ interaction: Option<Span>, // data.type
+ href: Option<Span>,
+ payload: Option<Span>,
+ /// Escaped or duplicate keys anywhere routing-relevant: only a real parse is safe.
+ fallback: bool,
+}
+
+/// Walk the event object starting at `start` (must be at `{`), capturing routing fields and the
+/// event's end position in one pass. A `data` object gets its depth-1 fields read by the same walk
+/// that discovers its end — the span skip `locate_value` would do reads the routing keys instead.
+fn scan_event(inner: &[u8], start: usize) -> SResult<(EventScan, usize)> {
+ let mut es = EventScan::default();
+ let mut seen = [false; 4];
+ let mut pos = start + 1;
+ let mut first = true;
+ loop {
+ pos = scan::skip_ws(inner, pos);
+ // At an entry boundary `}` can only close the object (keys must start with `"`).
+ if inner.get(pos) == Some(&b'}') {
+ return Ok((es, pos + 1));
+ }
+ if !first {
+ if inner.get(pos) != Some(&b',') {
+ return Err(non_snapshot("expected ',' between object entries"));
+ }
+ pos = scan::skip_ws(inner, pos + 1);
+ }
+ first = false;
+ if inner.get(pos) != Some(&b'"') {
+ return Err(non_snapshot("expected object key"));
+ }
+ let key_end = scan::skip_string(inner, pos).map_err(|e| non_snapshot(e.0))?;
+ let key = &inner[pos + 1..key_end - 1];
+ if key.contains(&b'\\') {
+ es.fallback = true;
+ }
+ pos = scan::skip_ws(inner, key_end);
+ if inner.get(pos) != Some(&b':') {
+ return Err(non_snapshot("expected ':' after object key"));
+ }
+ pos += 1;
+ let vstart = scan::skip_ws(inner, pos);
+ if key == b"data" && !seen[2] && inner.get(vstart) == Some(&b'{') {
+ seen[2] = true;
+ let dend = scan_event_data(inner, vstart, &mut es)?;
+ es.data = Some((vstart, dend));
+ es.data_is_object = true;
+ pos = dend;
+ continue;
+ }
+ let vspan = scan::locate_value(inner, vstart).map_err(|e| non_snapshot(e.0))?;
+ let (slot, idx) = match key {
+ b"type" => (&mut es.ty, 0),
+ b"timestamp" => (&mut es.ts, 1),
+ b"data" => (&mut es.data, 2),
+ b"cv" => (&mut es.cv, 3),
+ _ => {
+ pos = vspan.1;
+ continue;
+ }
+ };
+ if seen[idx] {
+ // A duplicate key means the raw bytes hold content JSON.parse would discard; only a
+ // real parse (which dedupes) is safe to emit.
+ es.fallback = true;
+ }
+ seen[idx] = true;
+ *slot = Some(vspan);
+ pos = vspan.1;
+ }
+}
+
+/// Depth-1 walk of an event's `data` object: captures the router/meta fields and returns the
+/// object's end position.
+fn scan_event_data(inner: &[u8], start: usize, es: &mut EventScan) -> SResult<usize> {
+ let mut seen = [false; 4];
+ let mut pos = start + 1;
+ let mut first = true;
+ loop {
+ pos = scan::skip_ws(inner, pos);
+ if inner.get(pos) == Some(&b'}') {
+ return Ok(pos + 1);
+ }
+ if !first {
+ if inner.get(pos) != Some(&b',') {
+ return Err(non_snapshot("expected ',' between object entries"));
+ }
+ pos = scan::skip_ws(inner, pos + 1);
+ }
+ first = false;
+ if inner.get(pos) != Some(&b'"') {
+ return Err(non_snapshot("expected object key"));
+ }
+ let key_end = scan::skip_string(inner, pos).map_err(|e| non_snapshot(e.0))?;
+ let key = &inner[pos + 1..key_end - 1];
+ if key.contains(&b'\\') {
+ es.fallback = true;
+ }
+ pos = scan::skip_ws(inner, key_end);
+ if inner.get(pos) != Some(&b':') {
+ return Err(non_snapshot("expected ':' after object key"));
+ }
+ let vspan = scan::locate_value(inner, pos + 1).map_err(|e| non_snapshot(e.0))?;
+ let (slot, idx) = match key {
+ b"source" => (&mut es.source, 0),
+ b"type" => (&mut es.interaction, 1),
+ b"href" => (&mut es.href, 2),
+ b"payload" => (&mut es.payload, 3),
+ _ => {
+ pos = vspan.1;
+ continue;
+ }
+ };
+ if seen[idx] {
+ es.fallback = true;
+ }
+ seen[idx] = true;
+ *slot = Some(vspan);
+ pos = vspan.1;
+ }
+}
+
+/// How many scrub-routed bytes may copy-parse via scratch before switching to in-place parses.
+const SCRATCH_BUDGET: usize = 64 * 1024;
+
+/// Process the array item starting at (or after whitespace from) `item_pos`; returns the position
+/// just past the event.
+fn process_event_at(
+ ctx: &Ctx<'_>,
+ inner: &mut [u8],
+ item_pos: usize,
+ sink: &mut Sink,
+ opts: AnonymizeOpts,
+) -> SResult<usize> {
+ let start = scan::skip_ws(inner, item_pos);
+ // Non-object events fail SnapshotEventSchema and are silently skipped, like the TS parse step.
+ if inner.get(start) != Some(&b'{') {
+ let span = scan::locate_value(inner, start).map_err(|e| non_snapshot(e.0))?;
+ return Ok(span.1);
+ }
+
+ let (es, end) = scan_event(inner, start)?;
+ let span = (start, end);
+
+ // Raw C0 controls route to the tree, which normalizes/rejects them like JSON.parse: `\n`/`\r`
+ // would break line framing if memcpy'd, the rest are invalid JSON the stream path would splice
+ // through verbatim (a stream-vs-tree divergence). The `< 0x20` scan autovectorizes.
+ if es.fallback || inner[span.0..span.1].iter().any(|&b| b < 0x20) {
+ process_event_via_tree(ctx, inner, span, sink)?;
+ return Ok(end);
+ }
+
+ let Some(ts) = valid_timestamp(es.ts.and_then(|s| scan::parse_number(inner, s))) else {
+ return Ok(end); // invalid/missing timestamp: the event is filtered out
+ };
+ let ty = es
+ .ty
+ .and_then(|s| scan::parse_number(inner, s))
+ .and_then(to_small_uint);
+ let compressed = es.cv.map(|s| !scan::is_null(inner, s)).unwrap_or(false);
+
+ // Everything the scrubbers touch lives inside `data`; events with no data object (or whose
+ // type/source never routes to a scrubber) pass through byte-identical.
+ let Some(data) = es.data else {
+ pass_through(inner, span, ts, ty, None, sink);
+ return Ok(end);
+ };
+
+ let needs_parse = match ty {
+ Some(TYPE_FULL_SNAPSHOT) => true,
+ Some(TYPE_INCREMENTAL) | Some(TYPE_META) | Some(TYPE_CUSTOM) | Some(TYPE_PLUGIN) => {
+ es.data_is_object
+ }
+ _ => false,
+ };
+ if !needs_parse {
+ pass_through(inner, span, ts, ty, es.data_is_object.then_some(&es), sink);
+ return Ok(end);
+ }
+
+ // Incremental events only route to a scrubber for mutation/input/canvas sources.
+ let source = es
+ .source
+ .and_then(|s| scan::parse_number(inner, s))
+ .and_then(to_small_uint);
+ if ty == Some(TYPE_INCREMENTAL)
+ && !matches!(
+ source,
+ Some(SOURCE_MUTATION) | Some(SOURCE_INPUT) | Some(SOURCE_CANVAS_MUTATION)
+ )
+ {
+ pass_through(inner, span, ts, ty, Some(&es), sink);
+ return Ok(end);
+ }
+
+ // Parse-free byte walk first: the bulk routes get scrubbed straight from the bytes, with
+ // unchanged values copied verbatim. The walk proves every object duplicate-key-free as it goes,
+ // which is what makes emitting original bytes safe (no shadowed duplicate content can survive);
+ // anything it can't prove — escaped keys, cv payloads, canvas/meta/custom/plugin routes — is
+ // declined and handled by the parse below. The walk never mutates the buffer, so falling
+ // through stays sound.
+ if opts.byte_walk {
+ let mark = sink.lines.len();
+ sink.lines.extend_from_slice(&inner[span.0..data.0]);
+ let data_mark = sink.lines.len();
+ match crate::bytewalk::scrub_data_bytes(
+ ctx,
+ ty,
+ source,
+ compressed,
+ inner,
+ data,
+ &mut sink.lines,
+ ) {
+ Some(changed) => {
+ if !changed {
+ // Nothing changed and the span is proven dup-free: keep the original bytes.
+ sink.lines.truncate(data_mark);
+ sink.lines.extend_from_slice(&inner[data.0..data.1]);
+ }
+ sink.lines.extend_from_slice(&inner[data.1..span.1]);
+ sink.open_line_at(mark);
+ // These routes never scrub data.href/source/type, so the scanned (pre-scrub)
+ // values equal what the tree path reads post-scrub.
+ let interaction = es
+ .interaction
+ .and_then(|s| scan::parse_number(inner, s))
+ .and_then(to_small_uint);
+ sink.events.push(EventMeta {
+ ts,
+ flags: flags_of(ty, source, interaction),
+ href: scanned_href(inner, &es),
+ });
+ return Ok(end);
+ }
+ None => sink.lines.truncate(mark),
+ }
+ }
+
+ // Scrub route: parse the data span — in place for the bulk (simd-json only mutates within the
+ // span, and the splice reads only the disjoint prefix/suffix), via a bounded scratch copy for
+ // small early events (see `scratch_budget`) — then splice the re-serialized value back between
+ // the untouched surrounding bytes. The splice happens even when nothing changed: JSON.parse
+ // dedupes duplicate keys, so re-serializing from the parsed tree guarantees no shadowed
+ // duplicate content inside `data` survives in the raw bytes. Later events sit entirely past
+ // `end`, so a consumed span is never re-read.
+ reject_if_too_deep(&inner[data.0..data.1], "snapshot event json")
+ .map_err(|e| Failure::new(FailKind::NonSnapshotMessage, e.to_string()))?;
+ let use_scratch = !sink.mutated && (data.1 - data.0) <= sink.scratch_budget;
+ if use_scratch {
+ sink.scratch_budget -= data.1 - data.0;
+ } else {
+ sink.mutated = true;
+ }
+ let mut buffers = std::mem::take(&mut sink.buffers);
+ let mut scratch = std::mem::take(&mut sink.scratch);
+ let result = (|| -> SResult<()> {
+ let (prefix, data_bytes, suffix): (&[u8], &mut [u8], &[u8]) = if use_scratch {
+ scratch.clear();
+ scratch.extend_from_slice(&inner[data.0..data.1]);
+ (
+ &inner[span.0..data.0],
+ &mut scratch[..],
+ &inner[data.1..span.1],
+ )
+ } else {
+ let (before, rest) = inner.split_at_mut(data.0);
+ let (data_bytes, after) = rest.split_at_mut(data.1 - data.0);
+ (&before[span.0..], data_bytes, &after[..span.1 - data.1])
+ };
+ let mut value = parse_untrusted_with_buffers(data_bytes, &mut buffers)
+ .map_err(|e| non_snapshot(format!("event data: {e}")))?;
+ route_data(ctx, ty, compressed, &mut value)
+ .map_err(|e| Failure::new(FailKind::AnonymizeFailed, e.to_string()))?;
+ let line_start = sink.lines.len();
+ sink.lines.extend_from_slice(prefix);
+ value
+ .write(&mut sink.lines)
+ .expect("writing json to a Vec cannot fail");
+ sink.lines.extend_from_slice(suffix);
+ sink.open_line_at(line_start);
+ push_meta_from_data(ty, ts, Some(&value), sink);
+ Ok(())
+ })();
+ sink.buffers = buffers;
+ scratch.clear();
+ sink.scratch = scratch;
+ result?;
+ Ok(end)
+}
+
+/// Emit a pass-through event: memcpy the span, derive meta from the scans.
+fn pass_through(
+ inner: &[u8],
+ span: Span,
+ ts: f64,
+ ty: Option<u8>,
+ data: Option<&EventScan>,
+ sink: &mut Sink,
+) {
+ let line_start = sink.lines.len();
+ sink.lines.extend_from_slice(&inner[span.0..span.1]);
+ sink.open_line_at(line_start);
+
+ let (source, interaction, href) = match data {
+ Some(d) => (
+ d.source
+ .and_then(|s| scan::parse_number(inner, s))
+ .and_then(to_small_uint),
+ d.interaction
+ .and_then(|s| scan::parse_number(inner, s))
+ .and_then(to_small_uint),
+ scanned_href(inner, d),
+ ),
+ None => (None, None, None),
+ };
+ sink.events.push(EventMeta {
+ ts,
+ flags: flags_of(ty, source, interaction),
+ href,
+ });
+}
+
+/// `hrefFrom` over scanned spans: `data.href` (string, trimmed, non-empty) falling back to
+/// `data.payload.href`.
+fn scanned_href(inner: &[u8], d: &EventScan) -> Option<String> {
+ let read = |span: Span| -> Option<String> {
+ if !scan::is_string(inner, span) {
+ return None;
+ }
+ let s = scan::unescape(inner, span).ok()?;
+ let t = s.trim();
+ (!t.is_empty()).then(|| t.to_string())
+ };
+ if let Some(h) = d.href.and_then(read) {
+ return Some(h);
+ }
+ let payload = d.payload.filter(|p| scan::is_object(inner, *p))?;
+ let mut href: Option<Span> = None;
+ for entry in scan::object_entries(inner, payload).ok()? {
+ let entry = entry.ok()?;
+ if entry.key_escaped {
+ return None; // vanishingly rare; href meta is best-effort here
+ }
+ if &inner[entry.key.0..entry.key.1] == b"href" {
+ href = Some(entry.value);
+ }
+ }
+ href.and_then(read)
+}
+
+fn flags_of(ty: Option<u8>, source: Option<u8>, interaction: Option<u8>) -> u8 {
+ if ty != Some(TYPE_INCREMENTAL) {
+ return 0;
+ }
+ let Some(s) = source else {
+ return 0;
+ };
+ let mut flags = 0u8;
+ // activeSources: MouseMove, MouseInteraction, Scroll, ViewportResize, Input, TouchMove,
+ // MediaInteraction, Drag.
+ if matches!(s, 1..=7 | 12) {
+ flags |= FLAG_ACTIVE;
+ }
+ // CLICK_TYPES: Click, ContextMenu, DblClick, TouchEnd.
+ if s == 2 && matches!(interaction, Some(2) | Some(3) | Some(4) | Some(9)) {
+ flags |= FLAG_CLICK;
+ }
+ if s == SOURCE_INPUT {
+ flags |= FLAG_KEYPRESS;
+ }
+ // MOUSE_ACTIVITY_SOURCES: MouseInteraction, MouseMove, TouchMove.
+ if matches!(s, 1 | 2 | 6) {
+ flags |= FLAG_MOUSE_ACTIVITY;
+ }
+ flags
+}
+
+/// Meta + console counts from a parsed (post-scrub) `data` value.
+fn push_meta_from_data(ty: Option<u8>, ts: f64, data: Option<&Value<'_>>, sink: &mut Sink) {
+ let dobj = data.and_then(as_object);
+ let source = dobj.and_then(|d| d.get("source")).and_then(as_small_uint);
+ let interaction = dobj.and_then(|d| d.get("type")).and_then(as_small_uint);
+ let href = dobj.and_then(|d| {
+ let read = |v: &Value<'_>| -> Option<String> {
+ let t = as_str(v)?.trim();
+ (!t.is_empty()).then(|| t.to_string())
+ };
+ d.get("href").and_then(read).or_else(|| {
+ d.get("payload")
+ .and_then(as_object)
+ .and_then(|p| p.get("href"))
+ .and_then(read)
+ })
+ });
+ sink.events.push(EventMeta {
+ ts,
+ flags: flags_of(ty, source, interaction),
+ href,
+ });
+
+ // rrweb/console@1 counts by level (mirrors `session-console-log-recorder.ts` safeLevel).
+ if ty == Some(TYPE_PLUGIN) {
+ if let Some(d) = dobj {
+ if d.get("plugin").and_then(as_str) == Some("rrweb/console@1") {
+ let level = d
+ .get("payload")
+ .and_then(as_object)
+ .and_then(|p| p.get("level"))
+ .and_then(as_str);
+ match level {
+ Some("warn") | Some("countReset") => sink.console[1] += 1,
+ Some("error") | Some("assert") => sink.console[2] += 1,
+ _ => sink.console[0] += 1,
+ }
+ }
+ }
+ }
+}
+
+/// Full-parse fallback for a single event whose bytes the scanner cannot prove safe (escaped or
+/// duplicate keys): parse, scrub, and re-serialize the whole event, normalizing like JSON.parse.
+fn process_event_via_tree(ctx: &Ctx<'_>, inner: &[u8], span: Span, sink: &mut Sink) -> SResult<()> {
+ reject_if_too_deep(&inner[span.0..span.1], "snapshot event json")
+ .map_err(|e| Failure::new(FailKind::NonSnapshotMessage, e.to_string()))?;
+ let mut scratch = inner[span.0..span.1].to_vec();
+ let mut event =
+ parse_untrusted(&mut scratch).map_err(|e| non_snapshot(format!("event: {e}")))?;
+ tree_event(ctx, &mut event, sink)
+}
+
+/// Scrub + emit one parsed event (shared by the per-event fallback and the whole-payload tree path).
+/// Always re-serializes from the tree, so JSON.parse normalization (duplicate keys, escapes) holds.
+fn tree_event(ctx: &Ctx<'_>, event: &mut Value<'_>, sink: &mut Sink) -> SResult<()> {
+ let Some(obj) = as_object(&*event) else {
+ return Ok(());
+ };
+ let Some(ts) = valid_timestamp(obj.get("timestamp").and_then(as_f64)) else {
+ return Ok(());
+ };
+ let ty = obj.get("type").and_then(as_small_uint);
+
+ route_event(ctx, event).map_err(|e| Failure::new(FailKind::AnonymizeFailed, e.to_string()))?;
+
+ let line_start = sink.lines.len();
+ event
+ .write(&mut sink.lines)
+ .expect("writing json to a Vec cannot fail");
+ sink.open_line_at(line_start);
+
+ let data = as_object(&*event).and_then(|o| o.get("data"));
+ push_meta_from_data(ty, ts, data, sink);
+ Ok(())
+}
+
+// ---------------------------------------------------------------------------
+// Tree path: the reference implementation and the streaming path's fallback.
+// ---------------------------------------------------------------------------
+
+/// Parse the whole inner event JSON and produce the output via the tree walk. Differential tests
+/// assert the streaming path agrees with this on semantics.
+pub fn anonymize_via_tree(
+ ctx: &Ctx<'_>,
+ distinct_id: &str,
+ inner: &[u8],
+) -> SResult<AnonymizedMessage> {
+ let mut buf = inner.to_vec();
+ anonymize_via_tree_mut(ctx, distinct_id, &mut buf)
+}
+
+/// [`anonymize_via_tree`] parsing the buffer in place (it is consumed).
+fn anonymize_via_tree_mut(
+ ctx: &Ctx<'_>,
+ distinct_id: &str,
+ inner: &mut [u8],
+) -> SResult<AnonymizedMessage> {
+ // JSON.parse on the TS side dies on pathological nesting too (stack overflow -> caught ->
+ // received_non_snapshot_message); the guard keeps the recursive parse/walk off the thread stack.
+ reject_if_too_deep(inner, "snapshot event json")
+ .map_err(|e| Failure::new(FailKind::NonSnapshotMessage, e.to_string()))?;
+ let inner_len = inner.len();
+ let mut root = parse_untrusted(inner).map_err(|e| non_snapshot(format!("event json: {e}")))?;
+
+ let (session_id, window_id, snapshot_source, snapshot_library) = {
+ let Some(obj) = as_object(&root) else {
+ return Err(non_snapshot("event json is not an object"));
+ };
+ match obj.get("event").map(|v| as_str(v)) {
+ Some(Some("$snapshot_items")) => {}
+ Some(Some(_)) => return Err(non_snapshot("not a $snapshot_items event")),
+ Some(None) | None => return Err(non_snapshot("missing event name")),
+ }
+ let Some(props) = obj.get("properties").and_then(as_object) else {
+ return Err(non_snapshot("missing properties object"));
+ };
+ let opt_string = |name: &str| -> SResult<Option<String>> {
+ match props.get(name) {
+ None => Ok(None),
+ Some(v) => match as_str(v) {
+ Some(s) => Ok(Some(s.to_string())),
+ None => Err(non_snapshot(format!("{name} is not a string"))),
+ },
+ }
+ };
+ let session_id = match props.get("$session_id") {
+ Some(v) => match as_str(v) {
+ Some(s) if !s.is_empty() => s.to_string(),
+ Some(_) => return Err(non_snapshot("empty $session_id")),
+ None => return Err(non_snapshot("$session_id is not a string")),
+ },
+ None => return Err(non_snapshot("missing $session_id")),
+ };
+ match props.get("$snapshot_items") {
+ Some(Value::Array(_)) => {}
+ Some(_) => return Err(non_snapshot("$snapshot_items is not an array")),
+ None => return Err(non_snapshot("missing $snapshot_items")),
+ }
+ (
+ session_id,
+ opt_string("$window_id")?,
+ opt_string("$snapshot_source")?,
+ opt_string("$lib")?,
+ )
+ };
+
+ let items = crate::json::as_object_mut(&mut root)
+ .and_then(|o| o.get_mut("properties"))
+ .and_then(crate::json::as_object_mut)
+ .and_then(|p| p.get_mut("$snapshot_items"))
+ .and_then(crate::json::as_array_mut)
+ .expect("validated above");
+
+ let mut sink = Sink::new(inner_len);
+ for event in items.iter_mut() {
+ tree_event(ctx, event, &mut sink)?;
+ }
+
+ finish(
+ distinct_id,
+ ScannedEnvelope {
+ session_id,
+ window_id,
+ snapshot_source,
+ snapshot_library,
+ },
+ sink,
+ Route::Tree,
+ )
+}
diff --git a/rust/replay-anonymizer-node/src/text.rs b/rust/replay-anonymizer-node/src/text.rs
new file mode 100644
index 000000000000..5d37aae2bf96
--- /dev/null
+++ b/rust/replay-anonymizer-node/src/text.rs
@@ -0,0 +1,252 @@
+//! Length-preserving text scrub: numeric tokens -> `#`, allow-listed words kept, everything else -> `*`.
+//! Mirrors `anonymize/text.ts`. `None` means "unchanged" (caller keeps the original).
+
+use crate::allow_lists::AllowLists;
+
+/// Replacement char for redacted (non-allow-listed) word characters.
+pub const REDACT_CHAR: char = '*';
+/// Replacement char for numeric tokens.
+pub const NUMBER_CHAR: char = '#';
+
+/// Guaranteed email-PII pass. 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).
+pub fn redact_emails(input: &str) -> Option<String> {
+ let bytes = input.as_bytes();
+ let mut at = find_at(bytes, 0)?;
+ let mut out = String::new();
+ let mut last = 0usize;
+ let mut changed = false;
+ loop {
+ let mut start = at;
+ while start > last && is_local_char(bytes[start - 1]) {
+ start -= 1;
+ }
+ let mut scan_end = at + 1;
+ while scan_end < bytes.len() && is_domain_char(bytes[scan_end]) {
+ scan_end += 1;
+ }
+ let end = trim_domain_to_tld(bytes, at + 1, scan_end);
+ if start < at {
+ if let Some(end) = end {
+ out.push_str(&input[last..start]);
+ for _ in input[start..end].chars() {
+ out.push(REDACT_CHAR);
+ }
+ last = end;
+ changed = true;
+ match find_at(bytes, end) {
+ Some(n) => at = n,
+ None => break,
+ }
+ continue;
+ }
+ }
+ match find_at(bytes, at + 1) {
+ Some(n) => at = n,
+ None => break,
+ }
+ }
+ if !changed {
+ return None;
+ }
+ out.push_str(&input[last..]);
+ Some(out)
+}
+
+fn find_at(bytes: &[u8], from: usize) -> Option<usize> {
+ memchr::memchr(b'@', &bytes[from..]).map(|i| from + i)
+}
+
+/// Longest `end` in `(domain_start, scan_end]` where the domain ends with `.` + >=2 letters, else None.
+fn trim_domain_to_tld(bytes: &[u8], domain_start: usize, scan_end: usize) -> Option<usize> {
+ let mut i = scan_end;
+ while i > domain_start {
+ let mut letters = 0usize;
+ while i > domain_start && is_ascii_letter(bytes[i - 1]) {
+ i -= 1;
+ letters += 1;
+ }
+ if letters >= 2 && i > domain_start + 1 && bytes[i - 1] == b'.' {
+ return Some(i + letters);
+ }
+ i -= 1; // skip the non-letter (or short-TLD dot) and keep looking left
+ }
+ None
+}
+
+fn is_ascii_letter(c: u8) -> bool {
+ c.is_ascii_alphabetic()
+}
+
+// [A-Za-z0-9._%+-]
+fn is_local_char(c: u8) -> bool {
+ c.is_ascii_alphanumeric() || matches!(c, b'.' | b'_' | b'%' | b'+' | b'-')
+}
+
+// [A-Za-z0-9.-]
+fn is_domain_char(c: u8) -> bool {
+ c.is_ascii_alphanumeric() || matches!(c, b'.' | b'-')
+}
+
+pub fn scrub_text(allow: &AllowLists, input: &str) -> Option<String> {
+ // Nuke whole email addresses first; the tokenizer then runs over what's left.
+ let emails = redact_emails(input);
+ let text: &str = emails.as_deref().unwrap_or(input);
+ match tokenize_scrub(allow, text) {
+ Some(t) => Some(t),
+ None => emails,
+ }
+}
+
+fn tokenize_scrub(allow: &AllowLists, text: &str) -> Option<String> {
+ let bytes = text.as_bytes();
+ let mut out = String::with_capacity(text.len());
+ let mut changed = false;
+ let mut i = 0usize;
+ while i < bytes.len() {
+ // Non-word run: find its end bytewise (ASCII fast path) and copy it in one slice push.
+ let run_start = i;
+ while i < bytes.len() {
+ let b = bytes[i];
+ if b < 0x80 {
+ if is_ascii_word_byte(b) {
+ break;
+ }
+ i += 1;
+ } else {
+ let c = next_char(text, i);
+ if is_word_char(c) {
+ break;
+ }
+ i += c.len_utf8();
+ }
+ }
+ out.push_str(&text[run_start..i]);
+ if i >= bytes.len() {
+ break;
+ }
+ // Word run; numeric-token shape is classified in the same scan.
+ let word_start = i;
+ let mut saw_digit = false;
+ let mut numericish = true; // only digits and . , - + so far
+ while i < bytes.len() {
+ let b = bytes[i];
+ if b < 0x80 {
+ if !is_ascii_word_byte(b) {
+ break;
+ }
+ if b.is_ascii_digit() {
+ saw_digit = true;
+ } else if !matches!(b, b'.' | b',' | b'-' | b'+') {
+ numericish = false;
+ }
+ i += 1;
+ } else {
+ let c = next_char(text, i);
+ if !is_word_char(c) {
+ break;
+ }
+ numericish = false;
+ i += c.len_utf8();
+ }
+ }
+ emit_word(
+ allow,
+ &text[word_start..i],
+ saw_digit && numericish,
+ &mut out,
+ &mut changed,
+ );
+ }
+ if changed {
+ Some(out)
+ } else {
+ None
+ }
+}
+
+fn next_char(text: &str, at: usize) -> char {
+ text[at..].chars().next().expect("at is a char boundary")
+}
+
+// A "word" is a maximal run of word chars: Unicode letters/numbers, `_`, `'`, `’`.
+// The byte test is the ASCII projection of `is_word_char` (`’` is non-ASCII, handled per-char).
+fn is_ascii_word_byte(b: u8) -> bool {
+ b.is_ascii_alphanumeric() || b == b'_' || b == b'\''
+}
+
+fn is_word_char(c: char) -> bool {
+ c.is_alphanumeric() || c == '_' || c == '\'' || c == '\u{2019}'
+}
+
+fn emit_word(allow: &AllowLists, word: &str, numeric: bool, out: &mut String, changed: &mut bool) {
+ if numeric {
+ push_redacted(word, NUMBER_CHAR, out);
+ *changed = true;
+ } else if word_is_allowed(allow, word) {
+ out.push_str(word);
+ } else {
+ push_redacted(word, REDACT_CHAR, out);
+ *changed = true;
+ }
+}
+
+/// Length-preserving redaction: one mark per source code point, pushed in chunks.
+fn push_redacted(word: &str, mark: char, out: &mut String) {
+ const STARS: &str = "********************************";
+ const HASHES: &str = "################################";
+ let chunk = if mark == NUMBER_CHAR { HASHES } else { STARS };
+ let mut n = if word.is_ascii() {
+ word.len()
+ } else {
+ word.chars().count()
+ };
+ while n > 0 {
+ let take = n.min(chunk.len());
+ out.push_str(&chunk[..take]);
+ n -= take;
+ }
+}
+
+fn word_is_allowed(allow: &AllowLists, word: &str) -> bool {
+ if allow.text_contains(word) {
+ return true;
+ }
+ // Possessive/quote forms all end in `s`, `'` or `\u{2019}` (whose UTF-8 ends 0x99) — anything
+ // else can't match below, so the suffix machinery is skipped for the typical redacted word.
+ if !matches!(
+ word.as_bytes().last(),
+ Some(b's') | Some(b'\'') | Some(0x99)
+ ) {
+ return false;
+ }
+ if !word.is_ascii() && word.contains('\u{2019}') {
+ let normalized = word.replace('\u{2019}', "'");
+ if allow.text_contains(&normalized) {
+ return true;
+ }
+ if let Some(base) = strip_possessive(&normalized) {
+ if allow.text_contains(base) {
+ return true;
+ }
+ }
+ }
+ if let Some(base) = strip_possessive(word) {
+ if allow.text_contains(base) {
+ return true;
+ }
+ }
+ false
+}
+
+fn strip_possessive(word: &str) -> Option<&str> {
+ for suffix in ["'s", "\u{2019}s", "'", "\u{2019}"] {
+ if let Some(base) = word.strip_suffix(suffix) {
+ if !base.is_empty() {
+ return Some(base);
+ }
+ }
+ }
+ None
+}
diff --git a/rust/replay-anonymizer-node/src/url.rs b/rust/replay-anonymizer-node/src/url.rs
new file mode 100644
index 000000000000..27ffaffb9520
--- /dev/null
+++ b/rust/replay-anonymizer-node/src/url.rs
@@ -0,0 +1,206 @@
+//! URL scrub. Mirrors `anonymize/url.ts`. `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).
+//! - 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.
+//! - Fragment: kept only if it is an allow-listed alphanumeric token.
+//! - With `scrub_authority` it strips userinfo/port and collapses the host to `example.com`
+//! (keeping a leading allow-listed subdomain label).
+
+use crate::allow_lists::AllowLists;
+
+pub fn scrub_url(allow: &AllowLists, input: &str) -> Option<String> {
+ scrub_url_opts(allow, input, false)
+}
+
+pub fn scrub_url_opts(allow: &AllowLists, input: &str, scrub_authority: bool) -> Option<String> {
+ let tail_idx = input.find(['?', '#']);
+ let (base, tail) = match tail_idx {
+ Some(i) => (&input[..i], &input[i..]),
+ None => (input, ""),
+ };
+ let mut changed = false;
+
+ let (scheme, authority, path) = split_url(base);
+ let mut out = String::with_capacity(input.len());
+ out.push_str(scheme);
+ if !authority.is_empty() {
+ if scrub_authority {
+ let scrubbed = scrub_host(allow, authority);
+ if scrubbed != authority {
+ changed = true;
+ }
+ out.push_str(&scrubbed);
+ } else {
+ out.push_str(authority);
+ }
+ }
+
+ let mut first = true;
+ for raw in path.split('/') {
+ if first {
+ first = false;
+ } else {
+ out.push('/');
+ }
+ if raw.is_empty() {
+ continue;
+ }
+ if is_numeric(raw) {
+ mask_number_into(raw, &mut out);
+ changed = true;
+ } else if is_safe_segment(raw) || allow.url_contains(raw) {
+ out.push_str(raw);
+ } else {
+ out.push_str("[redacted]");
+ changed = true;
+ }
+ }
+
+ let tail_out = scrub_tail(allow, tail);
+ if tail_out != tail {
+ changed = true;
+ }
+ out.push_str(&tail_out);
+
+ if changed {
+ Some(out)
+ } else {
+ None
+ }
+}
+
+fn scrub_tail(allow: &AllowLists, tail: &str) -> String {
+ if tail.is_empty() {
+ return String::new();
+ }
+ let starts_query = tail.as_bytes()[0] == b'?';
+ let (query, frag) = if starts_query {
+ match tail[1..].find('#') {
+ Some(h) => (&tail[1..1 + h], &tail[1 + h + 1..]),
+ None => (&tail[1..], ""),
+ }
+ } else {
+ ("", &tail[1..]) // tail starts with '#'
+ };
+
+ let mut out = String::new();
+ if starts_query {
+ let mut kept: Vec<String> = Vec::new();
+ for pair in query.split('&') {
+ if pair.is_empty() {
+ continue;
+ }
+ match pair.find('=') {
+ None => {
+ if is_allowed(allow, pair) {
+ kept.push(pair.to_string());
+ }
+ }
+ Some(eq) => {
+ let key = &pair[..eq];
+ let value = &pair[eq + 1..];
+ // A param survives only if its key or (non-empty) value is an allow-listed token.
+ let key_ok = is_allowed(allow, key);
+ let value_ok = !value.is_empty() && is_allowed(allow, value);
+ if !key_ok && !value_ok {
+ continue;
+ }
+ let kr = render_token(allow, key).unwrap_or_else(|| "[key]".to_string());
+ let vr = if value.is_empty() {
+ String::new()
+ } else {
+ render_token(allow, value).unwrap_or_else(|| "[value]".to_string())
+ };
+ kept.push(format!("{kr}={vr}"));
+ }
+ }
+ }
+ if !kept.is_empty() {
+ out.push('?');
+ out.push_str(&kept.join("&"));
+ }
+ }
+ if !frag.is_empty() && is_allowed(allow, frag) {
+ out.push('#');
+ out.push_str(frag);
+ }
+ out
+}
+
+// Strip userinfo + 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`.
+fn scrub_host(allow: &AllowLists, authority: &str) -> String {
+ let mut host = match authority.rfind('@') {
+ Some(at) => &authority[at + 1..],
+ None => authority,
+ };
+ if let Some(ci) = host.rfind(':') {
+ let after = &host[ci + 1..];
+ if !after.is_empty() && after.bytes().all(|b| b.is_ascii_digit()) {
+ host = &host[..ci];
+ }
+ }
+ let labels: Vec<&str> = host.split('.').collect();
+ let first = labels.first().copied().unwrap_or("");
+ if labels.len() > 2 && !first.is_empty() && allow.url_contains(first) {
+ format!("{first}.example.com")
+ } else {
+ "example.com".to_string()
+ }
+}
+
+// Split into scheme prefix (incl. `://` or `//`), authority (`[userinfo@]host[:port]`), and path.
+fn split_url(s: &str) -> (&str, &str, &str) {
+ let (scheme, rest) = if let Some(scheme_end) = s.find("://") {
+ (&s[..scheme_end + 3], &s[scheme_end + 3..])
+ } else if let Some(rest) = s.strip_prefix("//") {
+ (&s[..2], rest)
+ } else {
+ return ("", "", s); // relative URL: all path
+ };
+ match rest.find('/') {
+ None => (scheme, rest, ""),
+ Some(path_off) => (scheme, &rest[..path_off], &rest[path_off..]),
+ }
+}
+
+fn is_safe_segment(seg: &str) -> bool {
+ matches!(seg, "" | "." | "..")
+}
+
+// `$`, not `#` (the fragment separator).
+fn mask_number_into(n: &str, out: &mut String) {
+ for _ in 0..n.len() {
+ out.push('$');
+ }
+}
+
+fn is_numeric(t: &str) -> bool {
+ !t.is_empty() && t.bytes().all(|b| b.is_ascii_digit())
+}
+
+// 100% alphanumeric (empty allowed).
+fn is_simple(t: &str) -> bool {
+ t.bytes().all(|b| b.is_ascii_alphanumeric())
+}
+
+// An allow-listed, alphanumeric, non-number token — the only kind that keeps a query param/fragment
+// alive.
+fn is_allowed(allow: &AllowLists, t: &str) -> bool {
+ !t.is_empty() && is_simple(t) && !is_numeric(t) && allow.url_contains(t)
+}
+
+// Rendered form of a surviving token: a number -> `$$`, an allow-listed token -> itself, else None.
+fn render_token(allow: &AllowLists, t: &str) -> Option<String> {
+ if is_numeric(t) {
+ let mut s = String::with_capacity(t.len());
+ mask_number_into(t, &mut s);
+ Some(s)
+ } else if is_allowed(allow, t) {
+ Some(t.to_string())
+ } else {
+ None
+ }
+}
diff --git a/rust/replay-anonymizer-node/src/value.rs b/rust/replay-anonymizer-node/src/value.rs
new file mode 100644
index 000000000000..5a7066584ca0
--- /dev/null
+++ b/rust/replay-anonymizer-node/src/value.rs
@@ -0,0 +1,143 @@
+//! Generic / network / console value scrubs over parsed JSON (Custom and Plugin payloads).
+//! Mirrors `anonymize/value.ts`.
+
+use simd_json::borrowed::{Object, Value};
+
+use crate::allow_lists::AllowLists;
+use crate::json::{as_array_mut, as_object_mut, is_object, key, string_value};
+use crate::text::scrub_text;
+use crate::url::scrub_url;
+
+fn looks_like_url(s: &str) -> bool {
+ s.starts_with("http://") || s.starts_with("https://")
+}
+
+fn scrub_string_leaf(allow: &AllowLists, s: &str) -> Option<String> {
+ if looks_like_url(s) {
+ scrub_url(allow, s)
+ } else {
+ scrub_text(allow, s)
+ }
+}
+
+/// Scrub `slot`: a string leaf (with writeback), otherwise recurse into it.
+fn scrub_child(allow: &AllowLists, slot: &mut Value<'_>) -> bool {
+ if let Value::String(s) = slot {
+ match scrub_string_leaf(allow, s) {
+ Some(v) => {
+ *slot = string_value(v);
+ true
+ }
+ None => false,
+ }
+ } else {
+ scrub_value_in_place(allow, slot)
+ }
+}
+
+/// Recursively scrub string leaves inside an array/object, mutating in place.
+pub fn scrub_value_in_place(allow: &AllowLists, value: &mut Value<'_>) -> bool {
+ let mut changed = false;
+ match value {
+ Value::Array(arr) => {
+ for item in arr.iter_mut() {
+ changed |= scrub_child(allow, item);
+ }
+ }
+ Value::Object(obj) => {
+ for (_, val) in obj.iter_mut() {
+ changed |= scrub_child(allow, val);
+ }
+ }
+ _ => {}
+ }
+ changed
+}
+
+/// Generic scrub of `owner[key]`, handling both a string leaf and a container.
+pub fn scrub_generic_field(allow: &AllowLists, owner: &mut Object<'_>, field: &str) -> bool {
+ match owner.get_mut(field) {
+ Some(slot) => scrub_child(allow, slot),
+ None => false,
+ }
+}
+
+fn scrub_field_with(
+ allow: &AllowLists,
+ obj: &mut Object<'_>,
+ field: &'static str,
+ scrub: fn(&AllowLists, &str) -> Option<String>,
+) -> bool {
+ let Some(cur) = obj.get(field).and_then(crate::json::as_str) else {
+ return false;
+ };
+ match scrub(allow, cur) {
+ Some(v) => {
+ obj.insert(key(field), string_value(v));
+ true
+ }
+ None => false,
+ }
+}
+
+/// rrweb/network@1 payload: `{ requests: CapturedNetworkRequest[] }`. Per request: `name` is a
+/// Resource Timing URL (URL-scrub); request/response bodies and every header value are free text.
+pub fn scrub_network_plugin(allow: &AllowLists, owner: &mut Object<'_>, field: &str) -> bool {
+ if !owner.get(field).map(is_object).unwrap_or(false) {
+ return scrub_generic_field(allow, owner, field);
+ }
+ let Some(payload) = owner.get_mut(field).and_then(as_object_mut) else {
+ return false;
+ };
+ let Some(reqs) = payload.get_mut("requests").and_then(as_array_mut) else {
+ return false;
+ };
+ let mut changed = false;
+ for req in reqs.iter_mut() {
+ let Some(robj) = as_object_mut(req) else {
+ continue;
+ };
+ changed |= scrub_field_with(allow, robj, "name", scrub_url);
+ for f in ["requestBody", "responseBody"] {
+ changed |= scrub_field_with(allow, robj, f, scrub_text);
+ }
+ for f in ["requestHeaders", "responseHeaders"] {
+ if let Some(hdrs) = robj.get_mut(f).and_then(as_object_mut) {
+ for (_, v) in hdrs.iter_mut() {
+ if let Value::String(s) = v {
+ if let Some(nv) = scrub_text(allow, s) {
+ *v = string_value(nv);
+ changed = true;
+ }
+ }
+ }
+ }
+ }
+ }
+ changed
+}
+
+/// rrweb/console@1 payload: `{ level, payload: string[], trace: string[] }`.
+pub fn scrub_console_plugin(allow: &AllowLists, owner: &mut Object<'_>, field: &str) -> bool {
+ if !owner.get(field).map(is_object).unwrap_or(false) {
+ return scrub_generic_field(allow, owner, field);
+ }
+ let Some(payload) = owner.get_mut(field).and_then(as_object_mut) else {
+ return false;
+ };
+ let mut changed = false;
+ for f in ["payload", "trace"] {
+ if let Some(arr) = payload.get_mut(f).and_then(as_array_mut) {
+ for v in arr.iter_mut() {
+ // Console frames can hold URLs (stack traces); scrub URL-aware, not as plain text.
+ if let Value::String(s) = v {
+ if let Some(nv) = scrub_string_leaf(allow, s) {
+ *v = string_value(nv);
+ changed = true;
+ }
+ }
+ }
+ }
+ }
+ changed
+}
diff --git a/rust/replay-anonymizer-node/tests/fixtures/events.json b/rust/replay-anonymizer-node/tests/fixtures/events.json
new file mode 100644
index 000000000000..8a7885a2fc4b
--- /dev/null
+++ b/rust/replay-anonymizer-node/tests/fixtures/events.json
@@ -0,0 +1,483 @@
+[
+ {
+ "name": "full snapshot scrubs a text node, keeps allow-listed word",
+ "allow": { "text": ["text"], "url": [] },
+ "event": {
+ "type": 2,
+ "data": {
+ "node": {
+ "type": 0,
+ "childNodes": [
+ {
+ "type": 2,
+ "tagName": "div",
+ "attributes": { "title": "hidden text" },
+ "childNodes": [{ "type": 3, "textContent": "Secret text" }]
+ }
+ ]
+ },
+ "initialOffset": { "top": 0, "left": 0 }
+ }
+ },
+ "expected": {
+ "type": 2,
+ "data": {
+ "node": {
+ "type": 0,
+ "childNodes": [
+ {
+ "type": 2,
+ "tagName": "div",
+ "attributes": { "title": "****** text" },
+ "childNodes": [{ "type": 3, "textContent": "****** text" }]
+ }
+ ]
+ },
+ "initialOffset": { "top": 0, "left": 0 }
+ }
+ }
+ },
+ {
+ "name": "script text is never scrubbed",
+ "allow": { "text": [], "url": [] },
+ "event": {
+ "type": 2,
+ "data": {
+ "node": {
+ "type": 0,
+ "childNodes": [
+ {
+ "type": 2,
+ "tagName": "script",
+ "attributes": {},
+ "childNodes": [{ "type": 3, "textContent": "const secret = 42" }]
+ }
+ ]
+ },
+ "initialOffset": { "top": 0, "left": 0 }
+ }
+ },
+ "expected": {
+ "type": 2,
+ "data": {
+ "node": {
+ "type": 0,
+ "childNodes": [
+ {
+ "type": 2,
+ "tagName": "script",
+ "attributes": {},
+ "childNodes": [{ "type": 3, "textContent": "const secret = 42" }]
+ }
+ ]
+ },
+ "initialOffset": { "top": 0, "left": 0 }
+ }
+ }
+ },
+ {
+ "name": "input event text is scrubbed",
+ "allow": { "text": ["hello"], "url": [] },
+ "event": { "type": 3, "data": { "source": 5, "id": 1, "text": "hello secret", "isChecked": false } },
+ "expected": { "type": 3, "data": { "source": 5, "id": 1, "text": "hello ******", "isChecked": false } }
+ },
+ {
+ "name": "meta href strips authority and redacts the path",
+ "allow": { "text": [], "url": [] },
+ "event": { "type": 4, "data": { "href": "https://[email protected]/u/42", "width": 100, "height": 200 } },
+ "expected": { "type": 4, "data": { "href": "https://example.com/[redacted]/$$", "width": 100, "height": 200 } }
+ },
+ {
+ "name": "custom event payload string is scrubbed and email redacted",
+ "allow": { "text": ["call", "me", "at"], "url": [] },
+ "event": { "type": 5, "data": { "tag": "note", "payload": { "msg": "call me at [email protected]" } } },
+ "expected": { "type": 5, "data": { "tag": "note", "payload": { "msg": "call me at ************" } } }
+ },
+ {
+ "name": "network plugin scrubs request name url and body text",
+ "allow": { "text": [], "url": ["api"] },
+ "event": {
+ "type": 6,
+ "data": {
+ "plugin": "rrweb/network@1",
+ "payload": { "requests": [{ "name": "https://example.com/api/99", "requestBody": "token=secret" }] }
+ }
+ },
+ "expected": {
+ "type": 6,
+ "data": {
+ "plugin": "rrweb/network@1",
+ "payload": { "requests": [{ "name": "https://example.com/api/$$", "requestBody": "*****=******" }] }
+ }
+ }
+ },
+ {
+ "name": "console plugin scrubs url-bearing frames",
+ "allow": { "text": [], "url": ["x"] },
+ "event": {
+ "type": 6,
+ "data": { "plugin": "rrweb/console@1", "payload": { "level": "log", "payload": ["https://example.com/x/7"], "trace": [] } }
+ },
+ "expected": {
+ "type": 6,
+ "data": { "plugin": "rrweb/console@1", "payload": { "level": "log", "payload": ["https://example.com/x/$"], "trace": [] } }
+ }
+ },
+ {
+ "name": "mutation scrubs texts, attributes and added nodes",
+ "allow": { "text": ["keep"], "url": ["ok"] },
+ "event": {
+ "type": 3,
+ "data": {
+ "source": 0,
+ "texts": [{ "id": 5, "value": "keep secret" }],
+ "attributes": [{ "id": 6, "attributes": { "title": "hide me", "action": "https://example.com/ok/3" } }],
+ "adds": [{ "parentId": 1, "nextId": null, "node": { "type": 3, "textContent": "another secret" } }],
+ "removes": []
+ }
+ },
+ "expected": {
+ "type": 3,
+ "data": {
+ "source": 0,
+ "texts": [{ "id": 5, "value": "keep ******" }],
+ "attributes": [{ "id": 6, "attributes": { "title": "**** **", "action": "https://example.com/ok/$" } }],
+ "adds": [{ "parentId": 1, "nextId": null, "node": { "type": 3, "textContent": "******* ******" } }],
+ "removes": []
+ }
+ }
+ },
+ {
+ "name": "media element remote src becomes placeholder with scrubbed original stashed",
+ "allow": { "text": [], "url": [] },
+ "event": {
+ "type": 2,
+ "data": {
+ "node": {
+ "type": 0,
+ "childNodes": [
+ { "type": 2, "tagName": "img", "attributes": { "src": "https://cdn.example.com/pic.jpg?u=42", "alt": "profile photo" }, "childNodes": [] }
+ ]
+ },
+ "initialOffset": { "top": 0, "left": 0 }
+ }
+ },
+ "expected": {
+ "type": 2,
+ "data": {
+ "node": {
+ "type": 0,
+ "childNodes": [
+ {
+ "type": 2,
+ "tagName": "img",
+ "attributes": {
+ "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>",
+ "data-anon-original-src": "https://example.com/[redacted]",
+ "alt": "******* *****"
+ },
+ "childNodes": []
+ }
+ ]
+ },
+ "initialOffset": { "top": 0, "left": 0 }
+ }
+ }
+ },
+ {
+ "name": "canvas fillText args are text-scrubbed",
+ "allow": { "text": ["hello"], "url": [] },
+ "event": {
+ "type": 3,
+ "data": { "source": 9, "id": 1, "type": 0, "commands": [{ "property": "fillText", "args": ["Hello secret", 10, 20] }] }
+ },
+ "expected": {
+ "type": 3,
+ "data": { "source": 9, "id": 1, "type": 0, "commands": [{ "property": "fillText", "args": ["Hello ******", 10, 20] }] }
+ }
+ },
+ {
+ "name": "data-* attributes: free text scrubbed, single token left to email pass",
+ "allow": { "text": ["call"], "url": [] },
+ "event": {
+ "type": 2,
+ "data": {
+ "node": {
+ "type": 0,
+ "childNodes": [
+ { "type": 2, "tagName": "div", "attributes": { "data-note": "call bob", "data-id": "x1y2" }, "childNodes": [] }
+ ]
+ },
+ "initialOffset": { "top": 0, "left": 0 }
+ }
+ },
+ "expected": {
+ "type": 2,
+ "data": {
+ "node": {
+ "type": 0,
+ "childNodes": [
+ { "type": 2, "tagName": "div", "attributes": { "data-note": "call ***", "data-id": "x1y2" }, "childNodes": [] }
+ ]
+ },
+ "initialOffset": { "top": 0, "left": 0 }
+ }
+ }
+ },
+ {
+ "name": "comment and cdata text nodes are scrubbed",
+ "allow": { "text": ["comment", "cdata"], "url": [] },
+ "event": {
+ "type": 2,
+ "data": {
+ "node": {
+ "type": 0,
+ "childNodes": [
+ {
+ "type": 2,
+ "tagName": "div",
+ "attributes": {},
+ "childNodes": [
+ { "type": 5, "textContent": "secret comment" },
+ { "type": 4, "textContent": "secret cdata" }
+ ]
+ }
+ ]
+ },
+ "initialOffset": { "top": 0, "left": 0 }
+ }
+ },
+ "expected": {
+ "type": 2,
+ "data": {
+ "node": {
+ "type": 0,
+ "childNodes": [
+ {
+ "type": 2,
+ "tagName": "div",
+ "attributes": {},
+ "childNodes": [
+ { "type": 5, "textContent": "****** comment" },
+ { "type": 4, "textContent": "****** cdata" }
+ ]
+ }
+ ]
+ },
+ "initialOffset": { "top": 0, "left": 0 }
+ }
+ }
+ },
+ {
+ "name": "user-text attributes and non-media url attributes are scrubbed",
+ "allow": { "text": ["text", "here", "close"], "url": [] },
+ "event": {
+ "type": 2,
+ "data": {
+ "node": {
+ "type": 0,
+ "childNodes": [
+ {
+ "type": 2,
+ "tagName": "div",
+ "attributes": {
+ "value": "secret text",
+ "placeholder": "type here",
+ "aria-label": "close dialog",
+ "cite": "https://example.com/x/1"
+ },
+ "childNodes": []
+ }
+ ]
+ },
+ "initialOffset": { "top": 0, "left": 0 }
+ }
+ },
+ "expected": {
+ "type": 2,
+ "data": {
+ "node": {
+ "type": 0,
+ "childNodes": [
+ {
+ "type": 2,
+ "tagName": "div",
+ "attributes": {
+ "value": "****** text",
+ "placeholder": "**** here",
+ "aria-label": "close ******",
+ "cite": "https://example.com/[redacted]/$"
+ },
+ "childNodes": []
+ }
+ ]
+ },
+ "initialOffset": { "top": 0, "left": 0 }
+ }
+ }
+ },
+ {
+ "name": "non-string attribute values are left untouched",
+ "allow": { "text": ["there"], "url": [] },
+ "event": {
+ "type": 2,
+ "data": {
+ "node": {
+ "type": 0,
+ "childNodes": [
+ { "type": 2, "tagName": "div", "attributes": { "tabindex": 5, "title": "hi there" }, "childNodes": [] }
+ ]
+ },
+ "initialOffset": { "top": 0, "left": 0 }
+ }
+ },
+ "expected": {
+ "type": 2,
+ "data": {
+ "node": {
+ "type": 0,
+ "childNodes": [
+ { "type": 2, "tagName": "div", "attributes": { "tabindex": 5, "title": "** there" }, "childNodes": [] }
+ ]
+ },
+ "initialOffset": { "top": 0, "left": 0 }
+ }
+ }
+ },
+ {
+ "name": "data-anon-original-* attrs are not re-scrubbed",
+ "allow": { "text": ["hello"], "url": [] },
+ "event": {
+ "type": 2,
+ "data": {
+ "node": {
+ "type": 0,
+ "childNodes": [
+ {
+ "type": 2,
+ "tagName": "div",
+ "attributes": { "data-anon-original-src": "https://example.com/kept", "data-note": "hello world" },
+ "childNodes": []
+ }
+ ]
+ },
+ "initialOffset": { "top": 0, "left": 0 }
+ }
+ },
+ "expected": {
+ "type": 2,
+ "data": {
+ "node": {
+ "type": 0,
+ "childNodes": [
+ {
+ "type": 2,
+ "tagName": "div",
+ "attributes": { "data-anon-original-src": "https://example.com/kept", "data-note": "hello *****" },
+ "childNodes": []
+ }
+ ]
+ },
+ "initialOffset": { "top": 0, "left": 0 }
+ }
+ }
+ },
+ {
+ "name": "canvas strokeText in flattened single-command form is scrubbed",
+ "allow": { "text": ["hi"], "url": [] },
+ "event": { "type": 3, "data": { "source": 9, "id": 1, "type": 0, "property": "strokeText", "args": ["Hi secret", 1, 2] } },
+ "expected": { "type": 3, "data": { "source": 9, "id": 1, "type": 0, "property": "strokeText", "args": ["Hi ******", 1, 2] } }
+ },
+ {
+ "name": "canvas multiple commands (fillText + strokeText) each scrubbed",
+ "allow": { "text": ["a", "b"], "url": [] },
+ "event": {
+ "type": 3,
+ "data": {
+ "source": 9,
+ "id": 1,
+ "type": 0,
+ "commands": [
+ { "property": "fillText", "args": ["A secret"] },
+ { "property": "strokeText", "args": ["B secret"] }
+ ]
+ }
+ },
+ "expected": {
+ "type": 3,
+ "data": {
+ "source": 9,
+ "id": 1,
+ "type": 0,
+ "commands": [
+ { "property": "fillText", "args": ["A ******"] },
+ { "property": "strokeText", "args": ["B ******"] }
+ ]
+ }
+ }
+ },
+ {
+ "name": "console plugin scrubs text payload frames and url trace frames",
+ "allow": { "text": ["oops"], "url": ["a"] },
+ "event": {
+ "type": 6,
+ "data": {
+ "plugin": "rrweb/console@1",
+ "payload": { "level": "error", "payload": ["oops secret"], "trace": ["https://example.com/a/1"] }
+ }
+ },
+ "expected": {
+ "type": 6,
+ "data": {
+ "plugin": "rrweb/console@1",
+ "payload": { "level": "error", "payload": ["oops ******"], "trace": ["https://example.com/a/$"] }
+ }
+ }
+ },
+ {
+ "name": "network plugin scrubs request and response header values",
+ "allow": { "text": ["here"], "url": ["api"] },
+ "event": {
+ "type": 6,
+ "data": {
+ "plugin": "rrweb/network@1",
+ "payload": {
+ "requests": [
+ {
+ "name": "https://example.com/api/1",
+ "requestHeaders": { "Authorization": "Bearer secret", "X-Id": "42" },
+ "responseHeaders": { "Server": "nginx here" }
+ }
+ ]
+ }
+ }
+ },
+ "expected": {
+ "type": 6,
+ "data": {
+ "plugin": "rrweb/network@1",
+ "payload": {
+ "requests": [
+ {
+ "name": "https://example.com/api/$",
+ "requestHeaders": { "Authorization": "****** ******", "X-Id": "##" },
+ "responseHeaders": { "Server": "***** here" }
+ }
+ ]
+ }
+ }
+ }
+ },
+ {
+ "name": "custom payload scrubs string leaves in deeply nested containers",
+ "allow": { "text": ["hello"], "url": [] },
+ "event": { "type": 5, "data": { "tag": "note", "payload": { "a": { "b": ["hello secret", 42] } } } },
+ "expected": { "type": 5, "data": { "tag": "note", "payload": { "a": { "b": ["hello ******", 42] } } } }
+ },
+ {
+ "name": "unknown event type passes through unchanged",
+ "allow": { "text": [], "url": [] },
+ "event": { "type": 0, "data": { "href": "https://example.com/secret" } },
+ "expected": { "type": 0, "data": { "href": "https://example.com/secret" } }
+ }
+]
diff --git a/rust/replay-anonymizer-node/tests/fixtures/messages.json b/rust/replay-anonymizer-node/tests/fixtures/messages.json
new file mode 100644
index 000000000000..fb0de84cce75
--- /dev/null
+++ b/rust/replay-anonymizer-node/tests/fixtures/messages.json
@@ -0,0 +1,88 @@
+[
+ {
+ "name": "multiple windows with mixed event types all scrubbed under one allow list",
+ "allow": { "text": ["hello"], "url": ["api"] },
+ "message": {
+ "window-a": [
+ { "type": 4, "data": { "href": "https://[email protected]/u/42", "width": 100, "height": 200 } },
+ { "type": 3, "data": { "source": 5, "id": 1, "text": "hello secret", "isChecked": false } },
+ { "type": 1, "data": {} }
+ ],
+ "window-b": [
+ {
+ "type": 6,
+ "data": {
+ "plugin": "rrweb/network@1",
+ "payload": { "requests": [{ "name": "https://example.com/api/99", "requestBody": "token=secret" }] }
+ }
+ }
+ ]
+ },
+ "expected": {
+ "window-a": [
+ { "type": 4, "data": { "href": "https://example.com/[redacted]/$$", "width": 100, "height": 200 } },
+ { "type": 3, "data": { "source": 5, "id": 1, "text": "hello ******", "isChecked": false } },
+ { "type": 1, "data": {} }
+ ],
+ "window-b": [
+ {
+ "type": 6,
+ "data": {
+ "plugin": "rrweb/network@1",
+ "payload": { "requests": [{ "name": "https://example.com/api/$$", "requestBody": "*****=******" }] }
+ }
+ }
+ ]
+ }
+ },
+ {
+ "name": "a message with nothing to scrub is returned unchanged",
+ "allow": { "text": [], "url": [] },
+ "message": {
+ "w1": [{ "type": 1, "data": {} }, { "type": 0, "data": { "href": "https://example.com/x" } }],
+ "w2": [{ "type": 9, "data": { "foo": "bar" } }]
+ },
+ "expected": {
+ "w1": [{ "type": 1, "data": {} }, { "type": 0, "data": { "href": "https://example.com/x" } }],
+ "w2": [{ "type": 9, "data": { "foo": "bar" } }]
+ }
+ },
+ {
+ "name": "malformed and edge events are skipped while valid ones are still scrubbed, order preserved",
+ "allow": { "text": ["hi"], "url": [] },
+ "message": {
+ "w": [
+ { "type": 3, "data": { "source": 5, "id": 1, "text": "hi secret", "isChecked": false } },
+ { "type": 3, "data": null },
+ { "data": { "source": 5, "text": "no type here" } },
+ { "type": 3, "data": { "source": 999, "text": "unknown source" } },
+ { "type": 3, "data": { "source": 5, "id": 2, "text": "hi again", "isChecked": true } }
+ ]
+ },
+ "expected": {
+ "w": [
+ { "type": 3, "data": { "source": 5, "id": 1, "text": "hi ******", "isChecked": false } },
+ { "type": 3, "data": null },
+ { "data": { "source": 5, "text": "no type here" } },
+ { "type": 3, "data": { "source": 999, "text": "unknown source" } },
+ { "type": 3, "data": { "source": 5, "id": 2, "text": "hi *****", "isChecked": true } }
+ ]
+ }
+ },
+ {
+ "name": "allow list and email redaction apply consistently across events in a window",
+ "allow": { "text": ["call", "me", "at"], "url": [] },
+ "message": {
+ "w1": [
+ { "type": 5, "data": { "tag": "note", "payload": { "msg": "call me at [email protected]" } } },
+ { "type": 3, "data": { "source": 5, "id": 1, "text": "call me maybe", "isChecked": false } }
+ ]
+ },
+ "expected": {
+ "w1": [
+ { "type": 5, "data": { "tag": "note", "payload": { "msg": "call me at ************" } } },
+ { "type": 3, "data": { "source": 5, "id": 1, "text": "call me *****", "isChecked": false } }
+ ]
+ }
+ }
+]
diff --git a/rust/replay-anonymizer-node/tests/fixtures/text.json b/rust/replay-anonymizer-node/tests/fixtures/text.json
new file mode 100644
index 000000000000..d1ab02170a9f
--- /dev/null
+++ b/rust/replay-anonymizer-node/tests/fixtures/text.json
@@ -0,0 +1,74 @@
+[
+ {
+ "name": "keeps allow-listed words, redacts the rest length-preserving",
+ "allow": { "text": ["hello"], "url": [] },
+ "input": "hello world",
+ "expected": "hello *****"
+ },
+ {
+ "name": "numeric tokens become #",
+ "allow": { "text": [], "url": [] },
+ "input": "order 12345",
+ "expected": "***** #####"
+ },
+ {
+ "name": "redacts a whole email before tokenizing",
+ "allow": { "text": ["contact", "me", "at", "now"], "url": [] },
+ "input": "contact me at [email protected] now",
+ "expected": "contact me at ******************** now"
+ },
+ {
+ "name": "keeps a possessive whose base is allow-listed",
+ "allow": { "text": ["posthog", "dashboard"], "url": [] },
+ "input": "PostHog's dashboard",
+ "expected": "PostHog's dashboard"
+ },
+ {
+ "name": "typographic apostrophe possessive resolves to allow-listed base",
+ "allow": { "text": ["it", "fine"], "url": [] },
+ "input": "it’s fine",
+ "expected": "it’s fine"
+ },
+ {
+ "name": "unicode word kept when allow-listed",
+ "allow": { "text": ["café"], "url": [] },
+ "input": "café",
+ "expected": "café"
+ },
+ {
+ "name": "unicode word redacted per code point",
+ "allow": { "text": [], "url": [] },
+ "input": "café",
+ "expected": "****"
+ },
+ {
+ "name": "decimal number splits on the dot (tokenizer boundary), each digit run masked",
+ "allow": { "text": [], "url": [] },
+ "input": "3.14",
+ "expected": "#.##"
+ },
+ {
+ "name": "alphanumeric token is not numeric",
+ "allow": { "text": ["build"], "url": [] },
+ "input": "v2 build",
+ "expected": "** build"
+ },
+ {
+ "name": "at-sign without a valid TLD is not treated as an email",
+ "allow": { "text": ["foo", "bar"], "url": [] },
+ "input": "foo@bar",
+ "expected": "foo@bar"
+ },
+ {
+ "name": "multiple emails in one string are each redacted",
+ "allow": { "text": ["email", "or", "please"], "url": [] },
+ "input": "email [email protected] or [email protected] please",
+ "expected": "email ******* or ******* please"
+ },
+ {
+ "name": "email with a multi-label domain redacts through the whole domain",
+ "allow": { "text": ["mail", "end"], "url": [] },
+ "input": "mail [email protected] end",
+ "expected": "mail *********** end"
+ }
+]
diff --git a/rust/replay-anonymizer-node/tests/fixtures/url.json b/rust/replay-anonymizer-node/tests/fixtures/url.json
new file mode 100644
index 000000000000..7c89795a27ee
--- /dev/null
+++ b/rust/replay-anonymizer-node/tests/fixtures/url.json
@@ -0,0 +1,79 @@
+[
+ {
+ "name": "keeps allow-listed path segments, masks numbers",
+ "allow": { "text": [], "url": ["users", "profile"] },
+ "input": "https://example.com/users/42/profile",
+ "scrubAuthority": false,
+ "expected": "https://example.com/users/$$/profile"
+ },
+ {
+ "name": "redacts non-allow-listed path segments",
+ "allow": { "text": [], "url": [] },
+ "input": "/foo/bar?x=1",
+ "scrubAuthority": false,
+ "expected": "/[redacted]/[redacted]"
+ },
+ {
+ "name": "query param survives on allow-listed key, number value masked",
+ "allow": { "text": [], "url": ["page"] },
+ "input": "https://example.com/?page=2&secret=abc",
+ "scrubAuthority": false,
+ "expected": "https://example.com/?page=$"
+ },
+ {
+ "name": "allow-listed fragment kept",
+ "allow": { "text": [], "url": ["section"] },
+ "input": "https://example.com/#section",
+ "scrubAuthority": false,
+ "expected": "https://example.com/#section"
+ },
+ {
+ "name": "scrubAuthority strips userinfo/port and keeps allow-listed subdomain",
+ "allow": { "text": [], "url": ["us", "path"] },
+ "input": "https://user:[email protected]:8080/path",
+ "scrubAuthority": true,
+ "expected": "https://us.example.com/path"
+ },
+ {
+ "name": "scrubAuthority collapses a two-label host to example.com",
+ "allow": { "text": [], "url": [] },
+ "input": "https://example.com/u/42",
+ "scrubAuthority": true,
+ "expected": "https://example.com/[redacted]/$$"
+ },
+ {
+ "name": "query param with an allow-listed key and empty value survives",
+ "allow": { "text": [], "url": ["ok"] },
+ "input": "https://example.com/?ok=&x=1",
+ "scrubAuthority": false,
+ "expected": "https://example.com/?ok="
+ },
+ {
+ "name": "bare (valueless) query flag survives only when allow-listed",
+ "allow": { "text": [], "url": ["ok"] },
+ "input": "https://example.com/?ok&drop",
+ "scrubAuthority": false,
+ "expected": "https://example.com/?ok"
+ },
+ {
+ "name": "numeric fragment is dropped",
+ "allow": { "text": [], "url": [] },
+ "input": "https://example.com/#42",
+ "scrubAuthority": false,
+ "expected": "https://example.com/"
+ },
+ {
+ "name": "relative-path safe segments (. and ..) are preserved",
+ "allow": { "text": [], "url": [] },
+ "input": "/a/../b",
+ "scrubAuthority": false,
+ "expected": "/[redacted]/../[redacted]"
+ },
+ {
+ "name": "multiple surviving query params keep their order",
+ "allow": { "text": [], "url": ["a", "b", "x", "y"] },
+ "input": "https://example.com/?a=x&b=y",
+ "scrubAuthority": false,
+ "expected": "https://example.com/?a=x&b=y"
+ }
+]
diff --git a/rust/replay-anonymizer-node/tests/parity.rs b/rust/replay-anonymizer-node/tests/parity.rs
new file mode 100644
index 000000000000..5785e4498b96
--- /dev/null
+++ b/rust/replay-anonymizer-node/tests/parity.rs
@@ -0,0 +1,140 @@
+//! Reads the shared JSON fixtures (also consumed by the TS Jest suite) and asserts the Rust scrubbers
+//! match. Keeping one fixture set means a change must keep both implementations in agreement.
+
+use std::path::Path;
+use std::time::Instant;
+
+use replay_anonymizer_node::allow_lists::AllowLists;
+use replay_anonymizer_node::{
+ anonymize_event_str, anonymize_message, text::scrub_text, url::scrub_url_opts,
+};
+use serde_json::Value;
+
+fn fixtures(name: &str) -> Vec<Value> {
+ let path = Path::new(env!("CARGO_MANIFEST_DIR"))
+ .join("tests/fixtures")
+ .join(name);
+ let data = std::fs::read_to_string(&path).unwrap_or_else(|e| panic!("read {path:?}: {e}"));
+ serde_json::from_str(&data).unwrap_or_else(|e| panic!("parse {path:?}: {e}"))
+}
+
+fn allow_of(case: &Value) -> AllowLists {
+ let allow = &case["allow"];
+ let strings = |key: &str| -> Vec<String> {
+ allow[key]
+ .as_array()
+ .map(|a| {
+ a.iter()
+ .filter_map(|v| v.as_str().map(str::to_string))
+ .collect()
+ })
+ .unwrap_or_default()
+ };
+ AllowLists::new(strings("text"), strings("url"))
+}
+
+#[test]
+fn text_fixtures() {
+ for case in fixtures("text.json") {
+ let allow = allow_of(&case);
+ let input = case["input"].as_str().unwrap();
+ let expected = case["expected"].as_str().unwrap();
+ let actual = scrub_text(&allow, input).unwrap_or_else(|| input.to_string());
+ assert_eq!(actual, expected, "text case: {}", case["name"]);
+ }
+}
+
+#[test]
+fn url_fixtures() {
+ for case in fixtures("url.json") {
+ let allow = allow_of(&case);
+ let input = case["input"].as_str().unwrap();
+ let expected = case["expected"].as_str().unwrap();
+ let scrub_authority = case["scrubAuthority"].as_bool().unwrap_or(false);
+ let actual =
+ scrub_url_opts(&allow, input, scrub_authority).unwrap_or_else(|| input.to_string());
+ assert_eq!(actual, expected, "url case: {}", case["name"]);
+ }
+}
+
+#[test]
+fn event_fixtures() {
+ for case in fixtures("events.json") {
+ let allow = allow_of(&case);
+ let event_json = serde_json::to_string(&case["event"]).unwrap();
+ let scrubbed = anonymize_event_str(&allow, &event_json)
+ .expect("anonymize should not fail on fixtures");
+ let actual: Value = serde_json::from_str(&scrubbed).unwrap();
+ assert_eq!(actual, case["expected"], "event case: {}", case["name"]);
+ }
+}
+
+#[test]
+fn message_fixtures() {
+ // Full `{ windowId: Event[] }` messages (not single events) — exercises the whole-message walk:
+ // multiple windows, mixed/interleaved event types, malformed events, and the unchanged-message path.
+ for case in fixtures("messages.json") {
+ let allow = allow_of(&case);
+ let message_json = serde_json::to_string(&case["message"]).unwrap();
+ let mut bytes = message_json.into_bytes();
+ let scrubbed =
+ anonymize_message(&allow, &mut bytes).expect("anonymize should not fail on fixtures");
+ // `None` = nothing changed, so the caller keeps the original message.
+ let actual: Value = match scrubbed {
+ Some(s) => serde_json::from_str(&s).unwrap(),
+ None => case["message"].clone(),
+ };
+ assert_eq!(actual, case["expected"], "message case: {}", case["name"]);
+ }
+}
+
+#[test]
+fn pathologically_deep_json_fails_closed_without_crashing() {
+ // Untrusted rrweb could nest deep enough to overflow the walker's stack; the depth guard must
+ // reject it as an error (message dropped) rather than recursing into a crash.
+ let allow = AllowLists::new(Vec::<String>::new(), Vec::<String>::new());
+ let mut deep = String::from("{\"w\":");
+ deep.push_str(&"[".repeat(4000));
+ deep.push_str(&"]".repeat(4000));
+ deep.push('}');
+ let mut bytes = deep.into_bytes();
+ assert!(anonymize_message(&allow, &mut bytes).is_err());
+}
+
+#[test]
+fn email_redaction_is_linear() {
+ // A backtracking email regex is O(n^2) here (~seconds at this size); the linear scanner is ~ms.
+ let run = "A1b2C3d4".repeat((256 * 1024) / 8);
+ let allow = AllowLists::new(Vec::<String>::new(), Vec::<String>::new());
+ let start = Instant::now();
+ let out = scrub_text(&allow, &run);
+ assert!(
+ out.is_some(),
+ "an unbroken non-allowlisted run should be redacted"
+ );
+ assert!(
+ start.elapsed().as_millis() < 2000,
+ "email/text scrub should be linear, took {:?}",
+ start.elapsed()
+ );
+}
+
+#[test]
+fn email_scanner_worst_case_is_linear() {
+ // The exact incident shape: a long unbroken local part + `@` + a long domain that never forms a
+ // valid `.TLD` is what made the old email regex backtrack quadratically (minutes per event). The
+ // hand-rolled scanner expands around each `@` once with disjoint domain scans, so a 256 KB
+ // `@`-bearing run must still finish in milliseconds. `email_redaction_is_linear` has no `@`, so it
+ // only covers the tokenizer — this covers the email scanner itself.
+ let local = "a".repeat(128 * 1024);
+ let domain = "1".repeat(128 * 1024); // all digits: can never satisfy `.` + >=2 letters
+ let input = format!("{local}@{domain}");
+ let allow = AllowLists::new(Vec::<String>::new(), Vec::<String>::new());
+ let start = Instant::now();
+ let _ = scrub_text(&allow, &input);
+ assert!(
+ start.elapsed().as_millis() < 2000,
+ "email scanner should be linear on an @-bearing run, took {:?}",
+ start.elapsed()
+ );
+}
diff --git a/rust/replay-anonymizer-node/tests/snapshot.rs b/rust/replay-anonymizer-node/tests/snapshot.rs
new file mode 100644
index 000000000000..f3e5d892e0f3
--- /dev/null
+++ b/rust/replay-anonymizer-node/tests/snapshot.rs
@@ -0,0 +1,638 @@
+//! Tests for the byte-buffer snapshot pipeline (`snapshot.rs`).
+//!
+//! The streaming path is a byte scanner that must reproduce JSON.parse semantics without parsing;
+//! its failure modes are *divergence* bugs (mis-spliced spans, scanner-visible vs parser-visible
+//! keys, wrong dlq/drop classification), so the suite centers on a differential check against the
+//! tree path plus targeted leak/contract cases.
+
+use replay_anonymizer_node::allow_lists::AllowLists;
+use replay_anonymizer_node::snapshot::{
+ anonymize_kafka_payload, anonymize_kafka_payload_opts, anonymize_via_tree, AnonymizeOpts,
+ AnonymizedMessage, FailKind, Failure, FLAG_ACTIVE, FLAG_CLICK, FLAG_KEYPRESS,
+ FLAG_MOUSE_ACTIVITY,
+};
+use replay_anonymizer_node::Ctx;
+use serde_json::{json, Value};
+use std::path::Path;
+
+fn run(allow: &AllowLists, payload: &str) -> Result<AnonymizedMessage, Failure> {
+ let mut bytes = payload.as_bytes().to_vec();
+ anonymize_kafka_payload(allow, &mut bytes)
+}
+
+fn payload_of(inner: &Value) -> String {
+ serde_json::to_string(&json!({
+ "distinct_id": "d-1",
+ "data": serde_json::to_string(inner).unwrap(),
+ }))
+ .unwrap()
+}
+
+fn snapshot_message(events: Value) -> Value {
+ json!({
+ "event": "$snapshot_items",
+ "properties": {
+ "$snapshot_items": events,
+ "$session_id": "s-1",
+ "$window_id": "w-1",
+ "$snapshot_source": "web",
+ "$lib": "posthog-js",
+ }
+ })
+}
+
+/// Parse the output JSONL into `[windowId, event]` pairs.
+fn parse_lines(lines: &[u8]) -> Vec<Value> {
+ lines
+ .split(|b| *b == b'\n')
+ .filter(|l| !l.is_empty())
+ .map(|l| serde_json::from_slice(l).expect("output line must be valid json"))
+ .collect()
+}
+
+const TS0: f64 = 1_700_000_000_000.0;
+
+#[test]
+fn end_to_end_contract() {
+ let allow = AllowLists::new(["hello"], Vec::<String>::new());
+ let inner = snapshot_message(json!([
+ // Meta: href scrubbed (authority collapsed), no flags.
+ { "type": 4, "timestamp": TS0, "data": { "href": "https://foo.corp.com/path", "width": 1, "height": 1 } },
+ // Input: text scrubbed; keypress + active.
+ { "type": 3, "timestamp": TS0 + 1000.0, "data": { "source": 5, "id": 1, "text": "hello secret", "isChecked": false } },
+ // MouseInteraction click (pass-through): click + active + mouse.
+ { "type": 3, "timestamp": TS0 + 2000.5, "data": { "source": 2, "type": 2, "id": 5, "x": 1, "y": 2 } },
+ // Console warn plugin: counted, payload scrubbed.
+ { "type": 6, "timestamp": TS0 + 3000.0, "data": { "plugin": "rrweb/console@1", "payload": { "level": "warn", "payload": ["secret"], "trace": [] } } },
+ // Filtered out: no timestamp, non-object, non-positive timestamp.
+ { "type": 3, "data": { "source": 1 } },
+ "junk",
+ { "type": 3, "timestamp": -5, "data": { "source": 1 } },
+ ]));
+ let out = run(&allow, &payload_of(&inner)).expect("message anonymizes");
+
+ let lines = parse_lines(&out.lines);
+ assert_eq!(lines.len(), 4, "invalid events are filtered out");
+ for line in &lines {
+ assert_eq!(line[0], "w-1");
+ }
+ assert_eq!(
+ lines[0][1]["data"]["href"],
+ "https://example.com/[redacted]"
+ );
+ assert_eq!(lines[1][1]["data"]["text"], "hello ******");
+ assert_eq!(
+ lines[2][1]["data"],
+ json!({ "source": 2, "type": 2, "id": 5, "x": 1, "y": 2 })
+ );
+ assert_eq!(lines[3][1]["data"]["payload"]["payload"][0], "******");
+
+ let meta = &out.meta;
+ assert_eq!(meta.distinct_id, "d-1");
+ assert_eq!(meta.session_id, "s-1");
+ assert_eq!(meta.window_id, "w-1");
+ assert_eq!(meta.snapshot_source.as_deref(), Some("web"));
+ assert_eq!(meta.snapshot_library.as_deref(), Some("posthog-js"));
+ assert_eq!(meta.start_ts, TS0);
+ assert_eq!(meta.end_ts, TS0 + 3000.0);
+ assert_eq!(
+ (
+ meta.console_log_count,
+ meta.console_warn_count,
+ meta.console_error_count
+ ),
+ (0, 1, 0)
+ );
+
+ let flags: Vec<u8> = meta.events.iter().map(|e| e.flags).collect();
+ assert_eq!(
+ flags,
+ vec![
+ 0,
+ FLAG_ACTIVE | FLAG_KEYPRESS,
+ FLAG_ACTIVE | FLAG_CLICK | FLAG_MOUSE_ACTIVITY,
+ 0,
+ ]
+ );
+ assert_eq!(
+ meta.events[0].href.as_deref(),
+ Some("https://example.com/[redacted]"),
+ "href meta must be the post-scrub value"
+ );
+ assert_eq!(meta.events[1].href, None);
+ assert_eq!(
+ meta.events[2].ts,
+ TS0 + 2000.5,
+ "fractional timestamps survive"
+ );
+}
+
+#[test]
+fn failure_classification_matches_the_ts_parse_step() {
+ let allow = AllowLists::new(Vec::<String>::new(), Vec::<String>::new());
+ let ok_items = r#"[{"type":3,"timestamp":1700000000000,"data":{"source":1}}]"#;
+ let cases: Vec<(String, FailKind)> = vec![
+ ("not json".into(), FailKind::InvalidJson),
+ (r#"["array"]"#.into(), FailKind::InvalidMessagePayload),
+ (r#"{"data":"{}"}"#.into(), FailKind::InvalidMessagePayload),
+ (r#"{"distinct_id":"d","data":5}"#.into(), FailKind::InvalidMessagePayload),
+ (
+ payload_of(&json!({"event": "other", "properties": {"$snapshot_items": [], "$session_id": "s"}})),
+ FailKind::NonSnapshotMessage,
+ ),
+ (
+ r#"{"distinct_id":"d","data":"not json"}"#.into(),
+ FailKind::NonSnapshotMessage,
+ ),
+ (
+ payload_of(&json!({"event": "$snapshot_items", "properties": {"$snapshot_items": []}})),
+ FailKind::NonSnapshotMessage, // missing $session_id
+ ),
+ (
+ payload_of(&json!({"event": "$snapshot_items", "properties": {"$snapshot_items": [], "$session_id": ""}})),
+ FailKind::NonSnapshotMessage, // empty $session_id is falsy in the TS check
+ ),
+ (
+ payload_of(&json!({"event": "$snapshot_items", "properties": {"$snapshot_items": {}, "$session_id": "s"}})),
+ FailKind::NonSnapshotMessage, // zod: $snapshot_items must be an array
+ ),
+ (
+ payload_of(&json!({"event": "$snapshot_items", "properties": {"$session_id": "s"}})),
+ FailKind::NonSnapshotMessage, // missing $snapshot_items
+ ),
+ (
+ serde_json::to_string(&json!({
+ "distinct_id": "d",
+ "data": format!(r#"{{"event":"$snapshot_items","properties":{{"$snapshot_items":{ok_items},"$session_id":"s","$window_id":7}}}}"#),
+ }))
+ .unwrap(),
+ FailKind::NonSnapshotMessage, // zod: $window_id must be a string
+ ),
+ (
+ payload_of(&snapshot_message(json!([]))),
+ FailKind::NoValidEvents,
+ ),
+ (
+ payload_of(&snapshot_message(json!(["junk", {"type": 3}]))),
+ FailKind::NoValidEvents,
+ ),
+ ];
+ for (payload, expected) in cases {
+ let err = run(&allow, &payload).expect_err(&format!("should fail: {payload}"));
+ assert_eq!(err.kind, expected, "payload: {payload}");
+ }
+}
+
+#[test]
+fn scrub_errors_fail_closed_for_the_whole_message() {
+ let allow = AllowLists::new(Vec::<String>::new(), Vec::<String>::new());
+ // A cv event whose gzip stream is not latin-1 cannot be safely scrubbed: the message must drop,
+ // including its valid sibling event — never "emit what we could".
+ let inner = snapshot_message(json!([
+ { "type": 3, "timestamp": TS0, "data": { "source": 1 } },
+ { "type": 2, "timestamp": TS0 + 1.0, "cv": "2024-10", "data": "\u{100}bad" },
+ ]));
+ let err = run(&allow, &payload_of(&inner)).expect_err("must fail closed");
+ assert_eq!(err.kind, FailKind::AnonymizeFailed);
+
+ // Pathological nesting inside the event json fails closed before any recursive parse.
+ let nested = format!("{}{}", "[".repeat(2000), "]".repeat(2000));
+ let deep = format!(
+ r#"{{"event":"$snapshot_items","properties":{{"$session_id":"s","$snapshot_items":[{{"type":2,"timestamp":1700000000000,"data":{nested}}}]}}}}"#
+ );
+ let payload = serde_json::to_string(&json!({"distinct_id": "d", "data": deep})).unwrap();
+ let err = run(&allow, &payload).expect_err("must fail closed");
+ assert_eq!(err.kind, FailKind::NonSnapshotMessage);
+
+ // Mismatched brackets in an event's `data` (`[}`) are structurally invalid JSON; the scanner's
+ // span-locator must reject them (route to the tree) rather than close the wrong container and
+ // splice the invalid bytes through. The whole message fails closed, matching JSON.parse.
+ let mismatched = r#"{"event":"$snapshot_items","properties":{"$session_id":"s","$snapshot_items":[{"type":3,"timestamp":1700000000000,"data":{"source":1,"x":[}]}]}}"#;
+ let payload = serde_json::to_string(&json!({"distinct_id": "d", "data": mismatched})).unwrap();
+ run(&allow, &payload).expect_err("mismatched brackets must fail closed");
+}
+
+#[test]
+fn escaped_keys_cannot_smuggle_data_past_the_scanner() {
+ let allow = AllowLists::new(Vec::<String>::new(), Vec::<String>::new());
+ // `data` parses to the key `data` — the scanner can't see that, so it must fall back to a
+ // real parse and still scrub. A byte-compare router would pass the PII through verbatim.
+ let inner = r#"{"event":"$snapshot_items","properties":{"$session_id":"s","$window_id":"w","$snapshot_items":[{"type":3,"timestamp":1700000000000,"\u0064ata":{"source":5,"id":1,"text":"topsecret","isChecked":false}}]}}"#;
+ let payload = serde_json::to_string(&json!({"distinct_id": "d", "data": inner})).unwrap();
+ let out = run(&allow, &payload).expect("anonymizes via the tree fallback");
+ let lines = parse_lines(&out.lines);
+ assert_eq!(lines.len(), 1);
+ assert_eq!(lines[0][1]["data"]["text"], "*********");
+ assert!(
+ !out.lines.windows(9).any(|w| w == b"topsecret"),
+ "raw PII must not survive anywhere in the output bytes"
+ );
+
+ // Escaped keys at the envelope level route the whole message through the tree path.
+ let inner = r#"{"\u0065vent":"$snapshot_items","properties":{"$session_id":"s","$snapshot_items":[{"type":3,"timestamp":1700000000000,"data":{"source":5,"id":1,"text":"topsecret","isChecked":false}}]}}"#;
+ let payload = serde_json::to_string(&json!({"distinct_id": "d", "data": inner})).unwrap();
+ let out = run(&allow, &payload).expect("anonymizes via the tree fallback");
+ assert_eq!(parse_lines(&out.lines)[0][1]["data"]["text"], "*********");
+}
+
+#[test]
+fn duplicate_keys_cannot_shadow_pii_into_the_output() {
+ let allow = AllowLists::new(Vec::<String>::new(), Vec::<String>::new());
+ // JSON.parse keeps the *last* duplicate; the earlier one exists only in the raw bytes. The
+ // output must never contain it — a naive span memcpy would ship it to the unencrypted bucket.
+ let inner = r#"{"event":"$snapshot_items","properties":{"$session_id":"s","$snapshot_items":[{"type":3,"timestamp":1700000000000,"data":{"source":5,"id":1,"text":"leakyPII","isChecked":false},"data":{"source":5,"id":1,"text":"fine","isChecked":false}}]}}"#;
+ let payload = serde_json::to_string(&json!({"distinct_id": "d", "data": inner})).unwrap();
+ let out = run(&allow, &payload).expect("anonymizes");
+ let lines = parse_lines(&out.lines);
+ assert_eq!(lines[0][1]["data"]["text"], "****");
+ assert!(
+ !out.lines.windows(8).any(|w| w == b"leakyPII"),
+ "duplicate-key shadowed content must not survive"
+ );
+}
+
+#[test]
+fn pass_through_events_are_emitted_byte_exact() {
+ let allow = AllowLists::new(Vec::<String>::new(), Vec::<String>::new());
+ // A scroll event never routes to a scrubber; its bytes must be memcpy'd, not re-serialized —
+ // `1.50` would normalize to `1.5` through any parse/serialize round-trip.
+ let inner = r#"{"event":"$snapshot_items","properties":{"$session_id":"s","$window_id":"w","$snapshot_items":[{"type":3,"timestamp":1700000000000,"data":{"source":3,"id":7,"x":1.50,"y":0}}]}}"#;
+ let payload = serde_json::to_string(&json!({"distinct_id": "d", "data": inner})).unwrap();
+ let out = run(&allow, &payload).expect("anonymizes");
+ let text = String::from_utf8(out.lines.clone()).unwrap();
+ assert!(
+ text.contains(r#""x":1.50"#),
+ "pass-through span must keep its original bytes: {text}"
+ );
+}
+
+#[test]
+fn node_objects_with_too_many_keys_decline_to_the_parse() {
+ let allow = AllowLists::new(Vec::<String>::new(), Vec::<String>::new());
+ // A node with >MAX_OBJECT_KEYS unique keys must hand the event to the parse instead of running
+ // the per-key duplicate scan quadratically. The parse re-serializes numbers (`1.50` -> `1.5`),
+ // so the original bytes surviving means the walk handled it.
+ let junk: String = (0..33).map(|i| format!(r#""k{i}":1.50,"#)).collect();
+ let inner = format!(
+ r#"{{"event":"$snapshot_items","properties":{{"$session_id":"s","$window_id":"w","$snapshot_items":[{{"type":2,"timestamp":1700000000000,"data":{{"node":{{{junk}"type":3,"textContent":"reach me at [email protected]"}},"initialOffset":{{"left":0,"top":0}}}}}}]}}}}"#
+ );
+ let payload = serde_json::to_string(&json!({"distinct_id": "d", "data": inner})).unwrap();
+ let out = run(&allow, &payload).expect("anonymizes");
+ let text = String::from_utf8(out.lines.clone()).unwrap();
+ assert!(
+ !text.contains("1.50"),
+ "many-key node must decline to the parse (which normalizes 1.50 -> 1.5): {text}"
+ );
+ assert!(
+ !text.contains("[email protected]"),
+ "text still scrubbed: {text}"
+ );
+}
+
+#[test]
+fn decompress_payload_matches_the_capture_producer_format() {
+ use replay_anonymizer_node::snapshot::decompress_payload;
+ let body = br#"{"distinct_id":"d","data":"{}"}"#.to_vec();
+
+ // lz4: capture writes `block::compress` output behind a 4-byte LE uncompressed-size prefix,
+ // signalled by the content-encoding header.
+ let compressed = lz4::block::compress(&body, None, false).unwrap();
+ let mut framed = (body.len() as u32).to_le_bytes().to_vec();
+ framed.extend_from_slice(&compressed);
+ assert_eq!(decompress_payload(framed, Some("lz4")).unwrap(), body);
+
+ // gzip: detected by magic bytes, no header needed.
+ {
+ use std::io::Write;
+ let mut enc = flate2::write::GzEncoder::new(Vec::new(), flate2::Compression::default());
+ enc.write_all(&body).unwrap();
+ let zipped = enc.finish().unwrap();
+ assert_eq!(decompress_payload(zipped, None).unwrap(), body);
+ }
+
+ // Uncompressed passes through untouched.
+ assert_eq!(decompress_payload(body.clone(), None).unwrap(), body);
+
+ // Corrupt lz4 fails closed with the TS parse step's classification.
+ let err = decompress_payload(vec![9, 0, 0, 0, 0xff, 0xff], Some("lz4")).unwrap_err();
+ assert_eq!(err.kind.reason(), "invalid_compressed_data");
+}
+
+// ---------------------------------------------------------------------------
+// Differential: streaming vs tree on the shared fixtures plus seeded variations.
+// ---------------------------------------------------------------------------
+
+fn fixtures(name: &str) -> Vec<Value> {
+ let path = Path::new(env!("CARGO_MANIFEST_DIR"))
+ .join("tests/fixtures")
+ .join(name);
+ let data = std::fs::read_to_string(&path).unwrap_or_else(|e| panic!("read {path:?}: {e}"));
+ serde_json::from_str(&data).unwrap_or_else(|e| panic!("parse {path:?}: {e}"))
+}
+
+fn allow_of(case: &Value) -> AllowLists {
+ let strings = |key: &str| -> Vec<String> {
+ case["allow"][key]
+ .as_array()
+ .map(|a| {
+ a.iter()
+ .filter_map(|v| v.as_str().map(str::to_string))
+ .collect()
+ })
+ .unwrap_or_default()
+ };
+ AllowLists::new(strings("text"), strings("url"))
+}
+
+/// Deterministic xorshift64* so the fuzz corpus is reproducible.
+struct Rng(u64);
+impl Rng {
+ fn next(&mut self) -> u64 {
+ let mut x = self.0;
+ x ^= x >> 12;
+ x ^= x << 25;
+ x ^= x >> 27;
+ self.0 = x;
+ x.wrapping_mul(0x2545F4914F6CDD1D)
+ }
+ fn pick<'a, T>(&mut self, items: &'a [T]) -> &'a T {
+ &items[(self.next() % items.len() as u64) as usize]
+ }
+ fn chance(&mut self, one_in: u64) -> bool {
+ self.next().is_multiple_of(one_in)
+ }
+}
+
+fn assert_stream_matches_tree(allow: &AllowLists, inner_json: &str, label: &str) {
+ let payload = serde_json::to_string(&json!({"distinct_id": "d", "data": inner_json})).unwrap();
+ let ctx = Ctx::new(allow);
+ let tree = anonymize_via_tree(&ctx, "d", inner_json.as_bytes());
+
+ // Both scrub engines are pinned: the parse-free byte walk (with its per-event fallbacks) and
+ // the simd path.
+ for byte_walk in [true, false] {
+ let mut bytes = payload.as_bytes().to_vec();
+ let stream = anonymize_kafka_payload_opts(allow, &mut bytes, AnonymizeOpts { byte_walk });
+ match (&stream, &tree) {
+ (Ok(s), Ok(t)) => {
+ let s_lines = parse_lines(&s.lines);
+ let t_lines = parse_lines(&t.lines);
+ assert_eq!(
+ s_lines, t_lines,
+ "lines diverged (walk={byte_walk}): {label}"
+ );
+ assert_eq!(s.meta, t.meta, "meta diverged (walk={byte_walk}): {label}");
+ }
+ (Err(s), Err(t)) => {
+ assert_eq!(
+ s.kind, t.kind,
+ "failure kind diverged (walk={byte_walk}): {label}"
+ );
+ }
+ (s, t) => panic!(
+ "outcome diverged (walk={byte_walk}) for {label}: stream={:?} tree={:?}",
+ s.as_ref().map(|m| parse_lines(&m.lines)),
+ t.as_ref().map(|m| parse_lines(&m.lines)),
+ ),
+ }
+ }
+}
+
+#[test]
+fn differential_stream_vs_tree() {
+ // Event templates: every shared fixture event (scrub-routed shapes) plus pass-through shapes the
+ // fixtures don't cover. Timestamps are injected since the scrub fixtures don't carry them.
+ let event_cases = fixtures("events.json");
+ let message_cases = fixtures("messages.json");
+
+ let window_ids: &[&str] = &["w1", "", "π😀", "w\"quote\\back", "line\u{2028}sep", "\t"];
+ let pass_through: &[Value] = &[
+ json!({ "type": 3, "data": { "source": 1, "positions": [{"x": 1.5, "y": 2, "id": 3, "timeOffset": -20}] } }),
+ json!({ "type": 3, "data": { "source": 3, "id": 7, "x": 0, "y": 142.25 } }),
+ json!({ "type": 3, "data": { "source": 2, "type": 9, "id": 4, "x": 1, "y": 2 } }),
+ json!({ "type": 0, "data": {} }),
+ json!({ "type": 1, "data": {} }),
+ json!({ "type": 3, "data": { "source": 8, "id": 1, "adds": [{"rule": "body { color: red }"}] } }),
+ // Unknown/absent discriminants and odd extras.
+ json!({ "type": 99, "data": { "anything": ["x", 1, null] } }),
+ json!({ "data": { "source": 5, "text": "no type at all" } }),
+ json!({ "type": 3, "data": "not an object" }),
+ json!({ "type": 4, "data": { "href": " https://pad.example.io/x " } }),
+ ];
+ let junk_strings: &[&str] = &[
+ "plain",
+ "with \"quotes\" and \\backslashes\\",
+ "unicode π😀\u{2028}\u{2029}",
+ "control\u{1}\u{1f}",
+ "email [email protected] inside",
+ ];
+
+ let mut rng = Rng(0x5EED_CAFE_F00D_1234);
+ let mut checked = 0usize;
+
+ for case in event_cases.iter() {
+ let allow = allow_of(case);
+ let base_event = &case["event"];
+ for round in 0..6 {
+ // A message mixing the fixture event with random pass-through shapes and junk fields.
+ let mut events: Vec<Value> = Vec::new();
+ for i in 0..(1 + (rng.next() % 4)) {
+ let mut ev = if rng.chance(2) {
+ base_event.clone()
+ } else {
+ rng.pick(pass_through).clone()
+ };
+ if let Some(obj) = ev.as_object_mut() {
+ if !rng.chance(10) {
+ // Mostly-valid timestamps: integers and fractionals; occasionally missing.
+ let ts = TS0 + (i as f64) * 250.0 + if rng.chance(3) { 0.25 } else { 0.0 };
+ obj.insert("timestamp".into(), json!(ts));
+ }
+ if rng.chance(3) {
+ obj.insert("delay".into(), json!((rng.next() % 100) as i64));
+ }
+ if rng.chance(4) {
+ obj.insert("junk".into(), json!(*rng.pick(junk_strings)));
+ }
+ if rng.chance(5) {
+ // Float-encoded discriminant, e.g. `"type": 3.0` — must route identically.
+ if let Some(t) = obj.get("type").and_then(Value::as_i64) {
+ obj.insert("type".into(), json!(t as f64 + 0.0));
+ }
+ }
+ }
+ events.push(ev);
+ }
+ let mut message = snapshot_message(Value::Array(events));
+ message["properties"]["$window_id"] = json!(*rng.pick(window_ids));
+ if rng.chance(3) {
+ message["properties"]["extra"] = json!(*rng.pick(junk_strings));
+ }
+ if rng.chance(4) {
+ let obj = message["properties"].as_object_mut().unwrap();
+ obj.remove("$snapshot_source");
+ obj.remove("$lib");
+ }
+ let inner = if rng.chance(3) {
+ serde_json::to_string_pretty(&message).unwrap()
+ } else {
+ serde_json::to_string(&message).unwrap()
+ };
+ assert_stream_matches_tree(
+ &allow,
+ &inner,
+ &format!("case {} round {round}", case["name"]),
+ );
+ checked += 1;
+ }
+ }
+
+ // Whole-message fixtures: run each window's events as one payload.
+ for case in &message_cases {
+ let allow = allow_of(case);
+ for (window_id, events) in case["message"].as_object().unwrap() {
+ let mut events = events.clone();
+ if let Some(arr) = events.as_array_mut() {
+ for (i, ev) in arr.iter_mut().enumerate() {
+ if let Some(obj) = ev.as_object_mut() {
+ obj.insert("timestamp".into(), json!(TS0 + i as f64));
+ }
+ }
+ }
+ let mut message = snapshot_message(events);
+ message["properties"]["$window_id"] = json!(window_id);
+ let inner = serde_json::to_string(&message).unwrap();
+ assert_stream_matches_tree(
+ &allow,
+ &inner,
+ &format!("message case {} window {window_id}", case["name"]),
+ );
+ checked += 1;
+ }
+ }
+
+ assert!(
+ checked > 100,
+ "the differential corpus should stay meaningful, got {checked}"
+ );
+}
+
+#[test]
+fn differential_cv_stream_vs_tree() {
+ // Compressed with flate2 (an independent codec from the libdeflate legs under test); latin-1
+ // encoding matches the SDK (each gzip byte as its U+00XX codepoint). serde's serialization of
+ // these strings exercises every wire arm of the walker's latin-1 decoder: \u00XX and shorthand
+ // escapes for control bytes, raw two-byte UTF-8 for 0x80..=0xFF.
+ fn gz_latin1(json: &[u8]) -> String {
+ use std::io::Write;
+ let mut enc = flate2::write::GzEncoder::new(Vec::new(), flate2::Compression::default());
+ enc.write_all(json).unwrap();
+ enc.finish().unwrap().iter().map(|&b| b as char).collect()
+ }
+
+ let allow = AllowLists::new(["keep"], Vec::<String>::new());
+
+ let scrubbed_snapshot = gz_latin1(
+ br#"{"node":{"childNodes":[{"attributes":{"src":"https://cdn.corp.com/a.png","title":"keep secret"},"childNodes":[],"id":4,"tagName":"img","type":2},{"id":5,"textContent":"keep secret words","type":3}],"id":1,"type":0},"initialOffset":{"left":0,"top":0}}"#,
+ );
+ let unchanged_snapshot = gz_latin1(
+ br#"{"node":{"childNodes":[{"id":5,"textContent":"keep keep","type":3}],"id":1,"type":0}}"#,
+ );
+ // Escaped key: the walker declines both the wire walk and the decompressed walk; the parse
+ // fallback (which sees the key as `textContent`) must still scrub it.
+ let escaped_key_snapshot =
+ gz_latin1(br#"{"node":{"id":5,"\u0074extContent":"keep secret","type":3}}"#);
+ let texts_gz = gz_latin1(br#"[{"id":5,"value":"keep secret"}]"#);
+ let adds_unchanged_gz = gz_latin1(
+ br#"[{"nextId":null,"node":{"childNodes":[],"id":9,"tagName":"div","type":2},"parentId":1}]"#,
+ );
+ let attrs_gz = gz_latin1(br#"[{"attributes":{"src":"https://cdn.corp.com/img.png"},"id":3}]"#);
+ let non_array_gz = gz_latin1(br#"{"a":1}"#);
+
+ let ok_cases: Vec<(Value, &str)> = vec![
+ (
+ json!({ "type": 2, "timestamp": TS0, "cv": "2024-10", "data": scrubbed_snapshot }),
+ "cv snapshot scrubbed",
+ ),
+ (
+ json!({ "type": 2, "timestamp": TS0, "cv": "2024-10", "data": unchanged_snapshot }),
+ "cv snapshot unchanged",
+ ),
+ (
+ json!({ "type": 2, "timestamp": TS0, "cv": "2024-10", "data": escaped_key_snapshot }),
+ "cv snapshot with escaped key (parse fallback)",
+ ),
+ (
+ json!({ "type": 2, "timestamp": TS0, "cv": "2024-10", "data": { "node": { "id": 5, "textContent": "keep secret", "type": 3 } } }),
+ "cv marker with object data scrubs plain",
+ ),
+ (
+ json!({ "type": 3, "timestamp": TS0, "cv": "2024-10", "data": { "source": 0, "adds": adds_unchanged_gz, "attributes": null, "texts": texts_gz } }),
+ "cv mutation: texts change, adds don't, attributes null",
+ ),
+ (
+ json!({ "type": 3, "timestamp": TS0, "cv": "2024-10", "data": { "source": 0, "attributes": attrs_gz, "texts": "" } }),
+ "cv mutation: attributes change, texts empty string",
+ ),
+ (
+ json!({ "type": 3, "timestamp": TS0, "cv": "2024-10", "data": { "source": 0, "texts": [{ "id": 5, "value": "keep secret" }] } }),
+ "cv mutation: plain-array sub-field",
+ ),
+ (
+ json!({ "type": 3, "timestamp": TS0, "cv": "2024-10", "data": { "id": 1, "source": 5, "text": "keep secret" } }),
+ "cv marker on input scrubs plain",
+ ),
+ (
+ json!({ "type": 2, "timestamp": TS0, "cv": null, "data": { "node": { "id": 5, "textContent": "keep secret", "type": 3 } } }),
+ "null cv marker is not compressed",
+ ),
+ ];
+
+ for (event, label) in &ok_cases {
+ let inner = serde_json::to_string(&snapshot_message(json!([event]))).unwrap();
+ assert_stream_matches_tree(&allow, &inner, label);
+ }
+
+ // All succeeding shapes in one message: exercises sink sequencing around re-emitted cv spans.
+ let all: Vec<Value> = ok_cases.iter().map(|(e, _)| e.clone()).collect();
+ let inner = serde_json::to_string(&snapshot_message(json!(all))).unwrap();
+ assert_stream_matches_tree(&allow, &inner, "all cv shapes in one message");
+
+ // Failing shapes must fail identically through both paths.
+ for (event, label) in [
+ (
+ json!({ "type": 3, "timestamp": TS0, "cv": "2024-10", "data": { "source": 0, "texts": non_array_gz } }),
+ "cv mutation: non-array payload",
+ ),
+ (
+ json!({ "type": 2, "timestamp": TS0, "cv": "2024-10", "data": "not gzip" }),
+ "cv snapshot: non-gzip string",
+ ),
+ ] {
+ let inner = serde_json::to_string(&snapshot_message(json!([event]))).unwrap();
+ assert_stream_matches_tree(&allow, &inner, label);
+ }
+}
+
+#[test]
+fn mutation_media_attr_past_the_prescan_budget_declines_to_the_parse() {
+ // A media `src` positioned past the byte walk's 4 KB attribute prescan budget: the walk's
+ // media probe hits its fallback there, which must decline to the tree (not silently classify
+ // the attributes as non-media and scrub the src as a plain URL). The differential fails on the
+ // stream-vs-tree divergence if that decline is dropped.
+ let allow = AllowLists::new(Vec::<String>::new(), Vec::<String>::new());
+ let padding = "x".repeat(5000);
+ let inner = snapshot_message(json!([{
+ "type": 3,
+ "timestamp": TS0,
+ "data": { "source": 0, "attributes": [
+ { "id": 1, "attributes": { "data-pad": padding, "src": "https://cdn.corp.com/a.png" } }
+ ]}
+ }]));
+ let inner_json = serde_json::to_string(&inner).unwrap();
+ assert_stream_matches_tree(
+ &allow,
+ &inner_json,
+ "media src past the attribute prescan budget",
+ );
+}
diff --git a/rust/replay-anonymizer-node/tsconfig.json b/rust/replay-anonymizer-node/tsconfig.json
new file mode 100644
index 000000000000..d6d504ce92ae
--- /dev/null
+++ b/rust/replay-anonymizer-node/tsconfig.json
@@ -0,0 +1,22 @@
+{
+ "compilerOptions": {
+ "module": "nodenext",
+ "target": "esnext",
+ "declaration": true,
+ "removeComments": true,
+ "moduleResolution": "nodenext",
+ "esModuleInterop": true,
+ "allowJs": true,
+ "sourceMap": true,
+ "rootDir": "src/",
+ "outDir": "dist/",
+ "types": ["node"],
+ "resolveJsonModule": true,
+ "strict": true,
+ "noImplicitAny": true,
+ "useUnknownInCatchVariables": false,
+ "skipLibCheck": true
+ },
+ "include": ["src"],
+ "exclude": ["node_modules", "dist", "bin"]
+}