Skip to content

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

feat(replay): add anonymized ml training mirror for session recordings (#65916)

Tue Haulunde064dc7b0017
diff --git a/nodejs/package.json b/nodejs/package.json
index 9baa0b64bf8e..580868b70c81 100644
--- a/nodejs/package.json
+++ b/nodejs/package.json
@@ -69,6 +69,7 @@
"@clickhouse/client": "^1.12.0",
"@connectrpc/connect": "^2.1.1",
"@connectrpc/connect-node": "^2.1.1",
+ "@dsnp/parquetjs": "^1.8.7",
"@google-cloud/pubsub": "4.11.0",
"@google-cloud/storage": "^5.8.5",
"@maxmind/geoip2-node": "^3.4.0",
@@ -113,9 +114,9 @@
"libsodium-wrappers": "^0.7.15",
"liquidjs": "^10.27.0",
"lodash": "^4.18.1",
- "lz4": "^0.6.5",
"lru-cache": "^11.0.0",
"luxon": "^3.4.4",
+ "lz4": "^0.6.5",
"node-fetch": "^2.6.1",
"node-rdkafka": "^3.6.1",
"node-schedule": "^2.1.0",
@@ -129,6 +130,7 @@
"puppeteer": "^24.3.0",
"puppeteer-capture": "^1.43.0",
"re2": "^1.22.1",
+ "sharp": "^0.34.5",
"snappy": "^7.2.2",
"tail": "^2.2.6",
"tldts": "^6.1.57",
diff --git a/nodejs/src/capabilities.ts b/nodejs/src/capabilities.ts
index b2ccdc309c41..cb45bce1be35 100644
--- a/nodejs/src/capabilities.ts
+++ b/nodejs/src/capabilities.ts
@@ -206,6 +206,8 @@ export function getPluginServerCapabilities(
}
case PluginServerMode.recordings_blob_ingestion_v2:
case PluginServerMode.recordings_blob_ingestion_v2_overflow:
+ case PluginServerMode.recordings_blob_ingestion_v2_ml_mirror:
+ case PluginServerMode.recordings_blob_ingestion_v2_ml_parquet_sink:
case PluginServerMode.recording_api:
throw new Error(`Mode ${mode} is handled by IngestionSessionReplayServer, not PluginServer`)
}
diff --git a/nodejs/src/common/config.ts b/nodejs/src/common/config.ts
index 764fccd36169..884a91828201 100644
--- a/nodejs/src/common/config.ts
+++ b/nodejs/src/common/config.ts
@@ -22,6 +22,8 @@ export enum PluginServerMode {
recordings_blob_ingestion_v2 = 'recordings-blob-ingestion-v2',
// TODO: Remove once charts deploy with mode=recordings-blob-ingestion-v2 for overflow pods
recordings_blob_ingestion_v2_overflow = 'recordings-blob-ingestion-v2-overflow',
+ recordings_blob_ingestion_v2_ml_mirror = 'recordings-blob-ingestion-v2-ml-mirror',
+ recordings_blob_ingestion_v2_ml_parquet_sink = 'recordings-blob-ingestion-v2-ml-parquet-sink',
cdp_processed_events = 'cdp-processed-events',
cdp_person_updates = 'cdp-person-updates',
cdp_data_warehouse_events = 'cdp-data-warehouse-events',
diff --git a/nodejs/src/common/config/kafka-topics.ts b/nodejs/src/common/config/kafka-topics.ts
index 1a6adfaf5e66..2f2b57a08ca3 100644
--- a/nodejs/src/common/config/kafka-topics.ts
+++ b/nodejs/src/common/config/kafka-topics.ts
@@ -36,6 +36,9 @@ export const KAFKA_CLICKHOUSE_SESSION_RECORDING_EVENTS = `${prefix}clickhouse_se
export const KAFKA_CLICKHOUSE_SESSION_REPLAY_EVENTS = `${prefix}clickhouse_session_replay_events${suffix}`
export const KAFKA_CLICKHOUSE_SESSION_REPLAY_FEATURES = `${prefix}clickhouse_session_replay_features${suffix}`
+// anonymized block metadata mirrored to the ML account (consumed by the Parquet sink, not ClickHouse)
+export const KAFKA_SESSION_REPLAY_ML_BLOCK_METADATA = `${prefix}session_replay_ml_block_metadata${suffix}`
+
// write performance events to ClickHouse
export const KAFKA_PERFORMANCE_EVENTS = `${prefix}clickhouse_performance_events${suffix}`
// write heatmap events to ClickHouse
diff --git a/nodejs/src/index.ts b/nodejs/src/index.ts
index ea566f314e6a..ce3e6fc2a63f 100644
--- a/nodejs/src/index.ts
+++ b/nodejs/src/index.ts
@@ -11,6 +11,8 @@ import { IngestionApiServer } from '~/servers/ingestion-api-server'
import { IngestionGeneralServer } from '~/servers/ingestion-general-server'
import { IngestionLogsServer } from '~/servers/ingestion-logs-server'
import { IngestionMetricsServer } from '~/servers/ingestion-metrics-server'
+import { IngestionSessionReplayMlMirrorServer } from '~/servers/ingestion-session-replay-ml-mirror-server'
+import { IngestionSessionReplayMlParquetSinkServer } from '~/servers/ingestion-session-replay-ml-parquet-sink-server'
import { IngestionSessionReplayServer } from '~/servers/ingestion-session-replay-server'
import { IngestionTracesServer } from '~/servers/ingestion-traces-server'
import { RecordingApiServer } from '~/servers/recording-api-server'
@@ -31,6 +33,12 @@ function createServer(): NodeServer {
case PluginServerMode.recordings_blob_ingestion_v2_overflow:
return new IngestionSessionReplayServer()
+ case PluginServerMode.recordings_blob_ingestion_v2_ml_mirror:
+ return new IngestionSessionReplayMlMirrorServer()
+
+ case PluginServerMode.recordings_blob_ingestion_v2_ml_parquet_sink:
+ return new IngestionSessionReplayMlParquetSinkServer()
+
case PluginServerMode.recording_api:
return new RecordingApiServer()
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ai-training-optin-filter-step.test.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ai-training-optin-filter-step.test.ts
new file mode 100644
index 000000000000..1928b508943e
--- /dev/null
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ai-training-optin-filter-step.test.ts
@@ -0,0 +1,25 @@
+import { PipelineResultType } from '~/ingestion/framework/results'
+
+import { createAiTrainingOptInFilterStep } from './ai-training-optin-filter-step'
+import { TeamForReplay } from './teams/types'
+
+describe('ai-training-optin-filter-step', () => {
+ const step = createAiTrainingOptInFilterStep()
+ const team = (aiTrainingOptedIn: boolean): TeamForReplay => ({
+ teamId: 1,
+ consoleLogIngestionEnabled: false,
+ aiTrainingOptedIn,
+ })
+
+ it('passes through a team that opted into AI training', async () => {
+ const input = { team: team(true) }
+ const result = await step(input)
+ expect(result.type).toBe(PipelineResultType.OK)
+ })
+
+ it('drops a team that did not opt in', async () => {
+ const result = await step({ team: team(false) })
+ expect(result.type).toBe(PipelineResultType.DROP)
+ expect(result.type === PipelineResultType.DROP && result.reason).toBe('team_not_ai_training_opted_in')
+ })
+})
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ai-training-optin-filter-step.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ai-training-optin-filter-step.ts
new file mode 100644
index 000000000000..e54ac53aa962
--- /dev/null
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ai-training-optin-filter-step.ts
@@ -0,0 +1,17 @@
+import { drop, ok } from '~/ingestion/framework/results'
+import { ProcessingStep } from '~/ingestion/framework/steps'
+import { TeamForReplay } from '~/ingestion/pipelines/sessionreplay/teams/types'
+
+export interface AiTrainingOptInFilterStepInput {
+ team: TeamForReplay
+}
+
+/** Drops sessions whose org did not opt into AI training (fail-closed); used only by the ML mirror. */
+export function createAiTrainingOptInFilterStep<T extends AiTrainingOptInFilterStepInput>(): ProcessingStep<T, T> {
+ return function aiTrainingOptInFilterStep(input) {
+ if (!input.team.aiTrainingOptedIn) {
+ return Promise.resolve(drop('team_not_ai_training_opted_in'))
+ }
+ return Promise.resolve(ok(input))
+ }
+}
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/anonymize-step.test.ts b/nodejs/src/ingestion/pipelines/sessionreplay/anonymize-step.test.ts
new file mode 100644
index 000000000000..fb294a772138
--- /dev/null
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/anonymize-step.test.ts
@@ -0,0 +1,82 @@
+import { PipelineResultType } from '~/ingestion/framework/results'
+
+import { createAnonymizeStep } from './anonymize-step'
+import { defaultAllowLists } from './anonymize/default-dict'
+import { ParsedMessageData } from './kafka/types'
+
+describe('anonymize-step', () => {
+ const step = createAnonymizeStep({ scrubContext: { allow: defaultAllowLists() } })
+
+ const parsedMessageWith = (eventsByWindowId: Record<string, any[]>): ParsedMessageData =>
+ ({ eventsByWindowId }) as unknown as ParsedMessageData
+
+ it('scrubs events across all windows in place and returns OK', async () => {
+ const parsedMessage = parsedMessageWith({
+ win1: [{ type: 3, timestamp: 1, data: { source: 5, id: 1, text: 'Hello SecretName', isChecked: false } }],
+ win2: [{ type: 4, timestamp: 2, data: { href: 'https://example.com/user/abc/edit', width: 1, height: 1 } }],
+ })
+
+ const result = await step({ parsedMessage })
+
+ expect(result.type).toBe(PipelineResultType.OK)
+ expect((parsedMessage.eventsByWindowId.win1[0] as any).data.text).toBe('Hello **********')
+ expect((parsedMessage.eventsByWindowId.win2[0] as any).data.href).toBe(
+ 'https://example.com/user/[redacted]/edit'
+ )
+ })
+
+ it('blurs a data-image media source via the deferred job pass', async () => {
+ // Small patterned PNG (portable across libvips/libpng builds; a solid color would blur to
+ // identical bytes, so we use a checkerboard the blur visibly changes).
+ const onePxPng =
+ 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAIAAACQkWg2AAAACXBIWXMAAAPoAAAD6AG1e1JrAAAAJUlEQVQokWN4plEBRyInbOAIlzjDINRAjCJk8cGoYRAG60iMBwA8H08Qor0ygQAAAABJRU5ErkJggg=='
+ const parsedMessage = parsedMessageWith({
+ win1: [
+ {
+ type: 2,
+ timestamp: 1,
+ data: {
+ node: {
+ type: 0,
+ id: 1,
+ childNodes: [
+ { type: 2, id: 2, tagName: 'img', attributes: { src: onePxPng }, childNodes: [] },
+ ],
+ },
+ initialOffset: { top: 0, left: 0 },
+ },
+ },
+ ],
+ })
+
+ await step({ parsedMessage })
+
+ const src = (parsedMessage.eventsByWindowId.win1[0] as any).data.node.childNodes[0].attributes.src
+ // Blurred into a fresh PNG, not left as the placeholder or the original.
+ expect(src.startsWith('data:image/png;base64,')).toBe(true)
+ expect(src).not.toBe(onePxPng)
+ })
+
+ it('passes through events with no scrubbable content', async () => {
+ const parsedMessage = parsedMessageWith({
+ win1: [{ type: 3, timestamp: 1, data: { source: 1, positions: [] } }],
+ })
+
+ const result = await step({ parsedMessage })
+
+ expect(result.type).toBe(PipelineResultType.OK)
+ expect((parsedMessage.eventsByWindowId.win1[0] as any).data.source).toBe(1)
+ })
+
+ it('fails closed: drops the message when an event cannot be anonymized', async () => {
+ // A FullSnapshot whose data string is not valid latin-1 throws during scrubbing.
+ const parsedMessage = parsedMessageWith({
+ win1: [{ type: 2, timestamp: 1, cv: '2024-10', data: 'not-Ā-gzip' }],
+ })
+
+ const result = await step({ parsedMessage })
+
+ expect(result.type).toBe(PipelineResultType.DROP)
+ expect(result.type === PipelineResultType.DROP && result.reason).toBe('anonymize_failed')
+ })
+})
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/anonymize-step.ts b/nodejs/src/ingestion/pipelines/sessionreplay/anonymize-step.ts
new file mode 100644
index 000000000000..62ad91f20434
--- /dev/null
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/anonymize-step.ts
@@ -0,0 +1,31 @@
+import { drop, ok } from '~/ingestion/framework/results'
+import { ProcessingStep } from '~/ingestion/framework/steps'
+
+import { anonymizeParsedMessage } from './anonymize/anonymize-event'
+import { ScrubContext } from './anonymize/config'
+import { ParsedMessageData } from './kafka/types'
+
+export interface AnonymizeStepInput {
+ parsedMessage: ParsedMessageData
+}
+
+export interface AnonymizeStepConfig {
+ /** Shared, immutable scrub context (allow lists + tunables). */
+ scrubContext: ScrubContext
+}
+
+/**
+ * Anonymizes the parsed events in place before recording. Drops the message if any
+ * event can't be anonymized — fail-closed, since blocks are written unencrypted.
+ */
+export function createAnonymizeStep<T extends AnonymizeStepInput>(config: AnonymizeStepConfig): ProcessingStep<T, T> {
+ const { scrubContext } = config
+
+ return async function anonymizeStep(input) {
+ const { failed } = await anonymizeParsedMessage(scrubContext, input.parsedMessage)
+ if (failed) {
+ return drop('anonymize_failed')
+ }
+ return ok(input)
+ }
+}
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/anonymize/allow-list-loader.test.ts b/nodejs/src/ingestion/pipelines/sessionreplay/anonymize/allow-list-loader.test.ts
new file mode 100644
index 000000000000..811992954859
--- /dev/null
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/anonymize/allow-list-loader.test.ts
@@ -0,0 +1,46 @@
+import { buildAllowLists, loadAllowLists } from './allow-list-loader'
+
+describe('anonymize/allow-list-loader', () => {
+ describe('buildAllowLists', () => {
+ it('builds lists from a well-formed document', () => {
+ const lists = buildAllowLists({ text: ['Keepme'], url: ['Segment'] })
+ // Looked up case-insensitively.
+ expect(lists.textContains('keepme')).toBe(true)
+ expect(lists.urlContains('segment')).toBe(true)
+ expect(lists.textContains('other')).toBe(false)
+ })
+
+ it('filters non-string entries and tolerates missing fields', () => {
+ const lists = buildAllowLists({ text: ['ok', 42, null, { a: 1 }] as unknown[] })
+ expect(lists.textContains('ok')).toBe(true)
+ // Missing url field → empty url list (over-redaction, the safe direction).
+ expect(lists.urlContains('anything')).toBe(false)
+ })
+
+ it('coerces a garbage document to empty lists rather than throwing', () => {
+ const lists = buildAllowLists({ text: 'not-an-array' as unknown as unknown[] })
+ expect(lists.textContains('the')).toBe(false)
+ })
+ })
+
+ describe('loadAllowLists', () => {
+ it('returns the in-binary defaults when no fetcher is configured', async () => {
+ const lists = await loadAllowLists(undefined)
+ // A default stopword is present.
+ expect(lists.textContains('the')).toBe(true)
+ })
+
+ it('uses the fetched lists on success', async () => {
+ const lists = await loadAllowLists(() => Promise.resolve({ text: ['customword'], url: [] }))
+ expect(lists.textContains('customword')).toBe(true)
+ // The fetched list replaces (does not merge with) the defaults.
+ expect(lists.textContains('the')).toBe(false)
+ })
+
+ it('FAILS SAFE: a fetch error falls back to defaults, never to no scrubbing', async () => {
+ const lists = await loadAllowLists(() => Promise.reject(new Error('s3 unavailable')))
+ // Defaults are restored, so scrubbing stays enabled.
+ expect(lists.textContains('the')).toBe(true)
+ })
+ })
+})
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/anonymize/allow-list-loader.ts b/nodejs/src/ingestion/pipelines/sessionreplay/anonymize/allow-list-loader.ts
new file mode 100644
index 000000000000..a3109bd8bf75
--- /dev/null
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/anonymize/allow-list-loader.ts
@@ -0,0 +1,43 @@
+/** Loads the anonymizer allow lists, failing safe to the in-binary defaults (never to "no scrubbing"). */
+import { logger } from '~/common/utils/logger'
+
+import { AllowLists } from './allow-lists'
+import { defaultAllowLists } from './default-dict'
+
+export interface RawAllowLists {
+ text?: unknown
+ url?: unknown
+}
+
+/** Fetches the raw `{ text, url }` allow-list document (e.g. from S3). */
+export type AllowListFetcher = () => Promise<RawAllowLists>
+
+// Bound an untrusted allow-list document so a malformed/huge file can't exhaust memory.
+const MAX_ALLOW_LIST_ENTRIES = 500_000
+const MAX_ALLOW_LIST_ENTRY_LEN = 256
+
+function sanitizeEntries(raw: unknown): string[] {
+ if (!Array.isArray(raw)) {
+ return []
+ }
+ const entries = raw.filter((x): x is string => typeof x === 'string' && x.length <= MAX_ALLOW_LIST_ENTRY_LEN)
+ return entries.length > MAX_ALLOW_LIST_ENTRIES ? entries.slice(0, MAX_ALLOW_LIST_ENTRIES) : entries
+}
+
+export function buildAllowLists(raw: RawAllowLists): AllowLists {
+ return new AllowLists(sanitizeEntries(raw.text), sanitizeEntries(raw.url))
+}
+
+/** Load the allow lists once at startup, returning the in-binary defaults if there's no fetcher or it fails. */
+export async function loadAllowLists(fetcher: AllowListFetcher | undefined): Promise<AllowLists> {
+ if (!fetcher) {
+ return defaultAllowLists()
+ }
+ try {
+ const raw = await fetcher()
+ return buildAllowLists(raw)
+ } catch (error) {
+ logger.warn('🙈', 'anonymize_allow_list_load_failed_using_defaults', { error: String(error) })
+ return defaultAllowLists()
+ }
+}
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/anonymize/allow-lists.ts b/nodejs/src/ingestion/pipelines/sessionreplay/anonymize/allow-lists.ts
new file mode 100644
index 000000000000..8d79f9b2f462
--- /dev/null
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/anonymize/allow-lists.ts
@@ -0,0 +1,45 @@
+/** Case-insensitive allow lists of text words and URL path segments kept verbatim by the scrubbers. */
+
+function hasUpperAscii(s: string): boolean {
+ for (let i = 0; i < s.length; i++) {
+ const code = s.charCodeAt(i)
+ if (code >= 0x41 && code <= 0x5a) {
+ return true
+ }
+ }
+ return false
+}
+
+function asciiLowercase(s: string): string {
+ let out = ''
+ for (let i = 0; i < s.length; i++) {
+ const code = s.charCodeAt(i)
+ out += code >= 0x41 && code <= 0x5a ? String.fromCharCode(code + 0x20) : s[i]
+ }
+ return out
+}
+
+export class AllowLists {
+ private readonly text: Set<string>
+ private readonly url: Set<string>
+
+ constructor(text: Iterable<string>, url: Iterable<string>) {
+ this.text = new Set<string>()
+ for (const word of text) {
+ this.text.add(asciiLowercase(word))
+ }
+ this.url = new Set<string>()
+ for (const segment of url) {
+ this.url.add(asciiLowercase(segment))
+ }
+ }
+
+ public textContains(word: string): boolean {
+ // Fast path: an already-lowercase word needs no allocation.
+ return this.text.has(hasUpperAscii(word) ? asciiLowercase(word) : word)
+ }
+
+ public urlContains(segment: string): boolean {
+ return this.url.has(hasUpperAscii(segment) ? asciiLowercase(segment) : segment)
+ }
+}
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/anonymize/anonymize-event.test.ts b/nodejs/src/ingestion/pipelines/sessionreplay/anonymize/anonymize-event.test.ts
new file mode 100644
index 000000000000..c9d204fe7085
--- /dev/null
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/anonymize/anonymize-event.test.ts
@@ -0,0 +1,124 @@
+import { anonymizeEvent } from './anonymize-event'
+import { defaultAllowLists } from './default-dict'
+
+describe('anonymize/event router', () => {
+ const ctx = { allow: defaultAllowLists() }
+
+ it('scrubs Input text', () => {
+ const event: any = {
+ type: 3,
+ timestamp: 1,
+ data: { source: 5, id: 1, text: 'Hello SecretName', isChecked: false },
+ }
+ expect(anonymizeEvent(ctx, event)).toBe(true)
+ expect(event.data.text).toBe('Hello **********')
+ })
+
+ it('URL-scrubs Meta href and leaves width/height untouched', () => {
+ const event: any = {
+ type: 4,
+ timestamp: 1,
+ data: { href: 'https://example.com/api/v1/users/abc', width: 1280, height: 720 },
+ }
+ expect(anonymizeEvent(ctx, event)).toBe(true)
+ expect(event.data.href).toBe('https://example.com/api/v1/users/[redacted]')
+ expect(event.data.width).toBe(1280)
+ expect(event.data.height).toBe(720)
+ })
+
+ it('passes through a FullSnapshot with nothing to scrub', () => {
+ const event: any = {
+ type: 2,
+ timestamp: 1,
+ data: { node: { type: 0, id: 1, childNodes: [] }, initialOffset: { top: 0, left: 0 } },
+ }
+ expect(anonymizeEvent(ctx, event)).toBe(false)
+ })
+
+ it('passes through mouse-move incremental events', () => {
+ const event: any = {
+ type: 3,
+ timestamp: 1,
+ data: { source: 1, positions: [{ x: 1, y: 2, id: 3, timeOffset: 0 }] },
+ }
+ expect(anonymizeEvent(ctx, event)).toBe(false)
+ })
+
+ it('passes through Load events', () => {
+ const event: any = { type: 1, timestamp: 1, data: {} }
+ expect(anonymizeEvent(ctx, event)).toBe(false)
+ })
+
+ it('scrubs console plugin payload strings', () => {
+ const event: any = {
+ type: 6,
+ timestamp: 1,
+ data: { plugin: 'rrweb/console@1', payload: { level: 'info', payload: ['Hello SecretName'], trace: [] } },
+ }
+ expect(anonymizeEvent(ctx, event)).toBe(true)
+ expect(event.data.payload.payload[0]).toBe('Hello **********')
+ })
+
+ it('scrubs network plugin request name and body', () => {
+ const event: any = {
+ type: 6,
+ timestamp: 1,
+ data: {
+ plugin: 'rrweb/network@1',
+ payload: { requests: [{ name: 'https://example.com/user/abc/edit', requestBody: 'Hello SecretName' }] },
+ },
+ }
+ expect(anonymizeEvent(ctx, event)).toBe(true)
+ expect(event.data.payload.requests[0].name).toBe('https://example.com/user/[redacted]/edit')
+ expect(event.data.payload.requests[0].requestBody).toBe('Hello **********')
+ })
+
+ it('scrubs an arbitrary Custom payload generically', () => {
+ const event: any = { type: 5, timestamp: 1, data: { tag: 'x', payload: { note: 'Hello SecretName' } } }
+ expect(anonymizeEvent(ctx, event)).toBe(true)
+ expect(event.data.payload.note).toBe('Hello **********')
+ })
+
+ it('scrubs an unknown plugin payload generically', () => {
+ const event: any = {
+ type: 6,
+ timestamp: 1,
+ data: { plugin: 'some/other-plugin@1', payload: { note: 'Hello SecretName' } },
+ }
+ expect(anonymizeEvent(ctx, event)).toBe(true)
+ expect(event.data.payload.note).toBe('Hello **********')
+ })
+
+ it.each([
+ ['IncrementalSnapshot', 3],
+ ['Meta', 4],
+ ['Custom', 5],
+ ['Plugin', 6],
+ ])('passes through %s events whose data is not an object', (_name, type) => {
+ const event: any = { type, timestamp: 1, data: null }
+ expect(anonymizeEvent(ctx, event)).toBe(false)
+ })
+
+ it('passes through incremental events with an unhandled source', () => {
+ const event: any = { type: 3, timestamp: 1, data: { source: 99, foo: 'bar' } }
+ expect(anonymizeEvent(ctx, event)).toBe(false)
+ })
+
+ it('passes through (no change) a malformed event with non-object data', () => {
+ const event: any = { type: 2, timestamp: 1, data: null }
+ expect(anonymizeEvent(ctx, event)).toBe(false)
+ })
+
+ it('throws when a scrubber errors, so the caller can fail closed', () => {
+ // A throwing getter on `data` forces an exception inside routing. The
+ // error must propagate (not be swallowed as "nothing to scrub").
+ const event: any = {
+ type: 2,
+ timestamp: 1,
+ get data() {
+ throw new Error('boom')
+ },
+ }
+ expect(() => anonymizeEvent(ctx, event)).toThrow('boom')
+ })
+})
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/anonymize/anonymize-event.ts b/nodejs/src/ingestion/pipelines/sessionreplay/anonymize/anonymize-event.ts
new file mode 100644
index 000000000000..b4b66e77debe
--- /dev/null
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/anonymize/anonymize-event.ts
@@ -0,0 +1,136 @@
+/** 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 { RRWebEventSource, RRWebEventType } from '~/ingestion/pipelines/sessionreplay/rrweb-types'
+
+import { runBlurJobs } from './blur'
+import { scrubCanvasMutation } from './canvas'
+import { BlurJob, ScrubContext, isObject } from './config'
+import { scrubCompressedFullSnapshot, scrubCompressedMutation } from './cv'
+import { scrubFullSnapshot, scrubMutation } from './dom'
+import { scrubText } from './text'
+import { scrubUrl } from './url'
+import { scrubConsolePlugin, scrubGenericField, scrubNetworkPlugin } from './value'
+
+const NETWORK_PLUGIN = 'rrweb/network@1'
+const CONSOLE_PLUGIN = 'rrweb/console@1'
+
+/**
+ * Anonymizes every event in a parsed message in place, then awaits its blur jobs.
+ * Fails closed: returns `failed: true` if any event errors, so the caller can drop
+ * the message rather than write un-anonymized data to the unencrypted ML bucket.
+ */
+export async function anonymizeParsedMessage(
+ scrubContext: ScrubContext,
+ parsedMessage: ParsedMessageData
+): Promise<{ failed: boolean }> {
+ const blurJobs: BlurJob[] = []
+ const ctx: ScrubContext = { ...scrubContext, blurJobs }
+
+ for (const events of Object.values(parsedMessage.eventsByWindowId)) {
+ for (const event of events) {
+ try {
+ anonymizeEvent(ctx, event)
+ } catch (error) {
+ logger.warn('🙈', 'anonymize_event_failed', {
+ error: String(error),
+ type: isObject(event) ? event.type : undefined,
+ })
+ return { failed: true }
+ }
+ }
+ }
+
+ await runBlurJobs(blurJobs)
+ return { failed: false }
+}
+
+/**
+ * Scrubs a single event in place, returning whether it changed. Throws if a
+ * scrubber errors — callers must treat a throw as "could not anonymize", never
+ * as "nothing to scrub".
+ */
+export function anonymizeEvent(ctx: ScrubContext, event: unknown): boolean {
+ if (!isObject(event)) {
+ return false
+ }
+ return routeEvent(ctx, event)
+}
+
+function routeEvent(ctx: ScrubContext, event: Record<string, unknown>): boolean {
+ const compressed = event.cv != null
+ const data = event.data
+
+ switch (event.type) {
+ case RRWebEventType.FullSnapshot:
+ return compressed ? scrubCompressedFullSnapshot(ctx, event) : scrubFullSnapshot(ctx, data)
+
+ case RRWebEventType.IncrementalSnapshot: {
+ if (!isObject(data)) {
+ return false
+ }
+ if (data.source === RRWebEventSource.Mutation) {
+ return compressed ? scrubCompressedMutation(ctx, event) : scrubMutation(ctx, data)
+ }
+ if (data.source === RRWebEventSource.Input) {
+ return scrubStringField(ctx, data, 'text', 'text')
+ }
+ if (data.source === RRWebEventSource.CanvasMutation) {
+ return scrubCanvasMutation(ctx, data)
+ }
+ return false
+ }
+
+ case RRWebEventType.Meta: {
+ // Meta `href` is the page URL — also strip the authority and rewrite the host to
+ // example.com (Meta only for now).
+ if (!isObject(data) || typeof data.href !== 'string') {
+ return false
+ }
+ const r = scrubUrl(ctx, data.href, { scrubAuthority: true })
+ if (r.changed) {
+ data.href = r.value
+ return true
+ }
+ return false
+ }
+
+ case RRWebEventType.Custom:
+ return isObject(data) ? scrubGenericField(ctx, data, 'payload') : false
+
+ case RRWebEventType.Plugin: {
+ if (!isObject(data)) {
+ return false
+ }
+ if (data.plugin === NETWORK_PLUGIN) {
+ return scrubNetworkPlugin(ctx, data, 'payload')
+ }
+ if (data.plugin === CONSOLE_PLUGIN) {
+ return scrubConsolePlugin(ctx, data, 'payload')
+ }
+ return scrubGenericField(ctx, data, 'payload')
+ }
+
+ default:
+ // DomContentLoaded, Load, unknown types: pass-through.
+ return false
+ }
+}
+
+function scrubStringField(
+ ctx: ScrubContext,
+ owner: Record<string, unknown>,
+ key: string,
+ kind: 'text' | 'url'
+): boolean {
+ const value = owner[key]
+ if (typeof value !== 'string') {
+ return false
+ }
+ const result = kind === 'url' ? scrubUrl(ctx, value) : scrubText(ctx, value)
+ if (result.changed) {
+ owner[key] = result.value
+ return true
+ }
+ return false
+}
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/anonymize/assets.test.ts b/nodejs/src/ingestion/pipelines/sessionreplay/anonymize/assets.test.ts
new file mode 100644
index 000000000000..ac61bbd42f80
--- /dev/null
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/anonymize/assets.test.ts
@@ -0,0 +1,35 @@
+import { PLACEHOLDER_SRC, applyBlur, isMediaTag } from './assets'
+import { defaultAllowLists } from './default-dict'
+
+describe('anonymize/assets', () => {
+ const ctx = { allow: defaultAllowLists() }
+
+ it('classifies media tags', () => {
+ for (const tag of ['img', 'IMG', 'image', 'video', 'audio', 'source', 'track']) {
+ expect(isMediaTag(tag)).toBe(true)
+ }
+ for (const tag of ['iframe', 'div', 'a']) {
+ expect(isMediaTag(tag)).toBe(false)
+ }
+ })
+
+ it('replaces a remote src with the placeholder and stashes a host+path-scrubbed original', () => {
+ const attrs: Record<string, unknown> = { src: 'https://cdn.acme.io/users/42/avatar.png?t=secret' }
+ applyBlur(ctx, attrs)
+ expect(attrs.src).toBe(PLACEHOLDER_SRC)
+ const stash = attrs['data-anon-original-src'] as string
+ expect(typeof stash).toBe('string')
+ expect(stash).toContain('example.com') // host rewritten
+ expect(stash).not.toContain('acme') // original host gone
+ expect(stash).not.toContain('42') // path identifier redacted
+ expect(stash).not.toContain('secret') // query dropped
+ })
+
+ it('replaces a data-image src with the placeholder', () => {
+ const attrs: Record<string, unknown> = { src: 'data:image/png;base64,AAAA' }
+ applyBlur(ctx, attrs)
+ expect(attrs.src).toBe(PLACEHOLDER_SRC)
+ // data-image has no URL to preserve, so no stash is added.
+ expect('data-anon-original-src' in attrs).toBe(false)
+ })
+})
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/anonymize/assets.ts b/nodejs/src/ingestion/pipelines/sessionreplay/anonymize/assets.ts
new file mode 100644
index 000000000000..3e44b2e9d05d
--- /dev/null
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/anonymize/assets.ts
@@ -0,0 +1,82 @@
+/** Media detection + placeholder/blur dispatch. */
+import { BLANK_IMAGE_DATA_URI, blurImageDataUri, isImageDataUri } from './blur'
+import { ScrubContext } from './config'
+import { scrubUrl } from './url'
+
+// rrweb inlines rendered pixels (a `toDataURL()` snapshot) into this attribute — for `<canvas>`
+// in a FullSnapshot/adds, and for `<img>` when image inlining is on. It holds raw drawn content.
+export const INLINE_IMAGE_ATTR = 'rr_dataURL'
+
+export const PLACEHOLDER_SRC =
+ "data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 80 80'><rect width='80' height='80' fill='%23f3f4f6'/><rect x='6' y='6' width='68' height='68' fill='none' stroke='%23d1d5db' stroke-width='2' rx='6'/><circle cx='26' cy='26' r='6' fill='%239ca3af'/><path d='M14 60 L34 40 L48 50 L66 32 L66 66 L14 66 Z' fill='%239ca3af'/></svg>"
+
+export const MEDIA_SRC_ATTRS = ['src', 'srcset', 'href', 'xlink:href', 'poster']
+
+export function isMediaTag(tag: string): boolean {
+ switch (tag.toLowerCase()) {
+ case 'img':
+ case 'image':
+ case 'video':
+ case 'audio':
+ case 'source':
+ case 'track':
+ case 'picture':
+ return true
+ default:
+ return false
+ }
+}
+
+export function isMediaSrcAttr(name: string): boolean {
+ return MEDIA_SRC_ATTRS.includes(name)
+}
+
+/** True if an attribute map contains any media-source attribute. */
+export function hasMediaSrcAttr(attrs: Record<string, unknown>): boolean {
+ return MEDIA_SRC_ATTRS.some((name) => Object.prototype.hasOwnProperty.call(attrs, name))
+}
+
+/**
+ * Blur an inlined-image data URI held in an attribute (a `<canvas>`/`<img>` `rr_dataURL`).
+ * Blanks it synchronously (fail-safe) and defers the real blur. Returns whether it acted.
+ */
+export function blurInlineImageAttr(ctx: ScrubContext, attrs: Record<string, unknown>, name: string): boolean {
+ const value = attrs[name]
+ if (typeof value !== 'string' || !isImageDataUri(value)) {
+ return false
+ }
+ const original = value
+ attrs[name] = BLANK_IMAGE_DATA_URI
+ ctx.blurJobs?.push(async () => {
+ const blurred = await blurImageDataUri(original)
+ if (blurred !== null) {
+ attrs[name] = blurred
+ }
+ })
+ return true
+}
+
+/** Replace a media element's source attrs with the placeholder (queuing a blur job for data-images). */
+export function applyBlur(ctx: ScrubContext, attrs: Record<string, unknown>): void {
+ for (const key of MEDIA_SRC_ATTRS) {
+ const existing = attrs[key]
+ if (typeof existing !== 'string') {
+ continue
+ }
+ if (isImageDataUri(existing)) {
+ attrs[key] = PLACEHOLDER_SRC
+ ctx.blurJobs?.push(async () => {
+ const blurred = await blurImageDataUri(existing)
+ if (blurred !== null) {
+ attrs[key] = blurred
+ }
+ })
+ } else {
+ // Stash the scrubbed original under a namespaced attr (won't collide with app
+ // `data-original-*`), host-scrubbed too so the CDN host can't leak.
+ const scrubbed = scrubUrl(ctx, existing, { scrubAuthority: true })
+ attrs[key] = PLACEHOLDER_SRC
+ attrs[`data-anon-original-${key}`] = scrubbed.changed ? scrubbed.value : existing
+ }
+ }
+}
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/anonymize/blur.test.ts b/nodejs/src/ingestion/pipelines/sessionreplay/anonymize/blur.test.ts
new file mode 100644
index 000000000000..ad9e14c2f87b
--- /dev/null
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/anonymize/blur.test.ts
@@ -0,0 +1,76 @@
+import sharp from 'sharp'
+
+import { blurImageDataUri, isImageDataUri, runBlurJobs } from './blur'
+
+// A small patterned PNG (portable across libvips/libpng builds; a bare 1x1 is rejected by some,
+// and a solid color blurs to identical bytes, so we use a checkerboard the blur visibly changes).
+const ONE_PX_PNG =
+ 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAIAAACQkWg2AAAACXBIWXMAAAPoAAAD6AG1e1JrAAAAJUlEQVQokWN4plEBRyInbOAIlzjDINRAjCJk8cGoYRAG60iMBwA8H08Qor0ygQAAAABJRU5ErkJggg=='
+
+describe('anonymize/blur', () => {
+ it('detects image data URIs', () => {
+ expect(isImageDataUri('data:image/png;base64,AAAA')).toBe(true)
+ expect(isImageDataUri('https://example.com/x.png')).toBe(false)
+ expect(isImageDataUri('data:text/plain,hi')).toBe(false)
+ })
+
+ it('gaussian-blurs a base64 image into a PNG data URI', async () => {
+ const out = await blurImageDataUri(ONE_PX_PNG)
+ expect(out).not.toBeNull()
+ expect(out!.startsWith('data:image/png;base64,')).toBe(true)
+ // It is a real, different encoding, not the original bytes echoed back.
+ expect(out).not.toBe(ONE_PX_PNG)
+ })
+
+ it('falls back to a downsample when the gaussian blur throws', async () => {
+ // Force the Gaussian path to fail; the resize-only fallback should still produce an image.
+ const proto = Object.getPrototypeOf(sharp(Buffer.from([0])))
+ const spy = jest.spyOn(proto, 'blur').mockImplementation(() => {
+ throw new Error('blur boom')
+ })
+ try {
+ const out = await blurImageDataUri(ONE_PX_PNG)
+ expect(out).not.toBeNull()
+ expect(out!.startsWith('data:image/png;base64,')).toBe(true)
+ } finally {
+ spy.mockRestore()
+ }
+ })
+
+ it('returns null for non-image and remote sources', async () => {
+ expect(await blurImageDataUri('https://example.com/x.png')).toBeNull()
+ expect(await blurImageDataUri('data:text/plain;base64,aGk=')).toBeNull()
+ expect(await blurImageDataUri('data:image/png,notbase64')).toBeNull()
+ // No comma → not a data URI we can parse.
+ expect(await blurImageDataUri('data:image/png')).toBeNull()
+ })
+
+ it('runBlurJobs is a no-op for an empty or absent job list', async () => {
+ await expect(runBlurJobs([])).resolves.toBeUndefined()
+ await expect(runBlurJobs(undefined)).resolves.toBeUndefined()
+ })
+
+ it('runBlurJobs runs every job', async () => {
+ let ran = 0
+ const bump = () => {
+ ran++
+ return Promise.resolve()
+ }
+ await runBlurJobs([bump, bump])
+ expect(ran).toBe(2)
+ })
+
+ it('runBlurJobs swallows a job that throws (already-blanked image is left as-is)', async () => {
+ let ran = 0
+ await expect(
+ runBlurJobs([
+ () => Promise.reject(new Error('boom')),
+ () => {
+ ran++
+ return Promise.resolve()
+ },
+ ])
+ ).resolves.toBeUndefined()
+ expect(ran).toBe(1)
+ })
+})
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/anonymize/blur.ts b/nodejs/src/ingestion/pipelines/sessionreplay/anonymize/blur.ts
new file mode 100644
index 000000000000..68d666cd965a
--- /dev/null
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/anonymize/blur.ts
@@ -0,0 +1,107 @@
+/** Downsample + blur media/canvas images — scene stays legible, faces/text don't. Run deferred. */
+import sharp from 'sharp'
+
+import { BlurJob } from './config'
+
+const DOWNSAMPLE_RATIO = 0.12
+const BLUR_SIGMA = 2.34
+const MAX_LONG_SIDE = 96
+
+/** A 1×1 transparent PNG: the fail-safe stand-in dropped in before (and if) the real blur lands. */
+export const BLANK_PNG_BASE64 =
+ 'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNk+M9QDwADhgGAWjR9awAAAABJRU5ErkJggg=='
+export const BLANK_IMAGE_DATA_URI = `data:image/png;base64,${BLANK_PNG_BASE64}`
+
+export function isImageDataUri(s: string): boolean {
+ return s.startsWith('data:image/')
+}
+
+/** Scale to DOWNSAMPLE_RATIO, but never leave the long side above MAX_LONG_SIDE; floored at 1px. */
+function targetDims(width: unknown, height: unknown): [number, number] {
+ const w = typeof width === 'number' && width > 0 ? width : 1
+ const h = typeof height === 'number' && height > 0 ? height : 1
+ const scale = Math.min(DOWNSAMPLE_RATIO, MAX_LONG_SIDE / Math.max(w, h))
+ return [Math.max(1, Math.round(w * scale)), Math.max(1, Math.round(h * scale))]
+}
+
+/** Downsample a base64 image data URI to a fraction of its size + a blur, as a PNG; null if it can't. */
+export async function blurImageDataUri(s: string): Promise<string | null> {
+ if (!s.startsWith('data:')) {
+ return null
+ }
+ const comma = s.indexOf(',')
+ if (comma === -1) {
+ return null
+ }
+ const meta = s.slice('data:'.length, comma)
+ if (!meta.includes('base64') || !meta.startsWith('image/')) {
+ return null
+ }
+ const bytes = Buffer.from(s.slice(comma + 1), 'base64')
+
+ let tw: number, th: number
+ try {
+ const info = await sharp(bytes).metadata()
+ ;[tw, th] = targetDims(info.width, info.height)
+ } catch {
+ return null // can't even read the header
+ }
+ // Primary: downsample + Gaussian blur.
+ try {
+ const out = await sharp(bytes).resize(tw, th, { fit: 'fill' }).blur(BLUR_SIGMA).png().toBuffer()
+ return `data:image/png;base64,${out.toString('base64')}`
+ } catch {
+ // Blur failed on an odd input — fall through to a plain downsample (still de-identifies).
+ }
+ try {
+ const out = await sharp(bytes).resize(tw, th, { fit: 'fill' }).png().toBuffer()
+ return `data:image/png;base64,${out.toString('base64')}`
+ } catch {
+ return null
+ }
+}
+
+/**
+ * De-identify raw RGBA pixels: downsample to DOWNSAMPLE_RATIO + a blur, then scale back up to the
+ * original W×H, preserving byte length (`4·W·H`) so it slots back into a `putImageData` ImageData.
+ */
+export async function pixelateRawRgba(base64: string, width: number, height: number): Promise<string | null> {
+ try {
+ const buf = Buffer.from(base64, 'base64')
+ if (buf.length !== width * height * 4) {
+ return null
+ }
+ const [sw, sh] = targetDims(width, height)
+ const small = await sharp(buf, { raw: { width, height, channels: 4 } })
+ .resize(sw, sh, { fit: 'fill' })
+ .blur(BLUR_SIGMA)
+ .ensureAlpha()
+ .raw()
+ .toBuffer()
+ const out = await sharp(small, { raw: { width: sw, height: sh, channels: 4 } })
+ .resize(width, height, { fit: 'fill' })
+ .ensureAlpha()
+ .raw()
+ .toBuffer()
+ return out.length === width * height * 4 ? out.toString('base64') : null
+ } catch {
+ return null
+ }
+}
+
+/** Run deferred blur jobs concurrently. A job that throws is swallowed — the image was already
+ * blanked synchronously, so a failed enhancement degrades to the blank rather than leaking. */
+export async function runBlurJobs(jobs: BlurJob[] | undefined): Promise<void> {
+ if (!jobs || jobs.length === 0) {
+ return
+ }
+ await Promise.all(
+ jobs.map(async (job) => {
+ try {
+ await job()
+ } catch {
+ // image already neutralized synchronously; skip the enhancement
+ }
+ })
+ )
+}
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/anonymize/canvas.test.ts b/nodejs/src/ingestion/pipelines/sessionreplay/anonymize/canvas.test.ts
new file mode 100644
index 000000000000..ab4046e61e41
--- /dev/null
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/anonymize/canvas.test.ts
@@ -0,0 +1,190 @@
+import { runBlurJobs } from './blur'
+import { scrubCanvasMutation } from './canvas'
+import { BlurJob, ScrubContext } from './config'
+import { defaultAllowLists } from './default-dict'
+
+// A small patterned PNG (portable across libvips/libpng builds; solid colors blur to identical
+// bytes, so we use a checkerboard the blur visibly changes).
+const ONE_PX_PNG_BASE64 =
+ 'iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAIAAACQkWg2AAAACXBIWXMAAAPoAAAD6AG1e1JrAAAAJUlEQVQokWN4plEBRyInbOAIlzjDINRAjCJk8cGoYRAG60iMBwA8H08Qor0ygQAAAABJRU5ErkJggg=='
+// Must match BLANK_PNG_BASE64 in blur.ts (the fail-safe placeholder; never re-decoded).
+const BLANK_PNG_BASE64 =
+ 'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNk+M9QDwADhgGAWjR9awAAAABJRU5ErkJggg=='
+
+function makeCtx(): ScrubContext & { blurJobs: BlurJob[] } {
+ return { allow: defaultAllowLists(), blurJobs: [] }
+}
+
+describe('anonymize/canvas', () => {
+ it('redacts text drawn via fillText/strokeText (batched commands)', () => {
+ const ctx = makeCtx()
+ const data = {
+ source: 9,
+ id: 1,
+ type: 0,
+ commands: [
+ { property: 'fillText', args: ['SecretCustomerName', 10, 20] },
+ { property: 'strokeText', args: ['AnotherSecret', 0, 0] },
+ ],
+ }
+ expect(scrubCanvasMutation(ctx, data)).toBe(true)
+ expect(data.commands[0].args[0]).not.toContain('Secret')
+ expect(data.commands[0].args[0]).toMatch(/^\*+$/)
+ expect(data.commands[1].args[0]).toMatch(/^\*+$/)
+ // Numeric coordinates are untouched.
+ expect(data.commands[0].args[1]).toBe(10)
+ })
+
+ it('redacts text in the flattened single-command form', () => {
+ const ctx = makeCtx()
+ const data = { source: 9, id: 1, type: 0, property: 'fillText', args: ['HelloSecret', 1, 2] }
+ expect(scrubCanvasMutation(ctx, data)).toBe(true)
+ expect(data.args[0]).toMatch(/^\*+$/)
+ })
+
+ it('blanks a data:image arg synchronously and queues a blur job', () => {
+ const ctx = makeCtx()
+ const data = {
+ source: 9,
+ id: 1,
+ type: 0,
+ commands: [{ property: 'drawImage', args: [`data:image/png;base64,${ONE_PX_PNG_BASE64}`, 0, 0] }],
+ }
+ expect(scrubCanvasMutation(ctx, data)).toBe(true)
+ // Raw image gone immediately (fail-safe), blur deferred.
+ expect(data.commands[0].args[0]).not.toContain(ONE_PX_PNG_BASE64)
+ expect(data.commands[0].args[0]).toMatch(/^data:image\/png;base64,/)
+ expect(ctx.blurJobs).toHaveLength(1)
+ })
+
+ it('blanks an encoded image Blob snapshot and queues a blur job (ImageBitmap → Blob → ArrayBuffer)', () => {
+ const ctx = makeCtx()
+ const ab = { rr_type: 'ArrayBuffer', base64: ONE_PX_PNG_BASE64 }
+ const data = {
+ source: 9,
+ id: 1,
+ type: 0,
+ commands: [
+ {
+ property: 'drawImage',
+ args: [
+ { rr_type: 'ImageBitmap', args: [{ rr_type: 'Blob', type: 'image/png', data: [ab] }] },
+ 0,
+ 0,
+ ],
+ },
+ ],
+ }
+ expect(scrubCanvasMutation(ctx, data)).toBe(true)
+ expect(ab.base64).toBe(BLANK_PNG_BASE64)
+ expect(ctx.blurJobs).toHaveLength(1)
+ })
+
+ it('blanks a data:image src and URL-scrubs a remote src', () => {
+ const ctx = makeCtx()
+ const data = {
+ source: 9,
+ id: 1,
+ type: 0,
+ commands: [
+ {
+ property: 'drawImage',
+ args: [{ rr_type: 'HTMLImageElement', src: `data:image/png;base64,${ONE_PX_PNG_BASE64}` }],
+ },
+ {
+ property: 'drawImage',
+ args: [{ rr_type: 'HTMLImageElement', src: 'https://cdn.example.com/users/SecretUser/a.png' }],
+ },
+ ],
+ }
+ expect(scrubCanvasMutation(ctx, data)).toBe(true)
+ expect((data.commands[0].args[0] as any).src).toMatch(/^data:image\/png;base64,/)
+ expect((data.commands[0].args[0] as any).src).not.toContain(ONE_PX_PNG_BASE64)
+ expect((data.commands[1].args[0] as any).src).not.toContain('SecretUser')
+ expect((data.commands[1].args[0] as any).src).toContain('https://cdn.example.com')
+ expect(ctx.blurJobs).toHaveLength(1)
+ })
+
+ it('leaves non-image args (numbers, non-image ArrayBuffers) untouched', () => {
+ const ctx = makeCtx()
+ const buf = { rr_type: 'ArrayBuffer', base64: 'V0VCR0xCVUZGRVI=' } // not inside an image Blob
+ const data = {
+ source: 9,
+ id: 1,
+ type: 1,
+ commands: [
+ { property: 'setTransform', args: [1, 0, 0, 1, 0, 0] },
+ { property: 'bufferData', args: [34962, buf, 35044] },
+ ],
+ }
+ expect(scrubCanvasMutation(ctx, data)).toBe(false)
+ expect(buf.base64).toBe('V0VCR0xCVUZGRVI=')
+ expect(ctx.blurJobs).toHaveLength(0)
+ })
+
+ it('runs queued blur jobs end to end, swapping the blank for a real blurred image', async () => {
+ const ctx = makeCtx()
+ const ab = { rr_type: 'ArrayBuffer', base64: ONE_PX_PNG_BASE64 }
+ const data = {
+ source: 9,
+ id: 1,
+ type: 0,
+ commands: [{ property: 'drawImage', args: [{ rr_type: 'Blob', type: 'image/png', data: [ab] }, 0, 0] }],
+ }
+ scrubCanvasMutation(ctx, data)
+ await runBlurJobs(ctx.blurJobs)
+ // After blurring: not the blank placeholder and not the original.
+ expect(ab.base64).not.toBe(BLANK_PNG_BASE64)
+ expect(ab.base64).not.toBe(ONE_PX_PNG_BASE64)
+ })
+
+ // Build a putImageData command holding a W×H RGBA buffer with a non-uniform pattern.
+ const W = 32
+ const H = 32
+ function rawImageDataCommand(): { ab: { rr_type: string; base64: string }; data: Record<string, unknown> } {
+ const rgba = Buffer.alloc(W * H * 4)
+ for (let i = 0; i < W * H; i++) {
+ rgba[i * 4] = (i * 7) & 255
+ rgba[i * 4 + 1] = (i * 3) & 255
+ rgba[i * 4 + 2] = 200
+ rgba[i * 4 + 3] = 255
+ }
+ const ab = { rr_type: 'ArrayBuffer', base64: rgba.toString('base64') }
+ const data = {
+ source: 9,
+ id: 1,
+ type: 0,
+ property: 'putImageData',
+ args: [
+ { rr_type: 'ImageData', args: [{ rr_type: 'Uint8ClampedArray', args: [ab, 0, W * H * 4] }, W, H] },
+ 0,
+ 0,
+ ],
+ }
+ return { ab, data }
+ }
+
+ it('blanks raw ImageData pixels synchronously and queues a pixelate job', () => {
+ const ctx = makeCtx()
+ const { ab, data } = rawImageDataCommand()
+ const original = ab.base64
+ expect(scrubCanvasMutation(ctx, data)).toBe(true)
+ const blanked = Buffer.from(ab.base64, 'base64')
+ expect(blanked.length).toBe(W * H * 4)
+ expect(blanked.every((b) => b === 0)).toBe(true) // raw pixels gone immediately
+ expect(ab.base64).not.toBe(original)
+ expect(ctx.blurJobs).toHaveLength(1)
+ })
+
+ it('runs the ImageData pixelate job: same byte length, restored content, not the original', async () => {
+ const ctx = makeCtx()
+ const { ab, data } = rawImageDataCommand()
+ const original = ab.base64
+ scrubCanvasMutation(ctx, data)
+ await runBlurJobs(ctx.blurJobs)
+ const out = Buffer.from(ab.base64, 'base64')
+ expect(out.length).toBe(W * H * 4) // dimensions preserved for putImageData
+ expect(out.every((b) => b === 0)).toBe(false) // pixelated content restored
+ expect(ab.base64).not.toBe(original) // but not the original detail
+ })
+})
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/anonymize/canvas.ts b/nodejs/src/ingestion/pipelines/sessionreplay/anonymize/canvas.ts
new file mode 100644
index 000000000000..52d3d6ec159a
--- /dev/null
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/anonymize/canvas.ts
@@ -0,0 +1,266 @@
+/**
+ * Scrubs rrweb CanvasMutation events: redacts text drawn via fill/strokeText and
+ * Gaussian-blurs drawn images and canvas snapshots.
+ *
+ * Canvas data is either batched (`{ commands: [{property, args, setter?}] }`) or a
+ * single flattened command (`{ property, args, setter? }`). Each `args` entry is a
+ * recursive `CanvasArg`: primitives, arrays, or serialized objects —
+ * { rr_type: 'ArrayBuffer', base64 }
+ * { rr_type: 'Blob', data: CanvasArg[], type? } // encoded image snapshot
+ * { rr_type, src } // HTMLImageElement etc.
+ * { rr_type, args: CanvasArg[] } // ImageBitmap etc.
+ * { rr_type: 'ImageData', args: [pixels, w, h] } // putImageData raw RGBA
+ * Images are neutralized synchronously (fail-safe) and the real downsampled/blurred
+ * result is swapped in by the deferred blur job on success.
+ */
+import { BLANK_IMAGE_DATA_URI, BLANK_PNG_BASE64, blurImageDataUri, isImageDataUri, pixelateRawRgba } from './blur'
+import { ScrubContext, isObject } from './config'
+import { scrubText } from './text'
+import { scrubUrl } from './url'
+
+// Canvas API calls whose leading string arguments are user-visible text.
+const TEXT_COMMANDS = new Set(['fillText', 'strokeText'])
+
+/** Scrub a CanvasMutation `data` object in place. Returns whether anything changed. */
+export function scrubCanvasMutation(ctx: ScrubContext, data: Record<string, unknown>): boolean {
+ let changed = false
+ if (Array.isArray(data.commands)) {
+ for (const cmd of data.commands) {
+ if (isObject(cmd)) {
+ changed = scrubCommand(ctx, cmd) || changed
+ }
+ }
+ } else if (typeof data.property === 'string') {
+ // Flattened single-command form: `data` itself is the command.
+ changed = scrubCommand(ctx, data) || changed
+ }
+ return changed
+}
+
+function scrubCommand(ctx: ScrubContext, cmd: Record<string, unknown>): boolean {
+ if (!Array.isArray(cmd.args)) {
+ return false
+ }
+ const args = cmd.args
+ let changed = false
+
+ // Text drawn onto the canvas: fillText/strokeText take the text as leading string args.
+ if (typeof cmd.property === 'string' && TEXT_COMMANDS.has(cmd.property)) {
+ for (let i = 0; i < args.length; i++) {
+ if (typeof args[i] === 'string') {
+ const result = scrubText(ctx, args[i])
+ if (result.changed) {
+ args[i] = result.value
+ changed = true
+ }
+ }
+ }
+ }
+
+ // Images/snapshots can appear anywhere in the (recursive) arg tree.
+ for (let i = 0; i < args.length; i++) {
+ changed = blurCanvasArg(ctx, args, i) || changed
+ }
+ return changed
+}
+
+/** Recursively neutralize+blur image data inside a canvas arg, mutating in place. */
+function blurCanvasArg(ctx: ScrubContext, container: any, key: string | number): boolean {
+ const value = container[key]
+
+ if (typeof value === 'string') {
+ if (isImageDataUri(value)) {
+ queueImageBlur(ctx, value, (blurred) => (container[key] = blurred))
+ container[key] = BLANK_IMAGE_DATA_URI
+ return true
+ }
+ return false
+ }
+
+ if (Array.isArray(value)) {
+ let changed = false
+ for (let i = 0; i < value.length; i++) {
+ changed = blurCanvasArg(ctx, value, i) || changed
+ }
+ return changed
+ }
+
+ if (!isObject(value)) {
+ return false
+ }
+
+ // Serialized image element: { rr_type, src }. Data-URI src is an embedded image; a
+ // remote src is a URL that may itself carry PII.
+ if (typeof value.src === 'string') {
+ if (isImageDataUri(value.src)) {
+ const original = value.src
+ value.src = BLANK_IMAGE_DATA_URI
+ queueImageBlur(ctx, original, (blurred) => (value.src = blurred))
+ return true
+ }
+ const result = scrubUrl(ctx, value.src)
+ if (result.changed) {
+ value.src = result.value
+ return true
+ }
+ return false
+ }
+
+ // Encoded image snapshot: { rr_type: 'Blob', type: 'image/...', data: [ {rr_type:'ArrayBuffer', base64} ] }.
+ if (value.rr_type === 'Blob' && typeof value.type === 'string' && value.type.startsWith('image/')) {
+ return blurBlobImage(ctx, value)
+ }
+
+ // Raw pixels: { rr_type: 'ImageData', args: [pixels, width, height] } (putImageData).
+ if (value.rr_type === 'ImageData') {
+ return blurImageData(ctx, value)
+ }
+
+ // Otherwise recurse into nested arg/data arrays (ImageBitmap → Blob, etc.).
+ let changed = false
+ if (Array.isArray(value.args)) {
+ for (let i = 0; i < value.args.length; i++) {
+ changed = blurCanvasArg(ctx, value.args, i) || changed
+ }
+ }
+ if (Array.isArray(value.data)) {
+ for (let i = 0; i < value.data.length; i++) {
+ changed = blurCanvasArg(ctx, value.data, i) || changed
+ }
+ }
+ return changed
+}
+
+/** Blur the encoded image bytes inside an image Blob, neutralizing them first (fail-safe). */
+function blurBlobImage(ctx: ScrubContext, blob: Record<string, unknown>): boolean {
+ const data = blob.data
+ if (!Array.isArray(data)) {
+ return false
+ }
+ const ab = data.find(
+ (d): d is Record<string, unknown> => isObject(d) && d.rr_type === 'ArrayBuffer' && typeof d.base64 === 'string'
+ )
+ if (!ab) {
+ return false
+ }
+ const mime = typeof blob.type === 'string' ? blob.type : 'image/png'
+ const original = `data:${mime};base64,${ab.base64 as string}`
+ // Fail-safe: drop the raw snapshot to a blank pixel now; the job swaps in the blur on success.
+ ab.base64 = BLANK_PNG_BASE64
+ blob.type = 'image/png'
+ queueImageBlur(ctx, original, (blurred) => {
+ const parts = splitDataUri(blurred)
+ if (parts) {
+ ab.base64 = parts.base64
+ blob.type = parts.mime
+ }
+ })
+ return true
+}
+
+function queueImageBlur(ctx: ScrubContext, dataUri: string, apply: (blurred: string) => void): void {
+ ctx.blurJobs?.push(async () => {
+ const blurred = await blurImageDataUri(dataUri)
+ if (blurred !== null) {
+ apply(blurred)
+ }
+ })
+}
+
+interface RawLoc {
+ ab: Record<string, unknown>
+ start: number
+ length: number
+}
+
+/** Locate the RGBA ArrayBuffer behind an ImageData's pixel descriptor (direct or typed-array-wrapped). */
+function findRawBuffer(desc: unknown): RawLoc | null {
+ if (!isObject(desc)) {
+ return null
+ }
+ if (desc.rr_type === 'ArrayBuffer' && typeof desc.base64 === 'string') {
+ return { ab: desc, start: 0, length: Buffer.from(desc.base64, 'base64').length }
+ }
+ // Typed-array wrapper: { rr_type: 'Uint8ClampedArray', args: [ {ArrayBuffer}, byteOffset?, length? ] }.
+ if (Array.isArray(desc.args) && isObject(desc.args[0]) && desc.args[0].rr_type === 'ArrayBuffer') {
+ const ab = desc.args[0] as Record<string, unknown>
+ if (typeof ab.base64 !== 'string') {
+ return null
+ }
+ const full = Buffer.from(ab.base64, 'base64').length
+ const start = typeof desc.args[1] === 'number' ? desc.args[1] : 0
+ const length = typeof desc.args[2] === 'number' ? desc.args[2] : full - start
+ return { ab, start, length }
+ }
+ return null
+}
+
+/** Pixelate raw ImageData pixels in place (fail-safe blanked now, downsampled-and-restored by the job). */
+function blurImageData(ctx: ScrubContext, imageData: Record<string, unknown>): boolean {
+ const args = imageData.args
+ if (Array.isArray(args)) {
+ const width = args[1]
+ const height = args[2]
+ const loc =
+ typeof width === 'number' && typeof height === 'number' && width > 0 && height > 0
+ ? findRawBuffer(args[0])
+ : null
+ if (loc && loc.length === width * height * 4) {
+ const full = Buffer.from(loc.ab.base64 as string, 'base64')
+ if (loc.start >= 0 && loc.start + loc.length <= full.length) {
+ const rgba = full.subarray(loc.start, loc.start + loc.length).toString('base64')
+ const blanked = Buffer.from(full)
+ blanked.fill(0, loc.start, loc.start + loc.length)
+ loc.ab.base64 = blanked.toString('base64')
+ ctx.blurJobs?.push(async () => {
+ const out = await pixelateRawRgba(rgba, width, height)
+ if (out === null) {
+ return
+ }
+ const outBuf = Buffer.from(out, 'base64')
+ if (outBuf.length !== loc.length) {
+ return
+ }
+ const merged = Buffer.from(blanked)
+ outBuf.copy(merged, loc.start)
+ loc.ab.base64 = merged.toString('base64')
+ })
+ return true
+ }
+ }
+ }
+ // Unexpected shape — guarantee no raw-pixel leak by blanking every nested ArrayBuffer.
+ return blankArrayBuffers(imageData)
+}
+
+/** Zero out every nested `{rr_type:'ArrayBuffer', base64}` (same byte length). Last-resort fail-safe. */
+function blankArrayBuffers(node: unknown): boolean {
+ if (Array.isArray(node)) {
+ let changed = false
+ for (const item of node) {
+ changed = blankArrayBuffers(item) || changed
+ }
+ return changed
+ }
+ if (!isObject(node)) {
+ return false
+ }
+ if (node.rr_type === 'ArrayBuffer' && typeof node.base64 === 'string') {
+ node.base64 = Buffer.alloc(Buffer.from(node.base64, 'base64').length).toString('base64')
+ return true
+ }
+ let changed = false
+ for (const key of Object.keys(node)) {
+ changed = blankArrayBuffers((node as Record<string, unknown>)[key]) || changed
+ }
+ return changed
+}
+
+function splitDataUri(uri: string): { mime: string; base64: string } | null {
+ const comma = uri.indexOf(',')
+ if (!uri.startsWith('data:') || comma === -1) {
+ return null
+ }
+ const mime = uri.slice('data:'.length, comma).split(';')[0] || 'image/png'
+ return { mime, base64: uri.slice(comma + 1) }
+}
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/anonymize/config.ts b/nodejs/src/ingestion/pipelines/sessionreplay/anonymize/config.ts
new file mode 100644
index 000000000000..daa26a9f4e33
--- /dev/null
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/anonymize/config.ts
@@ -0,0 +1,21 @@
+import { AllowLists } from './allow-lists'
+
+/** Replacement char for redacted (non-allow-listed) word characters. */
+export const REDACT_CHAR = '*'
+/** Replacement char for numeric tokens. */
+export const NUMBER_CHAR = '#'
+
+/** A deferred image-blur job: an async closure that blurs its image and writes the result back in place. */
+export type BlurJob = () => Promise<void>
+
+/** Per-scrub context: the active allow lists plus tunables read by the scrubbers. */
+export interface ScrubContext {
+ allow: AllowLists
+ /** Optional collector for deferred image-blur jobs (see {@link BlurJob}). */
+ blurJobs?: BlurJob[]
+}
+
+/** Shared non-null-object type guard used across the scrubbers. */
+export function isObject(v: unknown): v is Record<string, any> {
+ return typeof v === 'object' && v !== null
+}
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/anonymize/css.test.ts b/nodejs/src/ingestion/pipelines/sessionreplay/anonymize/css.test.ts
new file mode 100644
index 000000000000..323265378a80
--- /dev/null
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/anonymize/css.test.ts
@@ -0,0 +1,45 @@
+import { runBlurJobs } from './blur'
+import { scrubCssImages } from './css'
+import { defaultAllowLists } from './default-dict'
+
+// A small patterned PNG.
+const ONE_PX =
+ 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAIAAACQkWg2AAAACXBIWXMAAAPoAAAD6AG1e1JrAAAAJUlEQVQokWN4plEBRyInbOAIlzjDINRAjCJk8cGoYRAG60iMBwA8H08Qor0ygQAAAABJRU5ErkJggg=='
+
+function ctx(): { allow: ReturnType<typeof defaultAllowLists>; blurJobs: any[] } {
+ return { allow: defaultAllowLists(), blurJobs: [] }
+}
+
+describe('anonymize/css', () => {
+ it('blurs url(data:image) backgrounds, leaving sprite/remote/non-data url() untouched', () => {
+ const c = ctx()
+ const node: Record<string, unknown> = {
+ textContent: `.a{background:url(${ONE_PX})} .b{background:url(/assets/sprite.svg#icon)} .c{mask:url("https://cdn.example.com/m.png")}`,
+ }
+ expect(scrubCssImages(c, node, 'textContent')).toBe(true)
+ const css = node.textContent as string
+ expect(css).not.toContain(ONE_PX) // raw image gone synchronously
+ expect(css).toContain('/assets/sprite.svg#icon') // sprite fragment untouched
+ expect(css).toContain('https://cdn.example.com/m.png') // remote url untouched
+ expect(c.blurJobs).toHaveLength(1)
+ })
+
+ it('leaves CSS with no inline data-image unchanged', () => {
+ const c = ctx()
+ const node = { textContent: '.a{background:url(/img/x.png)}' }
+ expect(scrubCssImages(c, node, 'textContent')).toBe(false)
+ expect(node.textContent).toBe('.a{background:url(/img/x.png)}')
+ expect(c.blurJobs).toHaveLength(0)
+ })
+
+ it('resolves the placeholder to a blurred png after the deferred job runs', async () => {
+ const c = ctx()
+ const node: Record<string, unknown> = { textContent: `.a{background:url(${ONE_PX})}` }
+ scrubCssImages(c, node, 'textContent')
+ await runBlurJobs(c.blurJobs)
+ const css = node.textContent as string
+ expect(css).toMatch(/url\(data:image\/png;base64,[A-Za-z0-9+/=]+\)/)
+ expect(css).not.toContain('#a0') // unique placeholder fragment resolved
+ expect(css).not.toContain(ONE_PX) // not the original
+ })
+})
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/anonymize/css.ts b/nodejs/src/ingestion/pipelines/sessionreplay/anonymize/css.ts
new file mode 100644
index 000000000000..67032a558c15
--- /dev/null
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/anonymize/css.ts
@@ -0,0 +1,36 @@
+/** Blur inline `url(data:image/...;base64,...)` backgrounds in CSS */
+import { BLANK_IMAGE_DATA_URI, blurImageDataUri } from './blur'
+import { ScrubContext } from './config'
+
+const URL_DATA_IMAGE_RE = /url\(\s*(['"]?)(data:image\/[a-z0-9.+-]+;base64,[A-Za-z0-9+/=]+)\1\s*\)/gi
+
+/**
+ * Replace each inline data-image background in `container[key]` with a blank placeholder synchronously
+ * (fail-safe), and queue a deferred blur that splices the blurred image back in. Returns whether it acted.
+ */
+export function scrubCssImages(ctx: ScrubContext, container: Record<string, unknown>, key: string): boolean {
+ const css = container[key]
+ if (typeof css !== 'string') {
+ return false
+ }
+ let changed = false
+ let n = 0
+ const value = css.replace(URL_DATA_IMAGE_RE, (_match, quote: string, original: string) => {
+ changed = true
+ // A unique, valid stand-in (blank image + ignored fragment) so each deferred blur can splice
+ // its own image back independently; on blur failure it just stays the blank.
+ const placeholder = `${BLANK_IMAGE_DATA_URI}#a${n++}`
+ ctx.blurJobs?.push(async () => {
+ const blurred = await blurImageDataUri(original)
+ const cur = container[key]
+ if (typeof cur === 'string') {
+ container[key] = cur.replace(placeholder, () => blurred ?? BLANK_IMAGE_DATA_URI)
+ }
+ })
+ return `url(${quote}${placeholder}${quote})`
+ })
+ if (changed) {
+ container[key] = value
+ }
+ return changed
+}
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/anonymize/cv.test.ts b/nodejs/src/ingestion/pipelines/sessionreplay/anonymize/cv.test.ts
new file mode 100644
index 000000000000..0c3bd671c369
--- /dev/null
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/anonymize/cv.test.ts
@@ -0,0 +1,125 @@
+import { gunzipSync, gzipSync } from 'zlib'
+
+import { parseJSON } from '~/common/utils/json-parse'
+
+import { anonymizeEvent } from './anonymize-event'
+import { defaultAllowLists } from './default-dict'
+
+const compress = (v: unknown): string => gzipSync(Buffer.from(JSON.stringify(v))).toString('latin1')
+const decompress = (s: string): any => parseJSON(gunzipSync(Buffer.from(s, 'latin1')).toString('utf8'))
+
+describe('anonymize/cv', () => {
+ const ctx = { allow: defaultAllowLists() }
+
+ it('round-trips a cv-compressed FullSnapshot and scrubs the DOM text', () => {
+ const payload = {
+ node: {
+ type: 0,
+ id: 1,
+ childNodes: [
+ {
+ type: 2,
+ id: 2,
+ tagName: 'div',
+ attributes: {},
+ childNodes: [{ type: 3, id: 3, textContent: 'Hello SecretName' }],
+ },
+ ],
+ },
+ initialOffset: { top: 0, left: 0 },
+ }
+ const event: any = { type: 2, timestamp: 1, cv: 'v2', data: compress(payload) }
+
+ expect(anonymizeEvent(ctx, event)).toBe(true)
+ const out = decompress(event.data)
+ expect(out.node.childNodes[0].childNodes[0].textContent).toBe('Hello **********')
+ })
+
+ it('round-trips a cv-compressed Mutation and scrubs the text sub-field', () => {
+ const event: any = {
+ type: 3,
+ timestamp: 1,
+ cv: 'v2',
+ data: {
+ source: 0,
+ texts: compress([{ id: 7, value: 'Hello SecretName' }]),
+ attributes: compress([]),
+ removes: compress([]),
+ adds: compress([]),
+ },
+ }
+
+ expect(anonymizeEvent(ctx, event)).toBe(true)
+ const outTexts = decompress(event.data.texts)
+ expect(outTexts[0].value).toBe('Hello **********')
+ })
+
+ it('scrubs a cv Mutation whose sub-fields are already decompressed arrays', () => {
+ // Some producers/exporters emit cv events with plain-array sub-fields.
+ // These must still be scrubbed (in place), not skipped as "absent".
+ const event: any = {
+ type: 3,
+ timestamp: 1,
+ cv: '2024-10',
+ data: {
+ source: 0,
+ texts: [{ id: 7, value: 'Hello SecretName' }],
+ attributes: [],
+ removes: [],
+ adds: [],
+ },
+ }
+ expect(anonymizeEvent(ctx, event)).toBe(true)
+ // Stays an array (not re-compressed to a string) and is scrubbed in place.
+ expect(Array.isArray(event.data.texts)).toBe(true)
+ expect(event.data.texts[0].value).toBe('Hello **********')
+ })
+
+ it('scrubs a cv FullSnapshot whose data is already a decompressed object', () => {
+ const event: any = {
+ type: 2,
+ timestamp: 1,
+ cv: '2024-10',
+ data: {
+ node: {
+ type: 0,
+ id: 1,
+ childNodes: [{ type: 3, id: 2, textContent: 'Hello SecretName' }],
+ },
+ initialOffset: { top: 0, left: 0 },
+ },
+ }
+ expect(anonymizeEvent(ctx, event)).toBe(true)
+ expect(event.data.node.childNodes[0].textContent).toBe('Hello **********')
+ })
+
+ it('throws on a cv FullSnapshot whose data string is not valid latin-1', () => {
+ // A codepoint > 0xFF cannot be a latin-1 gzip byte; decoding must throw
+ // so the caller fails closed rather than writing the raw blob.
+ const event: any = { type: 2, timestamp: 1, cv: '2024-10', data: 'not-Ā-gzip' }
+ expect(() => anonymizeEvent(ctx, event)).toThrow()
+ })
+
+ it('does not gunzip an absent/empty sub-field', () => {
+ // texts present, attributes/removes/adds absent — must still scrub texts.
+ const event: any = {
+ type: 3,
+ timestamp: 1,
+ cv: 'v2',
+ data: { source: 0, texts: compress([{ id: 1, value: 'Hello SecretName' }]) },
+ }
+ expect(anonymizeEvent(ctx, event)).toBe(true)
+ expect(decompress(event.data.texts)[0].value).toBe('Hello **********')
+ })
+
+ it('fails closed when a compressed sub-field does not decode to an array', () => {
+ // A decodable-but-non-array sub-field is malformed; must throw (→ message dropped) rather than zero it.
+ const event: any = {
+ type: 3,
+ timestamp: 1,
+ cv: 'v2',
+ data: { source: 0, texts: compress({ not: 'an array' }) },
+ }
+ expect(() => anonymizeEvent(ctx, event)).toThrow()
+ })
+})
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/anonymize/cv.ts b/nodejs/src/ingestion/pipelines/sessionreplay/anonymize/cv.ts
new file mode 100644
index 000000000000..c7d6dffd4f6e
--- /dev/null
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/anonymize/cv.ts
@@ -0,0 +1,102 @@
+/** Decode/scrub/re-encode per-event `cv` compression (gzip stored as latin-1 codepoints). */
+import { gunzipSync, gzipSync } from 'zlib'
+
+import { parseJSON } from '~/common/utils/json-parse'
+
+import { ScrubContext, isObject } from './config'
+import { scrubFullSnapshot, scrubMutation } from './dom'
+
+function latin1ToBytes(s: string): Buffer {
+ const buf = Buffer.allocUnsafe(s.length)
+ for (let i = 0; i < s.length; i++) {
+ const cp = s.charCodeAt(i)
+ if (cp > 0xff) {
+ throw new Error(`codepoint U+${cp.toString(16)} > 0xFF in latin-1 gzip stream`)
+ }
+ buf[i] = cp
+ }
+ return buf
+}
+
+function decompressString(s: string): unknown {
+ const json = gunzipSync(latin1ToBytes(s)).toString('utf8')
+ return parseJSON(json)
+}
+
+function compressToString(value: unknown): string {
+ // latin1 is the inverse of latin1ToBytes; JSON.stringify escapes it on serialization.
+ return gzipSync(Buffer.from(JSON.stringify(value), 'utf8')).toString('latin1')
+}
+
+/** Scrub a `cv`-compressed FullSnapshot event in place. Returns whether it changed. */
+export function scrubCompressedFullSnapshot(ctx: ScrubContext, event: Record<string, unknown>): boolean {
+ const data = event.data
+ if (typeof data !== 'string') {
+ // Not actually whole-blob compressed — scrub as a plain object.
+ return scrubFullSnapshot(ctx, data)
+ }
+ const payload = decompressString(data)
+ if (!scrubFullSnapshot(ctx, payload)) {
+ return false
+ }
+ event.data = compressToString(payload)
+ return true
+}
+
+/** Scrub a `cv`-compressed Mutation event in place. Returns whether it changed. */
+export function scrubCompressedMutation(ctx: ScrubContext, event: Record<string, unknown>): boolean {
+ const data = event.data
+ if (!isObject(data)) {
+ return false
+ }
+
+ // Sub-fields are gzipped strings on the wire but may arrive as plain arrays; handle both.
+ const texts = readSubfield(data.texts)
+ const attributes = readSubfield(data.attributes)
+ const adds = readSubfield(data.adds)
+
+ const synthetic: Record<string, unknown> = {
+ source: data.source,
+ texts: texts.array,
+ attributes: attributes.array,
+ adds: adds.array,
+ // `removes` is ids-only and untouched — left as-is.
+ }
+
+ if (!scrubMutation(ctx, synthetic)) {
+ return false
+ }
+
+ // Array sub-fields were mutated in place; only re-encode the ones that arrived gzipped.
+ if (texts.wasCompressed) {
+ data.texts = compressToString(synthetic.texts)
+ }
+ if (attributes.wasCompressed) {
+ data.attributes = compressToString(synthetic.attributes)
+ }
+ if (adds.wasCompressed) {
+ data.adds = compressToString(synthetic.adds)
+ }
+ return true
+}
+
+function readSubfield(field: unknown): { array: unknown[]; wasCompressed: boolean } {
+ if (field === undefined || field === null) {
+ return { array: [], wasCompressed: false }
+ }
+ if (typeof field === 'string') {
+ if (field.length === 0) {
+ return { array: [], wasCompressed: false }
+ }
+ const payload = decompressString(field)
+ if (!Array.isArray(payload)) {
+ // Fail closed: a decodable-but-non-array sub-field is malformed; dropping beats shipping a zeroed block.
+ throw new Error('cv mutation sub-field did not decode to an array')
+ }
+ return { array: payload, wasCompressed: true }
+ }
+ if (Array.isArray(field)) {
+ return { array: field, wasCompressed: false }
+ }
+ throw new Error('cv mutation sub-field is neither a gzipped string nor an array')
+}
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/anonymize/default-dict.ts b/nodejs/src/ingestion/pipelines/sessionreplay/anonymize/default-dict.ts
new file mode 100644
index 000000000000..88fde245e72e
--- /dev/null
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/anonymize/default-dict.ts
@@ -0,0 +1,2015 @@
+/** Default allow lists (English stopwords/UI vocabulary + safe URL segments), the fail-safe fallback. */
+import { AllowLists } from './allow-lists'
+
+export const DEFAULT_TEXT_WORDS: string[] = [
+ // articles, prepositions, conjunctions, pronouns
+ 'a',
+ 'an',
+ 'the',
+ 'and',
+ 'or',
+ 'but',
+ 'nor',
+ 'so',
+ 'yet',
+ 'as',
+ 'if',
+ 'then',
+ 'than',
+ 'of',
+ 'to',
+ 'in',
+ 'on',
+ 'at',
+ 'by',
+ 'for',
+ 'with',
+ 'from',
+ 'into',
+ 'onto',
+ 'out',
+ 'up',
+ 'down',
+ 'off',
+ 'over',
+ 'under',
+ 'between',
+ 'through',
+ 'across',
+ 'about',
+ 'after',
+ 'before',
+ 'during',
+ 'without',
+ 'within',
+ 'while',
+ 'until',
+ 'since',
+ 'per',
+ 'via',
+ 'vs',
+ 'versus',
+ 'etc',
+ 'i',
+ 'me',
+ 'my',
+ 'mine',
+ 'you',
+ 'your',
+ 'yours',
+ 'he',
+ 'him',
+ 'his',
+ 'she',
+ 'her',
+ 'hers',
+ 'it',
+ 'its',
+ 'we',
+ 'us',
+ 'our',
+ 'ours',
+ 'they',
+ 'them',
+ 'their',
+ 'theirs',
+ 'this',
+ 'that',
+ 'these',
+ 'those',
+ 'who',
+ 'whom',
+ 'whose',
+ 'which',
+ 'what',
+ 'where',
+ 'when',
+ 'why',
+ 'how',
+ 'any',
+ 'all',
+ 'some',
+ 'no',
+ 'none',
+ 'every',
+ 'each',
+ 'both',
+ 'either',
+ 'neither',
+ 'more',
+ 'less',
+ 'most',
+ 'least',
+ 'few',
+ 'many',
+ 'much',
+ 'such',
+ 'other',
+ 'another',
+ 'same',
+ 'own',
+ 'self',
+ // to-be / aux verbs
+ 'am',
+ 'is',
+ 'are',
+ 'was',
+ 'were',
+ 'be',
+ 'been',
+ 'being',
+ 'do',
+ 'does',
+ 'did',
+ 'done',
+ 'doing',
+ 'have',
+ 'has',
+ 'had',
+ 'having',
+ 'will',
+ 'would',
+ 'shall',
+ 'should',
+ 'can',
+ 'could',
+ 'may',
+ 'might',
+ 'must',
+ 'ought',
+ 'need',
+ 'not',
+ 'yes',
+ 'no',
+ 'ok',
+ 'okay',
+ // common everyday verbs (UI copy)
+ 'click',
+ 'tap',
+ 'press',
+ 'select',
+ 'choose',
+ 'pick',
+ 'submit',
+ 'save',
+ 'saved',
+ 'saving',
+ 'cancel',
+ 'cancelled',
+ 'discard',
+ 'dismiss',
+ 'close',
+ 'closed',
+ 'open',
+ 'opened',
+ 'opening',
+ 'edit',
+ 'edited',
+ 'editing',
+ 'modify',
+ 'change',
+ 'changed',
+ 'update',
+ 'updated',
+ 'updating',
+ 'create',
+ 'created',
+ 'creating',
+ 'add',
+ 'added',
+ 'adding',
+ 'remove',
+ 'removed',
+ 'removing',
+ 'delete',
+ 'deleted',
+ 'deleting',
+ 'duplicate',
+ 'duplicated',
+ 'copy',
+ 'copied',
+ 'paste',
+ 'cut',
+ 'clone',
+ 'fork',
+ 'drag',
+ 'drop',
+ 'move',
+ 'moved',
+ 'resize',
+ 'rename',
+ 'renamed',
+ 'search',
+ 'find',
+ 'finding',
+ 'filter',
+ 'filtered',
+ 'sort',
+ 'sorted',
+ 'group',
+ 'grouped',
+ 'ungroup',
+ 'refresh',
+ 'reload',
+ 'retry',
+ 'reset',
+ 'restore',
+ 'revert',
+ 'rollback',
+ 'undo',
+ 'redo',
+ 'expand',
+ 'collapse',
+ 'minimize',
+ 'maximize',
+ 'toggle',
+ 'show',
+ 'hide',
+ 'view',
+ 'preview',
+ 'browse',
+ 'explore',
+ 'navigate',
+ 'go',
+ 'goto',
+ 'load',
+ 'loading',
+ 'loaded',
+ 'fetch',
+ 'fetching',
+ 'fetched',
+ 'import',
+ 'imported',
+ 'export',
+ 'exported',
+ 'download',
+ 'downloaded',
+ 'downloading',
+ 'upload',
+ 'uploaded',
+ 'uploading',
+ 'attach',
+ 'attached',
+ 'detach',
+ 'send',
+ 'sent',
+ 'sending',
+ 'receive',
+ 'received',
+ 'reply',
+ 'forward',
+ 'share',
+ 'shared',
+ 'sharing',
+ 'invite',
+ 'invited',
+ 'join',
+ 'joined',
+ 'leave',
+ 'left',
+ 'approve',
+ 'approved',
+ 'reject',
+ 'rejected',
+ 'accept',
+ 'accepted',
+ 'decline',
+ 'declined',
+ 'confirm',
+ 'confirmed',
+ 'verify',
+ 'verified',
+ 'validate',
+ 'validated',
+ 'publish',
+ 'published',
+ 'draft',
+ 'drafts',
+ 'archive',
+ 'archived',
+ 'unarchive',
+ 'restore',
+ 'delete',
+ 'trash',
+ 'pin',
+ 'pinned',
+ 'unpin',
+ 'star',
+ 'starred',
+ 'unstar',
+ 'favorite',
+ 'favorited',
+ 'like',
+ 'liked',
+ 'unlike',
+ 'follow',
+ 'followed',
+ 'unfollow',
+ 'subscribe',
+ 'subscribed',
+ 'unsubscribe',
+ 'mute',
+ 'unmute',
+ 'block',
+ 'blocked',
+ 'unblock',
+ 'report',
+ 'reported',
+ 'flag',
+ 'flagged',
+ 'comment',
+ 'reply',
+ 'react',
+ 'mention',
+ 'tag',
+ 'tagged',
+ 'untag',
+ 'assign',
+ 'assigned',
+ 'unassign',
+ 'reassign',
+ 'start',
+ 'started',
+ 'starting',
+ 'stop',
+ 'stopped',
+ 'stopping',
+ 'pause',
+ 'paused',
+ 'resume',
+ 'resumed',
+ 'restart',
+ 'restarting',
+ 'begin',
+ 'end',
+ 'finish',
+ 'finished',
+ 'complete',
+ 'completed',
+ 'continue',
+ 'skip',
+ 'skipped',
+ 'exit',
+ 'quit',
+ 'install',
+ 'installed',
+ 'installing',
+ 'uninstall',
+ 'upgrade',
+ 'upgraded',
+ 'downgrade',
+ 'configure',
+ 'configured',
+ 'setup',
+ 'set',
+ 'build',
+ 'built',
+ 'compile',
+ 'compiled',
+ 'test',
+ 'tested',
+ 'testing',
+ 'deploy',
+ 'deployed',
+ 'deploying',
+ 'release',
+ 'released',
+ 'ship',
+ 'shipped',
+ 'rollout',
+ 'rollback',
+ 'publish',
+ 'promote',
+ 'promoted',
+ 'run',
+ 'running',
+ 'execute',
+ 'executed',
+ 'process',
+ 'processed',
+ 'processing',
+ 'queue',
+ 'queued',
+ 'schedule',
+ 'scheduled',
+ 'trigger',
+ 'triggered',
+ 'connect',
+ 'connected',
+ 'disconnect',
+ 'link',
+ 'linked',
+ 'unlink',
+ 'sync',
+ 'synced',
+ 'syncing',
+ 'buy',
+ 'bought',
+ 'purchase',
+ 'purchased',
+ 'order',
+ 'ordered',
+ 'checkout',
+ 'pay',
+ 'paid',
+ 'paying',
+ 'refund',
+ 'refunded',
+ 'charge',
+ 'charged',
+ 'renew',
+ 'renewed',
+ 'expire',
+ 'expired',
+ 'trial',
+ 'free',
+ 'login',
+ 'log',
+ 'logged',
+ 'logout',
+ 'signin',
+ 'signout',
+ 'signup',
+ 'register',
+ 'registered',
+ 'authenticate',
+ 'authorize',
+ 'authorized',
+ 'deauthorize',
+ 'unauthorized',
+ 'remember',
+ 'forgot',
+ 'reset',
+ 'recover',
+ 'enable',
+ 'enabled',
+ 'disable',
+ 'disabled',
+ 'activate',
+ 'activated',
+ 'deactivate',
+ 'lock',
+ 'locked',
+ 'unlock',
+ 'unlocked',
+ 'grant',
+ 'revoke',
+ 'permit',
+ 'deny',
+ 'allow',
+ 'blocklist',
+ 'allowlist',
+ // common nouns: navigation / structure
+ 'home',
+ 'homepage',
+ 'landing',
+ 'main',
+ 'page',
+ 'pages',
+ 'section',
+ 'sections',
+ 'panel',
+ 'panels',
+ 'tab',
+ 'tabs',
+ 'view',
+ 'views',
+ 'screen',
+ 'window',
+ 'modal',
+ 'dialog',
+ 'popup',
+ 'popover',
+ 'tooltip',
+ 'drawer',
+ 'sidebar',
+ 'header',
+ 'footer',
+ 'nav',
+ 'navigation',
+ 'menu',
+ 'menus',
+ 'breadcrumb',
+ 'breadcrumbs',
+ 'toolbar',
+ 'toolbox',
+ 'ribbon',
+ 'card',
+ 'cards',
+ 'tile',
+ 'tiles',
+ 'grid',
+ 'list',
+ 'lists',
+ 'tree',
+ 'table',
+ 'tables',
+ 'row',
+ 'rows',
+ 'column',
+ 'columns',
+ 'cell',
+ 'cells',
+ 'container',
+ 'wrapper',
+ 'block',
+ 'blocks',
+ 'section',
+ 'group',
+ 'stack',
+ 'layer',
+ 'layers',
+ 'dashboard',
+ 'dashboards',
+ 'workspace',
+ 'workspaces',
+ 'project',
+ 'projects',
+ 'team',
+ 'teams',
+ 'organization',
+ 'organizations',
+ 'org',
+ 'orgs',
+ 'company',
+ 'companies',
+ 'department',
+ 'settings',
+ 'preferences',
+ 'config',
+ 'configuration',
+ 'options',
+ 'profile',
+ 'profiles',
+ 'account',
+ 'accounts',
+ 'billing',
+ 'plan',
+ 'plans',
+ 'subscription',
+ 'subscriptions',
+ 'trial',
+ 'free',
+ 'pro',
+ 'premium',
+ 'enterprise',
+ 'business',
+ 'starter',
+ 'growth',
+ // common nouns: forms / fields
+ 'form',
+ 'forms',
+ 'field',
+ 'fields',
+ 'input',
+ 'inputs',
+ 'value',
+ 'values',
+ 'label',
+ 'labels',
+ 'placeholder',
+ 'name',
+ 'first',
+ 'last',
+ 'middle',
+ 'title',
+ 'prefix',
+ 'suffix',
+ 'username',
+ 'handle',
+ 'alias',
+ 'nickname',
+ 'email',
+ 'phone',
+ 'mobile',
+ 'fax',
+ 'address',
+ 'street',
+ 'city',
+ 'state',
+ 'region',
+ 'province',
+ 'zip',
+ 'postal',
+ 'code',
+ 'country',
+ 'language',
+ 'locale',
+ 'timezone',
+ 'password',
+ 'passcode',
+ 'pin',
+ 'otp',
+ 'code',
+ 'token',
+ 'secret',
+ 'key',
+ 'api',
+ 'checkbox',
+ 'radio',
+ 'switch',
+ 'slider',
+ 'select',
+ 'dropdown',
+ 'combobox',
+ 'datepicker',
+ 'timepicker',
+ // common nouns: identity / auth
+ 'user',
+ 'users',
+ 'member',
+ 'members',
+ 'guest',
+ 'guests',
+ 'owner',
+ 'admin',
+ 'administrator',
+ 'moderator',
+ 'developer',
+ 'designer',
+ 'engineer',
+ 'manager',
+ 'lead',
+ 'analyst',
+ 'viewer',
+ 'editor',
+ 'contributor',
+ 'collaborator',
+ 'client',
+ 'customer',
+ 'vendor',
+ 'supplier',
+ 'partner',
+ 'agent',
+ 'operator',
+ 'role',
+ 'roles',
+ 'permission',
+ 'permissions',
+ 'scope',
+ 'scopes',
+ 'policy',
+ 'policies',
+ 'access',
+ 'session',
+ 'sessions',
+ 'device',
+ 'devices',
+ // common nouns: data / analytics
+ 'data',
+ 'row',
+ 'record',
+ 'records',
+ 'entry',
+ 'entries',
+ 'item',
+ 'items',
+ 'object',
+ 'objects',
+ 'entity',
+ 'entities',
+ 'model',
+ 'models',
+ 'schema',
+ 'table',
+ 'tables',
+ 'view',
+ 'views',
+ 'query',
+ 'queries',
+ 'report',
+ 'reports',
+ 'chart',
+ 'charts',
+ 'graph',
+ 'graphs',
+ 'plot',
+ 'plots',
+ 'metric',
+ 'metrics',
+ 'kpi',
+ 'stat',
+ 'stats',
+ 'statistics',
+ 'count',
+ 'counts',
+ 'total',
+ 'totals',
+ 'average',
+ 'avg',
+ 'median',
+ 'mean',
+ 'min',
+ 'max',
+ 'sum',
+ 'diff',
+ 'delta',
+ 'percent',
+ 'percentage',
+ 'ratio',
+ 'rate',
+ 'rates',
+ 'trend',
+ 'trends',
+ 'growth',
+ 'decline',
+ 'increase',
+ 'decrease',
+ 'event',
+ 'events',
+ 'action',
+ 'actions',
+ 'interaction',
+ 'interactions',
+ 'session',
+ 'sessions',
+ 'visit',
+ 'visits',
+ 'view',
+ 'pageview',
+ 'click',
+ 'clicks',
+ 'impression',
+ 'impressions',
+ 'conversion',
+ 'conversions',
+ 'funnel',
+ 'funnels',
+ 'retention',
+ 'cohort',
+ 'cohorts',
+ 'experiment',
+ 'experiments',
+ 'variant',
+ 'variants',
+ 'test',
+ 'tests',
+ 'ab',
+ 'split',
+ 'flag',
+ 'flags',
+ 'feature',
+ 'features',
+ 'release',
+ 'releases',
+ 'insight',
+ 'insights',
+ 'trend',
+ 'trends',
+ 'anomaly',
+ 'anomalies',
+ 'alert',
+ 'alerts',
+ 'notification',
+ 'notifications',
+ 'log',
+ 'logs',
+ 'trace',
+ 'traces',
+ 'span',
+ 'spans',
+ 'error',
+ 'errors',
+ 'warning',
+ 'warnings',
+ 'info',
+ 'debug',
+ 'stack',
+ 'stacktrace',
+ // common nouns: dev / engineering
+ 'code',
+ 'snippet',
+ 'snippets',
+ 'file',
+ 'files',
+ 'folder',
+ 'folders',
+ 'directory',
+ 'directories',
+ 'path',
+ 'paths',
+ 'branch',
+ 'branches',
+ 'commit',
+ 'commits',
+ 'merge',
+ 'merges',
+ 'pull',
+ 'request',
+ 'requests',
+ 'pr',
+ 'prs',
+ 'issue',
+ 'issues',
+ 'ticket',
+ 'tickets',
+ 'bug',
+ 'bugs',
+ 'feature',
+ 'task',
+ 'tasks',
+ 'story',
+ 'stories',
+ 'epic',
+ 'milestone',
+ 'sprint',
+ 'backlog',
+ 'board',
+ 'boards',
+ 'kanban',
+ 'agile',
+ 'scrum',
+ 'build',
+ 'builds',
+ 'pipeline',
+ 'pipelines',
+ 'workflow',
+ 'workflows',
+ 'job',
+ 'jobs',
+ 'step',
+ 'steps',
+ 'stage',
+ 'stages',
+ 'deploy',
+ 'deploys',
+ 'release',
+ 'version',
+ 'versions',
+ 'tag',
+ 'tags',
+ 'repo',
+ 'repos',
+ 'repository',
+ 'repositories',
+ 'fork',
+ 'forks',
+ 'clone',
+ 'clones',
+ 'function',
+ 'functions',
+ 'method',
+ 'methods',
+ 'class',
+ 'classes',
+ 'module',
+ 'modules',
+ 'package',
+ 'packages',
+ 'library',
+ 'libraries',
+ 'framework',
+ 'frameworks',
+ 'dependency',
+ 'dependencies',
+ 'import',
+ 'imports',
+ 'export',
+ 'exports',
+ 'type',
+ 'types',
+ 'interface',
+ 'interfaces',
+ 'enum',
+ 'enums',
+ 'variable',
+ 'variables',
+ 'constant',
+ 'constants',
+ 'parameter',
+ 'parameters',
+ 'argument',
+ 'arguments',
+ 'return',
+ 'returns',
+ 'string',
+ 'number',
+ 'boolean',
+ 'array',
+ 'object',
+ 'null',
+ 'true',
+ 'false',
+ 'undefined',
+ 'void',
+ 'request',
+ 'requests',
+ 'response',
+ 'responses',
+ 'endpoint',
+ 'endpoints',
+ 'route',
+ 'routes',
+ 'url',
+ 'uri',
+ 'host',
+ 'domain',
+ 'subdomain',
+ 'port',
+ 'header',
+ 'headers',
+ 'body',
+ 'payload',
+ 'params',
+ 'query',
+ 'method',
+ 'get',
+ 'post',
+ 'put',
+ 'patch',
+ 'delete',
+ 'head',
+ 'options',
+ 'status',
+ 'code',
+ 'ok',
+ 'created',
+ 'accepted',
+ 'moved',
+ 'found',
+ 'redirect',
+ 'bad',
+ 'request',
+ 'unauthorized',
+ 'forbidden',
+ 'notfound',
+ 'conflict',
+ 'unprocessable',
+ 'internal',
+ 'server',
+ 'gateway',
+ 'timeout',
+ 'service',
+ 'services',
+ 'server',
+ 'servers',
+ 'client',
+ 'clients',
+ 'database',
+ 'databases',
+ 'db',
+ 'schema',
+ 'migration',
+ 'migrations',
+ 'index',
+ 'indexes',
+ 'cache',
+ 'caches',
+ 'queue',
+ 'queues',
+ 'stream',
+ 'streams',
+ 'topic',
+ 'topics',
+ 'channel',
+ 'channels',
+ 'container',
+ 'containers',
+ 'pod',
+ 'pods',
+ 'node',
+ 'nodes',
+ 'cluster',
+ 'clusters',
+ 'namespace',
+ 'namespaces',
+ 'deployment',
+ 'deployments',
+ 'replica',
+ 'replicas',
+ 'auth',
+ 'oauth',
+ 'sso',
+ 'saml',
+ 'ldap',
+ 'jwt',
+ 'bearer',
+ 'basic',
+ 'api',
+ 'sdk',
+ 'cli',
+ 'gui',
+ 'ui',
+ 'ux',
+ 'rest',
+ 'graphql',
+ 'grpc',
+ 'rpc',
+ 'soap',
+ 'websocket',
+ 'http',
+ 'https',
+ 'tcp',
+ 'udp',
+ 'ssl',
+ 'tls',
+ // statuses & feedback
+ 'active',
+ 'inactive',
+ 'enabled',
+ 'disabled',
+ 'online',
+ 'offline',
+ 'available',
+ 'unavailable',
+ 'open',
+ 'closed',
+ 'running',
+ 'stopped',
+ 'paused',
+ 'pending',
+ 'queued',
+ 'scheduled',
+ 'processing',
+ 'completed',
+ 'complete',
+ 'incomplete',
+ 'succeeded',
+ 'success',
+ 'successful',
+ 'failed',
+ 'failure',
+ 'failing',
+ 'error',
+ 'errored',
+ 'warning',
+ 'warnings',
+ 'info',
+ 'notice',
+ 'ready',
+ 'not',
+ 'ready',
+ 'expired',
+ 'active',
+ 'inactive',
+ 'draft',
+ 'published',
+ 'unpublished',
+ 'approved',
+ 'rejected',
+ 'pending',
+ 'review',
+ 'in',
+ 'progress',
+ 'blocked',
+ 'unblocked',
+ 'verified',
+ 'unverified',
+ 'locked',
+ 'unlocked',
+ // billing / payments
+ 'billing',
+ 'invoice',
+ 'invoices',
+ 'receipt',
+ 'receipts',
+ 'payment',
+ 'payments',
+ 'card',
+ 'cards',
+ 'credit',
+ 'debit',
+ 'bank',
+ 'transfer',
+ 'wire',
+ 'ach',
+ 'paypal',
+ 'stripe',
+ 'currency',
+ 'currencies',
+ 'subscription',
+ 'subscriptions',
+ 'plan',
+ 'plans',
+ 'tier',
+ 'tiers',
+ 'usage',
+ 'limit',
+ 'limits',
+ 'quota',
+ 'quotas',
+ 'balance',
+ 'credit',
+ 'credits',
+ 'discount',
+ 'discounts',
+ 'coupon',
+ 'coupons',
+ 'promo',
+ 'tax',
+ 'taxes',
+ 'vat',
+ 'fee',
+ 'fees',
+ 'refund',
+ 'refunds',
+ 'charge',
+ 'charges',
+ 'transaction',
+ 'transactions',
+ 'monthly',
+ 'yearly',
+ 'annual',
+ 'annually',
+ 'weekly',
+ 'daily',
+ 'hourly',
+ // time / date words
+ 'today',
+ 'yesterday',
+ 'tomorrow',
+ 'now',
+ 'soon',
+ 'later',
+ 'ago',
+ 'second',
+ 'seconds',
+ 'sec',
+ 'minute',
+ 'minutes',
+ 'min',
+ 'hour',
+ 'hours',
+ 'hr',
+ 'day',
+ 'days',
+ 'week',
+ 'weeks',
+ 'month',
+ 'months',
+ 'quarter',
+ 'quarters',
+ 'year',
+ 'years',
+ 'monday',
+ 'tuesday',
+ 'wednesday',
+ 'thursday',
+ 'friday',
+ 'saturday',
+ 'sunday',
+ 'mon',
+ 'tue',
+ 'wed',
+ 'thu',
+ 'fri',
+ 'sat',
+ 'sun',
+ 'january',
+ 'february',
+ 'march',
+ 'april',
+ 'may',
+ 'june',
+ 'july',
+ 'august',
+ 'september',
+ 'october',
+ 'november',
+ 'december',
+ 'jan',
+ 'feb',
+ 'mar',
+ 'apr',
+ 'jun',
+ 'jul',
+ 'aug',
+ 'sep',
+ 'sept',
+ 'oct',
+ 'nov',
+ 'dec',
+ 'am',
+ 'pm',
+ 'gmt',
+ 'utc',
+ 'morning',
+ 'afternoon',
+ 'evening',
+ 'night',
+ // adjectives / quantifiers
+ 'new',
+ 'old',
+ 'recent',
+ 'latest',
+ 'earliest',
+ 'first',
+ 'last',
+ 'next',
+ 'previous',
+ 'prior',
+ 'current',
+ 'upcoming',
+ 'past',
+ 'future',
+ 'default',
+ 'custom',
+ 'auto',
+ 'manual',
+ 'automatic',
+ 'auto',
+ 'primary',
+ 'secondary',
+ 'tertiary',
+ 'main',
+ 'alternate',
+ 'alt',
+ 'small',
+ 'medium',
+ 'large',
+ 'xs',
+ 'sm',
+ 'md',
+ 'lg',
+ 'xl',
+ 'xxl',
+ 'short',
+ 'long',
+ 'wide',
+ 'narrow',
+ 'thin',
+ 'thick',
+ 'tall',
+ 'high',
+ 'low',
+ 'fast',
+ 'slow',
+ 'quick',
+ 'easy',
+ 'hard',
+ 'simple',
+ 'advanced',
+ 'basic',
+ 'free',
+ 'paid',
+ 'open',
+ 'closed',
+ 'private',
+ 'public',
+ 'shared',
+ 'personal',
+ 'global',
+ 'local',
+ 'remote',
+ 'internal',
+ 'external',
+ 'production',
+ 'prod',
+ 'staging',
+ 'stage',
+ 'development',
+ 'dev',
+ 'test',
+ 'qa',
+ 'preview',
+ 'demo',
+ 'sandbox',
+ 'live',
+ 'draft',
+ 'beta',
+ 'alpha',
+ 'stable',
+ 'experimental',
+ 'good',
+ 'bad',
+ 'ok',
+ 'great',
+ 'best',
+ 'worst',
+ 'better',
+ 'worse',
+ 'always',
+ 'never',
+ 'sometimes',
+ 'often',
+ 'rarely',
+ 'usually',
+ // generic words / hellos / placeholders
+ 'hello',
+ 'hi',
+ 'welcome',
+ 'thanks',
+ 'thank',
+ 'you',
+ 'please',
+ 'sorry',
+ 'oops',
+ 'wow',
+ 'yes',
+ 'no',
+ 'maybe',
+ 'done',
+ 'ready',
+ 'loading',
+ 'wait',
+ 'waiting',
+ 'almost',
+ 'there',
+ 'untitled',
+ 'unnamed',
+ 'anonymous',
+ 'guest',
+ // English contractions — negative auxiliaries
+ "don't",
+ "doesn't",
+ "didn't",
+ "isn't",
+ "aren't",
+ "wasn't",
+ "weren't",
+ "haven't",
+ "hasn't",
+ "hadn't",
+ "can't",
+ 'cannot',
+ "couldn't",
+ "won't",
+ "wouldn't",
+ "shouldn't",
+ "shan't",
+ "mustn't",
+ "mightn't",
+ "needn't",
+ "oughtn't",
+ // be/have/will/would copulas
+ "i'm",
+ "i've",
+ "i'll",
+ "i'd",
+ "you're",
+ "you've",
+ "you'll",
+ "you'd",
+ "we're",
+ "we've",
+ "we'll",
+ "we'd",
+ "they're",
+ "they've",
+ "they'll",
+ "they'd",
+ "he's",
+ "he'll",
+ "he'd",
+ "she's",
+ "she'll",
+ "she'd",
+ "it's",
+ "it'll",
+ "it'd",
+ // interrogative / demonstrative contractions
+ "that's",
+ "there's",
+ "here's",
+ "what's",
+ "who's",
+ "where's",
+ "when's",
+ "how's",
+ "why's",
+ "let's",
+ "ain't",
+ // would've/could've/should've family
+ "would've",
+ "could've",
+ "should've",
+ "must've",
+ "might've",
+ // clipped / colloquial
+ "y'all",
+ "ya'll",
+ "ma'am",
+ "o'clock",
+ "'cause",
+ "'em",
+ "'tis",
+ // misc kept-with-apostrophe
+ "rock'n'roll",
+ // common locale-/region-y words
+ 'english',
+ 'spanish',
+ 'french',
+ 'german',
+ 'japanese',
+ 'chinese',
+ 'korean',
+ 'portuguese',
+ 'italian',
+ 'dutch',
+ 'russian',
+ 'arabic',
+ 'global',
+ 'world',
+ 'international',
+ 'usa',
+ 'us',
+ 'uk',
+ 'eu',
+ 'europe',
+ 'asia',
+ 'africa',
+ 'americas',
+ // analytics / posthog vocabulary
+ 'posthog',
+ 'analytics',
+ 'tracking',
+ 'telemetry',
+ 'events',
+ 'properties',
+ 'persons',
+ 'person',
+ 'groups',
+ 'cohorts',
+ 'feature',
+ 'flags',
+ 'experiments',
+ 'surveys',
+ 'replay',
+ 'recordings',
+ 'sessions',
+ 'insights',
+ 'dashboards',
+ 'actions',
+ 'annotations',
+ 'plugins',
+ 'apps',
+ 'pipelines',
+ 'destinations',
+ 'sources',
+ 'warehouse',
+ 'datasets',
+ 'queries',
+ 'saved',
+ 'trend',
+ 'funnel',
+ 'retention',
+ 'stickiness',
+ 'paths',
+ 'lifecycle',
+ 'breakdown',
+ 'filter',
+ 'filters',
+ 'interval',
+ 'intervals',
+ 'unique',
+ 'uniques',
+ 'distinct',
+ // common SaaS verbs / nouns
+ 'onboarding',
+ 'checkout',
+ 'signup',
+ 'signin',
+ 'feedback',
+ 'support',
+ 'contact',
+ 'help',
+ 'docs',
+ 'documentation',
+ 'guide',
+ 'guides',
+ 'tutorial',
+ 'tutorials',
+ 'example',
+ 'examples',
+ 'demo',
+ 'demos',
+ 'video',
+ 'videos',
+ 'article',
+ 'articles',
+ 'post',
+ 'posts',
+ 'blog',
+ 'news',
+ 'changelog',
+ 'roadmap',
+ 'status',
+ 'uptime',
+ 'faq',
+ 'about',
+ 'privacy',
+ 'terms',
+ 'legal',
+ 'security',
+ 'compliance',
+ // letters of the alphabet
+ 'a',
+ 'b',
+ 'c',
+ 'd',
+ 'e',
+ 'f',
+ 'g',
+ 'h',
+ 'i',
+ 'j',
+ 'k',
+ 'l',
+ 'm',
+ 'n',
+ 'o',
+ 'p',
+ 'q',
+ 'r',
+ 's',
+ 't',
+ 'u',
+ 'v',
+ 'w',
+ 'x',
+ 'y',
+ 'z',
+]
+
+export const DEFAULT_URL_SEGMENTS: string[] = [
+ // api versions / shapes
+ 'api',
+ 'apis',
+ 'v1',
+ 'v2',
+ 'v3',
+ 'v4',
+ 'v5',
+ 'v6',
+ 'v7',
+ 'graphql',
+ 'gql',
+ 'rest',
+ 'rpc',
+ 'grpc',
+ 'trpc',
+ 'soap',
+ 'ws',
+ 'webhook',
+ 'webhooks',
+ 'callback',
+ 'callbacks',
+ 'internal',
+ 'external',
+ 'public',
+ 'private',
+ 'beta',
+ 'alpha',
+ 'preview',
+ 'edge',
+ 'experimental',
+ // auth / identity
+ 'auth',
+ 'oauth',
+ 'oauth2',
+ 'openid',
+ 'saml',
+ 'sso',
+ 'ldap',
+ 'jwt',
+ 'login',
+ 'logout',
+ 'signin',
+ 'signout',
+ 'signup',
+ 'register',
+ 'registration',
+ 'verify',
+ 'verification',
+ 'confirm',
+ 'confirmation',
+ 'forgot',
+ 'reset',
+ 'recover',
+ 'recovery',
+ 'password',
+ 'passcode',
+ 'mfa',
+ '2fa',
+ 'otp',
+ 'totp',
+ 'callback',
+ 'callbacks',
+ // common app surfaces
+ 'home',
+ 'index',
+ 'dashboard',
+ 'dashboards',
+ 'overview',
+ 'feed',
+ 'timeline',
+ 'explore',
+ 'discover',
+ 'trending',
+ 'search',
+ 'results',
+ 'settings',
+ 'preferences',
+ 'profile',
+ 'profiles',
+ 'account',
+ 'accounts',
+ 'user',
+ 'users',
+ 'me',
+ 'self',
+ 'you',
+ 'billing',
+ 'subscription',
+ 'subscriptions',
+ 'plan',
+ 'plans',
+ 'pricing',
+ 'checkout',
+ 'cart',
+ 'order',
+ 'orders',
+ 'invoice',
+ 'invoices',
+ 'receipt',
+ 'receipts',
+ 'payment',
+ 'payments',
+ 'card',
+ 'cards',
+ 'team',
+ 'teams',
+ 'organization',
+ 'organizations',
+ 'org',
+ 'orgs',
+ 'company',
+ 'companies',
+ 'workspace',
+ 'workspaces',
+ 'project',
+ 'projects',
+ 'group',
+ 'groups',
+ 'members',
+ 'member',
+ 'admins',
+ 'admin',
+ 'owner',
+ 'owners',
+ 'guest',
+ 'guests',
+ 'invite',
+ 'invites',
+ 'invitation',
+ 'invitations',
+ // CRUD verbs / list ops
+ 'new',
+ 'edit',
+ 'create',
+ 'update',
+ 'delete',
+ 'remove',
+ 'restore',
+ 'archive',
+ 'duplicate',
+ 'clone',
+ 'fork',
+ 'copy',
+ 'move',
+ 'rename',
+ 'list',
+ 'all',
+ 'show',
+ 'view',
+ 'preview',
+ 'details',
+ 'detail',
+ 'summary',
+ 'stats',
+ 'stat',
+ 'info',
+ 'about',
+ 'import',
+ 'export',
+ 'download',
+ 'upload',
+ 'share',
+ 'embed',
+ 'search',
+ 'filter',
+ 'sort',
+ 'group',
+ 'compare',
+ // e-commerce
+ 'products',
+ 'product',
+ 'catalog',
+ 'store',
+ 'shop',
+ 'category',
+ 'categories',
+ 'collection',
+ 'collections',
+ 'brand',
+ 'brands',
+ 'tag',
+ 'tags',
+ 'review',
+ 'reviews',
+ 'wishlist',
+ 'favorites',
+ 'saved',
+ // content
+ 'posts',
+ 'post',
+ 'articles',
+ 'article',
+ 'blog',
+ 'blogs',
+ 'news',
+ 'press',
+ 'media',
+ 'stories',
+ 'story',
+ 'comments',
+ 'comment',
+ 'likes',
+ 'like',
+ 'reactions',
+ 'shares',
+ 'share',
+ 'pages',
+ 'page',
+ 'docs',
+ 'doc',
+ 'documentation',
+ 'guide',
+ 'guides',
+ 'tutorial',
+ 'tutorials',
+ 'manual',
+ 'reference',
+ 'help',
+ 'support',
+ 'faq',
+ 'faqs',
+ 'contact',
+ 'feedback',
+ 'about',
+ 'team',
+ 'careers',
+ 'jobs',
+ 'press',
+ 'privacy',
+ 'terms',
+ 'tos',
+ 'legal',
+ 'security',
+ 'compliance',
+ 'cookies',
+ 'sitemap',
+ 'changelog',
+ 'roadmap',
+ 'status',
+ 'uptime',
+ // developer / api
+ 'developers',
+ 'developer',
+ 'dev',
+ 'console',
+ 'playground',
+ 'sandbox',
+ 'examples',
+ 'example',
+ 'samples',
+ 'sample',
+ 'code',
+ 'snippets',
+ 'snippet',
+ 'demo',
+ 'demos',
+ 'tools',
+ 'tool',
+ 'cli',
+ 'sdk',
+ 'sdks',
+ 'library',
+ 'libraries',
+ 'package',
+ 'packages',
+ 'downloads',
+ 'download',
+ 'releases',
+ 'release',
+ 'versions',
+ 'version',
+ // assets / static
+ 'static',
+ 'assets',
+ 'asset',
+ 'public',
+ 'files',
+ 'file',
+ 'media',
+ 'uploads',
+ 'upload',
+ 'images',
+ 'image',
+ 'img',
+ 'icons',
+ 'icon',
+ 'logos',
+ 'logo',
+ 'videos',
+ 'video',
+ 'audio',
+ 'fonts',
+ 'font',
+ 'css',
+ 'js',
+ 'javascript',
+ 'ts',
+ 'typescript',
+ 'html',
+ 'json',
+ 'xml',
+ 'yaml',
+ 'toml',
+ 'markdown',
+ 'md',
+ 'txt',
+ 'pdf',
+ 'thumbnails',
+ 'thumbnail',
+ 'thumbs',
+ 'avatars',
+ 'avatar',
+ 'fonts',
+ 'vendor',
+ 'node_modules',
+ 'build',
+ 'dist',
+ 'out',
+ // analytics / posthog domain
+ 'events',
+ 'event',
+ 'persons',
+ 'person',
+ 'groups',
+ 'cohorts',
+ 'cohort',
+ 'feature_flags',
+ 'flags',
+ 'flag',
+ 'experiments',
+ 'experiment',
+ 'surveys',
+ 'survey',
+ 'replay',
+ 'recordings',
+ 'recording',
+ 'sessions',
+ 'session',
+ 'insights',
+ 'insight',
+ 'dashboards',
+ 'dashboard',
+ 'actions',
+ 'action',
+ 'annotations',
+ 'annotation',
+ 'plugins',
+ 'plugin',
+ 'apps',
+ 'app',
+ 'pipelines',
+ 'pipeline',
+ 'destinations',
+ 'destination',
+ 'sources',
+ 'source',
+ 'warehouse',
+ 'datasets',
+ 'dataset',
+ 'queries',
+ 'query',
+ 'saved',
+ 'trends',
+ 'trend',
+ 'funnels',
+ 'funnel',
+ 'retention',
+ 'stickiness',
+ 'paths',
+ 'path',
+ 'lifecycle',
+ 'explore',
+ 'sql',
+ 'notebooks',
+ 'notebook',
+ 'alerts',
+ 'alert',
+ 'subscriptions',
+ 'subscription',
+ // ops / infra
+ 'health',
+ 'healthz',
+ 'ready',
+ 'readyz',
+ 'ping',
+ 'status',
+ 'metrics',
+ 'logs',
+ 'log',
+ 'traces',
+ 'trace',
+ 'debug',
+ 'monitor',
+ 'monitoring',
+ 'alerts',
+ 'alert',
+ 'incidents',
+ 'incident',
+ 'errors',
+ 'error',
+ 'audit',
+ 'auditlog',
+ 'history',
+ 'activity',
+ 'activities',
+ 'tasks',
+ 'task',
+ 'jobs',
+ 'job',
+ 'workers',
+ 'worker',
+ 'queue',
+ 'queues',
+ 'schedules',
+ 'schedule',
+ 'cron',
+ // generic resource patterns
+ 'data',
+ 'records',
+ 'items',
+ 'entries',
+ 'objects',
+ 'graph',
+ 'report',
+ 'reports',
+ 'exports',
+ 'imports',
+ 'auth',
+ 'callback',
+ 'redirect',
+ 'verify',
+ 'confirm',
+ // locale prefixes
+ 'en',
+ 'us',
+ 'uk',
+ 'eu',
+ 'de',
+ 'fr',
+ 'es',
+ 'it',
+ 'pt',
+ 'br',
+ 'jp',
+ 'kr',
+ 'cn',
+ 'tw',
+ 'hk',
+ 'in',
+ 'au',
+ 'ca',
+ 'mx',
+ 'ru',
+ 'nl',
+ 'se',
+ 'no',
+ 'dk',
+ 'fi',
+ 'pl',
+ 'en-us',
+ 'en-gb',
+ 'en-au',
+ 'en-ca',
+ 'es-es',
+ 'es-mx',
+ 'fr-fr',
+ 'fr-ca',
+ 'de-de',
+ 'pt-br',
+ 'pt-pt',
+ 'zh-cn',
+ 'zh-tw',
+ 'ja-jp',
+ // pagination markers
+ 'page',
+ 'pages',
+ 'next',
+ 'prev',
+ 'previous',
+ 'first',
+ 'last',
+ 'more',
+]
+
+let cachedDefault: AllowLists | undefined
+
+/** The default allow lists, built once and shared (the underlying lists are immutable). */
+export function defaultAllowLists(): AllowLists {
+ return (cachedDefault ??= new AllowLists(DEFAULT_TEXT_WORDS, DEFAULT_URL_SEGMENTS))
+}
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/anonymize/dom.test.ts b/nodejs/src/ingestion/pipelines/sessionreplay/anonymize/dom.test.ts
new file mode 100644
index 000000000000..a23663c0b0eb
--- /dev/null
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/anonymize/dom.test.ts
@@ -0,0 +1,259 @@
+import { defaultAllowLists } from './default-dict'
+import { scrubFullSnapshot, scrubMutation } from './dom'
+
+describe('anonymize/dom', () => {
+ const ctx = { allow: defaultAllowLists() }
+
+ it('scrubs text nodes but leaves script source untouched', () => {
+ const event = {
+ type: 2,
+ timestamp: 1,
+ data: {
+ node: {
+ type: 0,
+ id: 1,
+ childNodes: [
+ {
+ type: 2,
+ id: 2,
+ tagName: 'div',
+ attributes: {},
+ childNodes: [{ type: 3, id: 3, textContent: 'Hello SecretName' }],
+ },
+ {
+ type: 2,
+ id: 4,
+ tagName: 'script',
+ attributes: {},
+ childNodes: [{ type: 3, id: 5, textContent: 'var x = 1;' }],
+ },
+ ],
+ },
+ initialOffset: { top: 0, left: 0 },
+ },
+ }
+ const changed = scrubFullSnapshot(ctx, event.data)
+ expect(changed).toBe(true)
+
+ const root = event.data.node
+ const div = root.childNodes[0]
+ const txt = div.childNodes[0]
+ // "Hello" is allow-listed; "SecretName" is 10 chars → ten *s.
+ expect(txt.textContent).toBe('Hello **********')
+
+ const script = root.childNodes[1]
+ const scriptTxt = script.childNodes[0]
+ expect(scriptTxt.textContent).toBe('var x = 1;')
+ })
+
+ it('URL-scrubs url attributes and leaves class untouched', () => {
+ const event = {
+ type: 2,
+ timestamp: 1,
+ data: {
+ node: {
+ type: 0,
+ id: 1,
+ childNodes: [
+ {
+ type: 2,
+ id: 2,
+ tagName: 'a',
+ attributes: { href: 'https://example.com/user/abc/edit', class: 'link primary' },
+ childNodes: [],
+ },
+ ],
+ },
+ initialOffset: { top: 0, left: 0 },
+ },
+ }
+ scrubFullSnapshot(ctx, event.data)
+ const a = event.data.node.childNodes[0]
+ expect(a.attributes.href).toBe('https://example.com/user/[redacted]/edit')
+ expect(a.attributes.class).toBe('link primary')
+ })
+
+ it('preserves non-string attribute values and scrubs only string url/text attrs', () => {
+ const event = {
+ type: 2,
+ timestamp: 1,
+ data: {
+ node: {
+ type: 0,
+ id: 1,
+ childNodes: [
+ {
+ type: 2,
+ id: 2,
+ tagName: 'body',
+ attributes: {
+ href: 'https://example.com/user/abc/edit',
+ title: 'Smithson lives nearby',
+ class: 'x',
+ 'data-n': 3,
+ disabled: true,
+ removed: null,
+ },
+ childNodes: [],
+ },
+ ],
+ },
+ initialOffset: { top: 0, left: 0 },
+ },
+ }
+ scrubFullSnapshot(ctx, event.data)
+ const attrs = event.data.node.childNodes[0].attributes
+ // String url/user-text attrs scrubbed:
+ expect(attrs.href).toBe('https://example.com/user/[redacted]/edit')
+ expect(attrs.title).toBe('******** ***** ******')
+ // Non-url/text string left as-is; non-string values untouched:
+ expect(attrs.class).toBe('x')
+ expect(attrs['data-n']).toBe(3)
+ expect(attrs.disabled).toBe(true)
+ expect(attrs.removed).toBeNull()
+ })
+
+ it('scrubs an inline (uncompressed) mutation', () => {
+ const data: any = {
+ source: 0,
+ texts: [{ id: 5, value: 'Hello SecretName' }],
+ attributes: [{ id: 4, attributes: { title: 'Smithson lives nearby', class: 'y' } }],
+ removes: [{ parentId: 3, id: 7 }],
+ adds: [{ parentId: 4, nextId: null, node: { type: 3, id: 8, textContent: 'Hello Smithson' } }],
+ }
+ const changed = scrubMutation(ctx, data)
+ expect(changed).toBe(true)
+ expect(data.texts[0].value).toBe('Hello **********')
+ expect(data.attributes[0].attributes.title).toBe('******** ***** ******')
+ expect(data.attributes[0].attributes.class).toBe('y')
+ expect(data.adds[0].node.textContent).toBe('Hello ********')
+ // removes is ids-only and untouched.
+ expect(data.removes[0].id).toBe(7)
+ })
+
+ it('scrubs Comment and CDATA text content', () => {
+ const event = {
+ type: 2,
+ timestamp: 1,
+ data: {
+ node: {
+ type: 0,
+ id: 1,
+ childNodes: [
+ { type: 5, id: 2, textContent: 'Hello SecretName' },
+ { type: 4, id: 3, textContent: 'Hello SecretName' },
+ // DocumentType (type 1) carries no text and is left alone.
+ { type: 1, id: 4, name: 'html' },
+ ],
+ },
+ initialOffset: { top: 0, left: 0 },
+ },
+ }
+ const changed = scrubFullSnapshot(ctx, event.data)
+ expect(changed).toBe(true)
+ expect(event.data.node.childNodes[0].textContent).toBe('Hello **********')
+ expect(event.data.node.childNodes[1].textContent).toBe('Hello **********')
+ })
+
+ it('replaces a remote image src with the placeholder and preserves the URL', () => {
+ const event = {
+ type: 2,
+ timestamp: 1,
+ data: {
+ node: {
+ type: 0,
+ id: 1,
+ childNodes: [
+ {
+ type: 2,
+ id: 2,
+ tagName: 'img',
+ attributes: { src: 'https://example.com/u/abc.png', alt: 'profile photo of user' },
+ childNodes: [],
+ },
+ ],
+ },
+ initialOffset: { top: 0, left: 0 },
+ },
+ }
+ scrubFullSnapshot(ctx, event.data)
+ const img = event.data.node.childNodes[0]
+ expect(typeof img.attributes.src).toBe('string')
+ expect((img.attributes.src as string).startsWith('data:image/svg+xml')).toBe(true)
+ expect('data-anon-original-src' in img.attributes).toBe(true)
+ })
+
+ it('keeps state-token data-* (so styling survives) but redacts PII-looking values and emails', () => {
+ const attrs: Record<string, unknown> = {
+ 'data-state': 'active', // enum/state token → kept (CSS selectors depend on it)
+ 'data-scheme': 'primary', // ditto
+ 'data-tooltip': 'Logged in as Smithson', // free text (whitespace) → redacted
+ 'data-contact': '[email protected]', // email → redacted regardless
+ 'data-anon-original-src': 'https://example.com/[redacted]/[redacted]', // our stash → left intact
+ }
+ scrubMutation(ctx, { source: 0, attributes: [{ id: 2, attributes: attrs }] })
+ expect(attrs['data-state']).toBe('active')
+ expect(attrs['data-scheme']).toBe('primary')
+ expect(attrs['data-tooltip']).not.toContain('Smithson')
+ expect(attrs['data-contact']).not.toContain('jane')
+ expect(attrs['data-contact']).not.toContain('example.com')
+ expect(attrs['data-anon-original-src']).toBe('https://example.com/[redacted]/[redacted]')
+ })
+
+ it('leaves CSS untouched: the inline style attribute and <style> text pass through verbatim', () => {
+ // CSS is author stylesheet content, not user PII; scrubbing url() targets broke far
+ // more (SVG sprite fragments, CDN asset paths) than it ever saved, so we no longer touch it.
+ const attrs: Record<string, unknown> = { style: 'background: url(/users/SecretUser/bg.png)' }
+ expect(scrubMutation(ctx, { source: 0, attributes: [{ id: 2, attributes: attrs }] })).toBe(false)
+ expect(attrs.style).toBe('background: url(/users/SecretUser/bg.png)')
+
+ const cssText = '.a { background: url(/users/SecretUser/x.png) }'
+ const event = {
+ type: 2,
+ timestamp: 1,
+ data: {
+ node: {
+ type: 0,
+ id: 1,
+ childNodes: [
+ {
+ type: 2,
+ id: 2,
+ tagName: 'style',
+ attributes: {},
+ childNodes: [{ type: 3, id: 3, textContent: cssText }],
+ },
+ ],
+ },
+ initialOffset: { top: 0, left: 0 },
+ },
+ }
+ expect(scrubFullSnapshot(ctx, event.data)).toBe(false)
+ expect(event.data.node.childNodes[0].childNodes[0].textContent).toBe(cssText)
+ })
+
+ it('blurs canvas pixels inlined as rr_dataURL in a FullSnapshot', () => {
+ const blurCtx = { allow: defaultAllowLists(), blurJobs: [] as any[] }
+ const onePxPng =
+ 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAIAAACQkWg2AAAACXBIWXMAAAPoAAAD6AG1e1JrAAAAJUlEQVQokWN4plEBRyInbOAIlzjDINRAjCJk8cGoYRAG60iMBwA8H08Qor0ygQAAAABJRU5ErkJggg=='
+ const canvasAttrs: Record<string, unknown> = { rr_dataURL: onePxPng, width: '300', height: '150' }
+ const event = {
+ type: 2,
+ timestamp: 1,
+ data: {
+ node: {
+ type: 0,
+ id: 1,
+ childNodes: [{ type: 2, id: 2, tagName: 'canvas', attributes: canvasAttrs, childNodes: [] }],
+ },
+ initialOffset: { top: 0, left: 0 },
+ },
+ }
+ expect(scrubFullSnapshot(blurCtx, event.data)).toBe(true)
+ // Raw pixels gone immediately (fail-safe), blur deferred; dimensions untouched.
+ expect(canvasAttrs.rr_dataURL).not.toBe(onePxPng)
+ expect(canvasAttrs.rr_dataURL).toMatch(/^data:image\/png;base64,/)
+ expect(canvasAttrs.width).toBe('300')
+ expect(blurCtx.blurJobs).toHaveLength(1)
+ })
+})
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/anonymize/dom.ts b/nodejs/src/ingestion/pipelines/sessionreplay/anonymize/dom.ts
new file mode 100644
index 000000000000..995c78a05e82
--- /dev/null
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/anonymize/dom.ts
@@ -0,0 +1,241 @@
+/** Walks parsed rrweb serialized nodes, scrubbing text content and attributes in place. */
+import {
+ INLINE_IMAGE_ATTR,
+ applyBlur,
+ blurInlineImageAttr,
+ hasMediaSrcAttr,
+ isMediaSrcAttr,
+ isMediaTag,
+} from './assets'
+import { ScrubContext, isObject } from './config'
+import { scrubCssImages } from './css'
+import { redactEmails, scrubText } from './text'
+import { scrubUrl } from './url'
+
+export enum NodeType {
+ Document = 0,
+ DocumentType = 1,
+ Element = 2,
+ Text = 3,
+ Cdata = 4,
+ Comment = 5,
+}
+
+type ParentKind = 'script' | 'style' | 'other'
+type TagKind = 'script' | 'style' | 'media' | 'other'
+
+type AnyNode = Record<string, unknown>
+
+export function scrubFullSnapshot(ctx: ScrubContext, data: unknown): boolean {
+ if (!isObject(data) || !isObject(data.node)) {
+ return false
+ }
+ return walkNode(ctx, data.node, 'other')
+}
+
+export function scrubMutation(ctx: ScrubContext, data: unknown): boolean {
+ if (!isObject(data)) {
+ return false
+ }
+ let changed = false
+
+ if (Array.isArray(data.texts)) {
+ for (const t of data.texts) {
+ if (isObject(t) && typeof t.value === 'string') {
+ const result = scrubText(ctx, t.value)
+ if (result.changed) {
+ t.value = result.value
+ changed = true
+ }
+ }
+ }
+ }
+
+ if (Array.isArray(data.attributes)) {
+ for (const a of data.attributes) {
+ if (isObject(a) && isObject(a.attributes)) {
+ const kind: TagKind = hasMediaSrcAttr(a.attributes) ? 'media' : 'other'
+ changed = scrubAttrs(ctx, a.attributes, kind) || changed
+ }
+ }
+ }
+
+ if (Array.isArray(data.adds)) {
+ for (const added of data.adds) {
+ if (isObject(added) && isObject(added.node)) {
+ changed = walkNode(ctx, added.node, 'other') || changed
+ }
+ }
+ }
+
+ return changed
+}
+
+function walkNode(ctx: ScrubContext, node: AnyNode, parent: ParentKind): boolean {
+ let changed = false
+
+ switch (node.type) {
+ case NodeType.Element: {
+ const kind = classifyTag(typeof node.tagName === 'string' ? node.tagName : '')
+ if (isObject(node.attributes)) {
+ changed = scrubAttrs(ctx, node.attributes, kind) || changed
+ }
+ const childParent: ParentKind = kind === 'media' ? 'other' : kind
+ if (Array.isArray(node.childNodes)) {
+ for (const child of node.childNodes) {
+ if (isObject(child)) {
+ changed = walkNode(ctx, child, childParent) || changed
+ }
+ }
+ }
+ break
+ }
+ case NodeType.Document: {
+ if (Array.isArray(node.childNodes)) {
+ for (const child of node.childNodes) {
+ if (isObject(child)) {
+ changed = walkNode(ctx, child, 'other') || changed
+ }
+ }
+ }
+ break
+ }
+ case NodeType.Text: {
+ // Script is code — never touch it.
+ if (parent === 'script') {
+ return false
+ }
+ if (parent === 'style' || node.isStyle === true) {
+ return scrubCssImages(ctx, node, 'textContent')
+ }
+ changed = scrubTextContent(ctx, node) || changed
+ break
+ }
+ case NodeType.Comment:
+ case NodeType.Cdata: {
+ changed = scrubTextContent(ctx, node) || changed
+ break
+ }
+ // DocumentType: nothing.
+ }
+
+ return changed
+}
+
+function scrubTextContent(ctx: ScrubContext, node: AnyNode): boolean {
+ if (typeof node.textContent !== 'string') {
+ return false
+ }
+ const result = scrubText(ctx, node.textContent)
+ if (result.changed) {
+ node.textContent = result.value
+ return true
+ }
+ return false
+}
+
+function classifyTag(tag: string): TagKind {
+ const lower = tag.toLowerCase()
+ if (lower === 'script') {
+ return 'script'
+ }
+ if (lower === 'style') {
+ return 'style'
+ }
+ if (isMediaTag(tag)) {
+ return 'media'
+ }
+ return 'other'
+}
+
+function scrubAttrs(ctx: ScrubContext, attrs: Record<string, unknown>, kind: TagKind): boolean {
+ let changed = false
+
+ for (const name of Object.keys(attrs)) {
+ if (kind === 'media' && isMediaSrcAttr(name)) {
+ continue
+ }
+ // Inlined rendered pixels (canvas/img `rr_dataURL`): blur the image, on any tag.
+ if (name === INLINE_IMAGE_ATTR) {
+ changed = blurInlineImageAttr(ctx, attrs, name) || changed
+ continue
+ }
+ const value = attrs[name]
+ // Only string attribute values are scrubbed (objects/numbers/bools are skipped).
+ if (typeof value !== 'string') {
+ continue
+ }
+ let result
+ if (isUrlAttr(name)) {
+ result = scrubUrl(ctx, value)
+ } else if (name === 'style') {
+ changed = scrubCssImages(ctx, attrs, name) || changed
+ continue
+ } else if (isUserTextAttr(name)) {
+ result = scrubText(ctx, value)
+ } else if (isDataAttr(name)) {
+ result = dataAttrLooksSensitive(value) ? scrubText(ctx, value) : redactEmails(value)
+ } else {
+ continue
+ }
+ if (result.changed) {
+ attrs[name] = result.value
+ changed = true
+ }
+ }
+
+ if (kind === 'media') {
+ applyBlur(ctx, attrs)
+ changed = true
+ }
+
+ return changed
+}
+
+function isUserTextAttr(name: string): boolean {
+ switch (name) {
+ case 'alt':
+ case 'title':
+ case 'placeholder':
+ case 'aria-label':
+ case 'aria-description':
+ case 'aria-roledescription':
+ case 'aria-valuetext':
+ case 'aria-placeholder':
+ case 'value':
+ case 'label':
+ case 'summary':
+ return true
+ default:
+ return false
+ }
+}
+
+function isDataAttr(name: string): boolean {
+ return name.startsWith('data-') && !name.startsWith('data-anon-original-')
+}
+
+function dataAttrLooksSensitive(value: string): boolean {
+ // Free text (whitespace) or an email-ish token — not a single enum/state/id token.
+ return value.includes('@') || /\s/.test(value)
+}
+
+function isUrlAttr(name: string): boolean {
+ switch (name) {
+ case 'href':
+ case 'src':
+ case 'srcset':
+ case 'action':
+ case 'formaction':
+ case 'cite':
+ case 'data':
+ case 'poster':
+ case 'background':
+ case 'xlink:href':
+ case 'manifest':
+ case 'longdesc':
+ return true
+ default:
+ return false
+ }
+}
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/anonymize/index.ts b/nodejs/src/ingestion/pipelines/sessionreplay/anonymize/index.ts
new file mode 100644
index 000000000000..f3e5a782166b
--- /dev/null
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/anonymize/index.ts
@@ -0,0 +1,5 @@
+export { AllowLists } from './allow-lists'
+export { anonymizeEvent, anonymizeParsedMessage } from './anonymize-event'
+export { loadAllowLists } from './allow-list-loader'
+export { type ScrubContext } from './config'
+export { defaultAllowLists } from './default-dict'
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/anonymize/text.test.ts b/nodejs/src/ingestion/pipelines/sessionreplay/anonymize/text.test.ts
new file mode 100644
index 000000000000..4037d64fa792
--- /dev/null
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/anonymize/text.test.ts
@@ -0,0 +1,59 @@
+import { defaultAllowLists } from './default-dict'
+import { scrubText } from './text'
+
+describe('anonymize/text', () => {
+ const allow = defaultAllowLists()
+ const scrub = (input: string): string => scrubText({ allow }, input).value
+
+ it('keeps allow-listed words', () => {
+ expect(scrub('Click submit to continue')).toBe('Click submit to continue')
+ })
+
+ it('redacts unknown words per char', () => {
+ expect(scrub('Hello Mr Smithson')).toBe('Hello ** ********')
+ })
+
+ it('turns numbers into hash per char', () => {
+ expect(scrub('user 42 home 99')).toBe('user ## home ##')
+ })
+
+ it('redacts numeric tokens with #', () => {
+ expect(scrub('submit 4242 Smithson')).toBe('submit #### ********')
+ })
+
+ it('preserves punctuation', () => {
+ expect(scrub('user, click submit!')).toBe('user, click submit!')
+ })
+
+ it('preserves contractions', () => {
+ expect(scrub("I'll click submit but don't save it. Let's continue.")).toBe(
+ "I'll click submit but don't save it. Let's continue."
+ )
+ })
+
+ it('handles the typographic apostrophe', () => {
+ expect(scrub('I’ll save it')).toBe('I’ll save it')
+ })
+
+ it('lets a possessive inherit its base allow-listing', () => {
+ expect(scrub("the user's account")).toBe("the user's account")
+ })
+
+ it('keeps allow-listed words in long (>8 word) text — no full-redact threshold', () => {
+ expect(scrub('click submit cancel click submit cancel click submit cancel Smithson')).toBe(
+ 'click submit cancel click submit cancel click submit cancel ********'
+ )
+ })
+
+ it('preserves code-point length when redacting astral (surrogate-pair) characters', () => {
+ // Two CJK-extension-B letters = 2 code points (4 UTF-16 units). Redaction
+ // must produce 2 mark chars, not 4.
+ expect(scrub('𠀀𠀀')).toBe('**')
+ })
+
+ it('redacts whole email addresses via the regex pass (even allow-listed fragments)', () => {
+ // `to`/`in` are stop-words the tokenizer would keep, but the email pass nukes the address first.
+ expect(scrub('to [email protected]')).toBe('to ' + '*'.repeat('[email protected]'.length))
+ expect(scrub('email [email protected]')).not.toContain('[email protected]')
+ })
+})
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/anonymize/text.ts b/nodejs/src/ingestion/pipelines/sessionreplay/anonymize/text.ts
new file mode 100644
index 000000000000..aa5e1a71bf85
--- /dev/null
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/anonymize/text.ts
@@ -0,0 +1,124 @@
+/** Length-preserving text scrub: numeric tokens → `#`, allow-listed words kept, everything else → `*`. */
+import { AllowLists } from './allow-lists'
+import { NUMBER_CHAR, REDACT_CHAR, ScrubContext } from './config'
+
+export interface ScrubResult {
+ value: string
+ changed: boolean
+}
+
+// A "word" is a maximal run of word chars: Unicode letters/numbers, `_`, `'`, `’`.
+const WORD_RE = /[\p{L}\p{N}_'’]+/gu
+
+// Guaranteed email-PII pass, run over all text
+const EMAIL_RE = /[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}/g
+
+/** Redact any email addresses in `input` (length-preserving). Safe to run anywhere. */
+export function redactEmails(input: string): ScrubResult {
+ let changed = false
+ const value = input.replace(EMAIL_RE, (m) => {
+ changed = true
+ return REDACT_CHAR.repeat(codePointLength(m))
+ })
+ return { value, changed }
+}
+
+export function scrubText(ctx: ScrubContext, input: string): ScrubResult {
+ // Nuke whole email addresses first; the tokenizer then runs over what's left.
+ const emails = redactEmails(input)
+ const text = emails.value
+ let changed = emails.changed
+ let out = ''
+ let lastIndex = 0
+
+ WORD_RE.lastIndex = 0
+ let match: RegExpExecArray | null
+ while ((match = WORD_RE.exec(text)) !== null) {
+ const word = match[0]
+ const start = match.index
+ if (start > lastIndex) {
+ out += text.slice(lastIndex, start)
+ }
+ const emitted = emitWord(word, ctx.allow)
+ out += emitted.value
+ changed = changed || emitted.changed
+ lastIndex = WORD_RE.lastIndex
+ }
+ if (lastIndex < text.length) {
+ out += text.slice(lastIndex)
+ }
+
+ return { value: out, changed }
+}
+
+function emitWord(word: string, allow: AllowLists): ScrubResult {
+ if (isNumericToken(word)) {
+ return { value: redact(word, NUMBER_CHAR), changed: true }
+ }
+ if (wordIsAllowed(allow, word)) {
+ return { value: word, changed: false }
+ }
+ return { value: redact(word, REDACT_CHAR), changed: true }
+}
+
+/** Length-preserving redaction: one mark per source code point (not UTF-16 unit). */
+function redact(word: string, mark: string): string {
+ return mark.repeat(codePointLength(word))
+}
+
+function codePointLength(s: string): number {
+ let n = 0
+ for (let i = 0; i < s.length; i++) {
+ n++
+ const c = s.charCodeAt(i)
+ if (c >= 0xd800 && c <= 0xdbff && i + 1 < s.length) {
+ i++ // skip the low surrogate
+ }
+ }
+ return n
+}
+
+function wordIsAllowed(allow: AllowLists, word: string): boolean {
+ if (allow.textContains(word)) {
+ return true
+ }
+ if (word.includes('’')) {
+ const normalized = word.replace(/’/g, "'")
+ if (allow.textContains(normalized)) {
+ return true
+ }
+ const base = stripPossessive(normalized)
+ if (base !== null && allow.textContains(base)) {
+ return true
+ }
+ }
+ const base = stripPossessive(word)
+ if (base !== null && allow.textContains(base)) {
+ return true
+ }
+ return false
+}
+
+function stripPossessive(word: string): string | null {
+ for (const suffix of ["'s", '’s', "'", '’']) {
+ if (word.endsWith(suffix)) {
+ const base = word.slice(0, word.length - suffix.length)
+ if (base.length > 0) {
+ return base
+ }
+ }
+ }
+ return null
+}
+
+function isNumericToken(word: string): boolean {
+ let sawDigit = false
+ for (const c of word) {
+ if (c >= '0' && c <= '9') {
+ sawDigit = true
+ } else if (c !== '.' && c !== ',' && c !== '-' && c !== '+') {
+ return false
+ }
+ }
+ return sawDigit
+}
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/anonymize/url.test.ts b/nodejs/src/ingestion/pipelines/sessionreplay/anonymize/url.test.ts
new file mode 100644
index 000000000000..6c62f847928f
--- /dev/null
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/anonymize/url.test.ts
@@ -0,0 +1,101 @@
+import { AllowLists } from './allow-lists'
+import { defaultAllowLists } from './default-dict'
+import { scrubUrl } from './url'
+
+describe('anonymize/url', () => {
+ const allow = defaultAllowLists()
+ const scrub = (input: string): string => scrubUrl({ allow }, input).value
+
+ it('keeps allow-listed segments, masks numbers, and redacts other identifiers', () => {
+ expect(scrub('https://example.com/api/v1/users/42/profile')).toBe('https://example.com/api/v1/users/$$/profile')
+ })
+
+ it('drops non-allow-listed query params and fragments', () => {
+ expect(scrub('https://example.com/dashboard?token=secret#frag')).toBe('https://example.com/dashboard')
+ })
+
+ it('redacts segments in a relative path', () => {
+ expect(scrub('/user/abc/edit')).toBe('/user/[redacted]/edit')
+ })
+
+ it('keeps the authority verbatim for a protocol-relative URL', () => {
+ expect(scrub('//cdn.example.com/assets/abc/logo.png')).toBe('//cdn.example.com/assets/[redacted]/[redacted]')
+ })
+
+ it('treats a host-only URL (no path) as authority and leaves it unchanged', () => {
+ expect(scrub('https://example.com')).toBe('https://example.com')
+ expect(scrub('//cdn.example.com')).toBe('//cdn.example.com')
+ })
+
+ it('redacts a bare relative segment with no authority', () => {
+ expect(scrub('secrettoken')).toBe('[redacted]')
+ })
+
+ it('leaves a fully allow-listed path untouched (no change)', () => {
+ expect(scrub('https://example.com/api/v1/users')).toBe('https://example.com/api/v1/users')
+ })
+
+ describe('scrubAuthority (Meta only)', () => {
+ const ctx = { allow: new AllowLists([], ['us', 'api', 'v1', 'users', 'profile']) }
+ const sa = (i: string): string => scrubUrl(ctx, i, { scrubAuthority: true }).value
+
+ it('keeps an allow-listed subdomain and rewrites the rest to example.com', () => {
+ expect(sa('https://us.website.com/api/v1/users/42/profile')).toBe(
+ 'https://us.example.com/api/v1/users/$$/profile'
+ )
+ })
+ it('drops a 2-label host to example.com (no doubled label)', () => {
+ expect(sa('https://website.com/x')).toBe('https://example.com/[redacted]')
+ expect(sa('https://example.com/x')).toBe('https://example.com/[redacted]')
+ })
+ it('strips userinfo and port', () => {
+ expect(sa('https://user:[email protected]:8443/x')).toBe('https://us.example.com/[redacted]')
+ })
+ it('default (no opts) keeps the authority verbatim', () => {
+ expect(scrub('https://us.website.com/users/42')).toBe('https://us.website.com/users/$$')
+ })
+ })
+
+ describe('query and fragment (numbers scrubbed; key/value allow-listed with [key]/[value] fallback)', () => {
+ const ctx = { allow: new AllowLists([], ['app', 'page', 'sort', 'tab', 'q', 'about', 'asc', 'settings']) }
+ const u = (i: string): string => scrubUrl(ctx, i).value
+
+ it('keeps params whose key and value are both allow-listed (+ an allow-listed fragment)', () => {
+ expect(u('https://example.com/app?sort=asc&tab=settings#about')).toBe(
+ 'https://example.com/app?sort=asc&tab=settings#about'
+ )
+ })
+ it('masks a numeric value with $ per digit, kept because the key is allow-listed', () => {
+ expect(u('https://example.com/app?page=2')).toBe('https://example.com/app?page=$')
+ expect(u('https://example.com/app?page=2024')).toBe('https://example.com/app?page=$$$$')
+ })
+ it('drops a param whose only non-denied side is a number (number counts as denied)', () => {
+ expect(u('https://example.com/app?id=42')).toBe('https://example.com/app')
+ })
+ it('replaces the denied side: key allowed + value denied → key=[value]', () => {
+ expect(u('https://example.com/app?sort=secret')).toBe('https://example.com/app?sort=[value]')
+ })
+ it('replaces the denied side: key denied + value allowed → [key]=value', () => {
+ expect(u('https://example.com/app?xyz=asc')).toBe('https://example.com/app?[key]=asc')
+ })
+ it('drops the param only when both key and value are denied', () => {
+ expect(u('https://example.com/app?token=secret')).toBe('https://example.com/app')
+ })
+ it('treats a complex (non-alphanumeric) value as denied → [value]', () => {
+ expect(u('https://example.com/app?q=a%20b')).toBe('https://example.com/app?q=[value]')
+ })
+ it('keeps a bare allow-listed flag and drops a denied one', () => {
+ expect(u('https://example.com/app?sort&token')).toBe('https://example.com/app?sort')
+ })
+ it('keeps an allow-listed fragment and drops a numeric or non-allow-listed one', () => {
+ expect(u('https://example.com/app#about')).toBe('https://example.com/app#about')
+ expect(u('https://example.com/app#42')).toBe('https://example.com/app') // number alone → dropped
+ expect(u('https://example.com/app#xyz')).toBe('https://example.com/app') // not allow-listed
+ })
+ })
+
+ it('masks a bare-number path segment with $', () => {
+ const numCtx = { allow: new AllowLists([], ['users']) }
+ expect(scrubUrl(numCtx, 'https://example.com/users/2/x').value).toBe('https://example.com/users/$/[redacted]')
+ })
+})
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/anonymize/url.ts b/nodejs/src/ingestion/pipelines/sessionreplay/anonymize/url.ts
new file mode 100644
index 000000000000..2c314765067e
--- /dev/null
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/anonymize/url.ts
@@ -0,0 +1,168 @@
+/**
+ * URL scrub.
+ *
+ * - Numbers (a bare run of digits) are masked to `$` per digit (length-preserving; `$` rather than `#`
+ * so it doesn't clash with the fragment separator).
+ * - Path: keep allow-listed segments; a number → `$$`; anything else → `[redacted]`.
+ * - Query: a param survives only if its key or value is an allow-listed alphanumeric token. A number
+ * counts as denied for survival, so `id=42` is dropped while `page=2` → `page=$`. When a param
+ * survives, each side renders independently: allow-listed → kept, number → `$$`, denied → `[key]`/`[value]`.
+ * - Fragment: kept only if it is an allow-listed alphanumeric token; numbers and everything else dropped.
+ * - With `{ scrubAuthority: true }` it strips userinfo/port and
+ * collapses the host to `example.com` (keeping a leading allow-listed subdomain label).
+ */
+import { ScrubContext } from './config'
+import { ScrubResult } from './text'
+
+export interface UrlScrubOptions {
+ scrubAuthority?: boolean
+}
+
+const SIMPLE = /^[A-Za-z0-9]*$/ // 100% alphanumeric (empty allowed)
+const NUMERIC = /^[0-9]+$/ // a bare number
+
+const maskNumber = (n: string): string => '$'.repeat(n.length) // `$`, not `#` (the fragment separator)
+
+// An allow-listed, alphanumeric, non-number token — the only kind that keeps a query param/fragment
+// alive.
+function isAllowed(ctx: ScrubContext, t: string): boolean {
+ return t.length > 0 && SIMPLE.test(t) && !NUMERIC.test(t) && ctx.allow.urlContains(t)
+}
+
+// Rendered form of a surviving token: a number → `$$`, an allow-listed token → itself, else null.
+function renderToken(ctx: ScrubContext, t: string): string | null {
+ return NUMERIC.test(t) ? maskNumber(t) : isAllowed(ctx, t) ? t : null
+}
+
+export function scrubUrl(ctx: ScrubContext, input: string, opts?: UrlScrubOptions): ScrubResult {
+ const tailIdx = input.search(/[?#]/)
+ const base = tailIdx === -1 ? input : input.slice(0, tailIdx)
+ const tail = tailIdx === -1 ? '' : input.slice(tailIdx) // starts with ? or #
+ let changed = false
+
+ const { scheme, authority, path } = splitUrl(base)
+ let out = scheme
+ if (authority) {
+ if (opts?.scrubAuthority) {
+ const scrubbed = scrubHost(ctx, authority)
+ if (scrubbed !== authority) {
+ changed = true
+ }
+ out += scrubbed
+ } else {
+ out += authority
+ }
+ }
+
+ let first = true
+ for (const raw of path.split('/')) {
+ if (first) {
+ first = false
+ } else {
+ out += '/'
+ }
+ if (raw.length === 0) {
+ continue
+ }
+ if (NUMERIC.test(raw)) {
+ out += maskNumber(raw) // a bare number → $$
+ changed = true
+ } else if (isSafeSegment(raw) || ctx.allow.urlContains(raw)) {
+ out += raw
+ } else {
+ out += '[redacted]'
+ changed = true
+ }
+ }
+
+ const tailOut = scrubTail(ctx, tail)
+ if (tailOut !== tail) {
+ changed = true
+ }
+ out += tailOut
+
+ return { value: out, changed }
+}
+
+function scrubTail(ctx: ScrubContext, tail: string): string {
+ if (tail === '') {
+ return ''
+ }
+ let query = ''
+ let frag = ''
+ if (tail[0] === '?') {
+ const h = tail.indexOf('#')
+ query = h === -1 ? tail.slice(1) : tail.slice(1, h)
+ frag = h === -1 ? '' : tail.slice(h + 1)
+ } else {
+ frag = tail.slice(1) // tail starts with '#'
+ }
+
+ let out = ''
+ if (tail[0] === '?') {
+ const kept: string[] = []
+ for (const pair of query.split('&')) {
+ if (pair === '') {
+ continue
+ }
+ const eq = pair.indexOf('=')
+ if (eq === -1) {
+ if (isAllowed(ctx, pair)) {
+ kept.push(pair)
+ }
+ continue
+ }
+ const key = pair.slice(0, eq)
+ const value = pair.slice(eq + 1)
+ if (!isAllowed(ctx, key) && !(value !== '' && isAllowed(ctx, value))) {
+ continue
+ }
+ const kr = renderToken(ctx, key) ?? '[key]'
+ const vr = value === '' ? '' : (renderToken(ctx, value) ?? '[value]')
+ kept.push(`${kr}=${vr}`)
+ }
+ if (kept.length > 0) {
+ out += '?' + kept.join('&')
+ }
+ }
+ if (frag.length > 0 && isAllowed(ctx, frag)) {
+ out += '#' + frag
+ }
+ return out
+}
+
+// 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`.
+function scrubHost(ctx: ScrubContext, authority: string): string {
+ const at = authority.lastIndexOf('@')
+ let host = at !== -1 ? authority.slice(at + 1) : authority
+ host = host.replace(/:\d+$/, '') // drop :port
+ const labels = host.split('.')
+ const first = labels[0] ?? ''
+ return labels.length > 2 && first && ctx.allow.urlContains(first) ? `${first}.example.com` : 'example.com'
+}
+
+// Split into scheme prefix (incl. `://` or `//`), authority (`[userinfo@]host[:port]`), and path.
+function splitUrl(s: string): { scheme: string; authority: string; path: string } {
+ let scheme = ''
+ let rest = s
+ const schemeEnd = s.indexOf('://')
+ if (schemeEnd !== -1) {
+ scheme = s.slice(0, schemeEnd + 3)
+ rest = s.slice(schemeEnd + 3)
+ } else if (s.startsWith('//')) {
+ scheme = '//'
+ rest = s.slice(2)
+ } else {
+ return { scheme: '', authority: '', path: s } // relative URL: all path
+ }
+ const pathOff = rest.indexOf('/')
+ if (pathOff === -1) {
+ return { scheme, authority: rest, path: '' }
+ }
+ return { scheme, authority: rest.slice(0, pathOff), path: rest.slice(pathOff) }
+}
+
+function isSafeSegment(seg: string): boolean {
+ return seg === '' || seg === '.' || seg === '..'
+}
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/anonymize/value.test.ts b/nodejs/src/ingestion/pipelines/sessionreplay/anonymize/value.test.ts
new file mode 100644
index 000000000000..57b777f7981a
--- /dev/null
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/anonymize/value.test.ts
@@ -0,0 +1,65 @@
+import { defaultAllowLists } from './default-dict'
+import { scrubConsolePlugin, scrubGenericField, scrubNetworkPlugin } from './value'
+
+describe('anonymize/value', () => {
+ const ctx = { allow: defaultAllowLists() }
+
+ describe('scrubGenericField', () => {
+ it('recurses objects/arrays, scrubs string leaves, leaves keys and non-strings alone', () => {
+ const owner = {
+ payload: {
+ a: 'Hello SecretName',
+ b: ['Hello SecretName', 42, true],
+ c: { url: 'https://example.com/user/abc/profile?token=secret' },
+ },
+ }
+ expect(scrubGenericField(ctx, owner, 'payload')).toBe(true)
+ expect(owner.payload.a).toBe('Hello **********')
+ expect(owner.payload.b[0]).toBe('Hello **********')
+ expect(owner.payload.b[1]).toBe(42)
+ expect(owner.payload.b[2]).toBe(true)
+ // http(s) string leaves are URL-scrubbed (denied query dropped), not text-scrubbed.
+ expect(owner.payload.c.url).toBe('https://example.com/user/[redacted]/profile')
+ })
+
+ it('scrubs a bare string field in place', () => {
+ const owner: Record<string, unknown> = { payload: 'Hello SecretName' }
+ expect(scrubGenericField(ctx, owner, 'payload')).toBe(true)
+ expect(owner.payload).toBe('Hello **********')
+ })
+
+ it('reports no change when nothing is scrubbable', () => {
+ const owner = { payload: { count: 1, ok: true } }
+ expect(scrubGenericField(ctx, owner, 'payload')).toBe(false)
+ })
+ })
+
+ describe('scrubNetworkPlugin', () => {
+ it('scrubs request header values', () => {
+ const owner = {
+ payload: { requests: [{ requestHeaders: { Authorization: 'Bearer SecretToken' } }] },
+ }
+ expect(scrubNetworkPlugin(ctx, owner, 'payload')).toBe(true)
+ expect(owner.payload.requests[0].requestHeaders.Authorization).toBe('Bearer ***********')
+ })
+
+ it('falls back to a generic scrub when the payload is not an object', () => {
+ const owner: Record<string, unknown> = { payload: 'Hello SecretName' }
+ expect(scrubNetworkPlugin(ctx, owner, 'payload')).toBe(true)
+ expect(owner.payload).toBe('Hello **********')
+ })
+
+ it('returns no change when the requests array is missing', () => {
+ const owner = { payload: { somethingElse: 1 } }
+ expect(scrubNetworkPlugin(ctx, owner, 'payload')).toBe(false)
+ })
+ })
+
+ describe('scrubConsolePlugin', () => {
+ it('falls back to a generic scrub when the payload is not an object', () => {
+ const owner: Record<string, unknown> = { payload: 'Hello SecretName' }
+ expect(scrubConsolePlugin(ctx, owner, 'payload')).toBe(true)
+ expect(owner.payload).toBe('Hello **********')
+ })
+ })
+})
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/anonymize/value.ts b/nodejs/src/ingestion/pipelines/sessionreplay/anonymize/value.ts
new file mode 100644
index 000000000000..5f560c281115
--- /dev/null
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/anonymize/value.ts
@@ -0,0 +1,121 @@
+/** Generic / network / console value scrubs over parsed JSON (Custom and Plugin payloads). */
+import { ScrubContext, isObject } from './config'
+import { ScrubResult, scrubText } from './text'
+import { scrubUrl } from './url'
+
+const NETWORK_BODY_FIELDS = ['requestBody', 'responseBody']
+const NETWORK_HEADER_FIELDS = ['requestHeaders', 'responseHeaders']
+const CONSOLE_FIELDS = ['payload', 'trace']
+
+type ScrubFn = (ctx: ScrubContext, s: string) => ScrubResult
+
+function looksLikeUrl(s: string): boolean {
+ return s.startsWith('http://') || s.startsWith('https://')
+}
+
+function scrubStringLeaf(ctx: ScrubContext, s: string): ScrubResult {
+ return looksLikeUrl(s) ? scrubUrl(ctx, s) : scrubText(ctx, s)
+}
+
+/** Scrub `container[key]` if it is a string, writing back on change. */
+function scrubFieldWith(ctx: ScrubContext, container: any, key: string | number, scrub: ScrubFn): boolean {
+ const value = container[key]
+ if (typeof value !== 'string') {
+ return false
+ }
+ const result = scrub(ctx, value)
+ if (result.changed) {
+ container[key] = result.value
+ return true
+ }
+ return false
+}
+
+/** Scrub `container[key]`: a string leaf (with writeback), otherwise recurse into it. */
+function scrubChild(ctx: ScrubContext, container: any, key: string | number): boolean {
+ const value = container[key]
+ if (typeof value !== 'string') {
+ return scrubValueInPlace(ctx, value)
+ }
+ const result = scrubStringLeaf(ctx, value)
+ if (result.changed) {
+ container[key] = result.value
+ return true
+ }
+ return false
+}
+
+/** Recursively scrub string leaves inside an array/object, mutating in place. */
+export function scrubValueInPlace(ctx: ScrubContext, value: unknown): boolean {
+ let changed = false
+ if (Array.isArray(value)) {
+ for (let i = 0; i < value.length; i++) {
+ changed = scrubChild(ctx, value, i) || changed
+ }
+ } else if (isObject(value)) {
+ for (const key of Object.keys(value)) {
+ changed = scrubChild(ctx, value, key) || changed
+ }
+ }
+ return changed
+}
+
+/** Generic scrub of `owner[key]`, handling both a string leaf and a container. */
+export function scrubGenericField(ctx: ScrubContext, owner: Record<string, unknown>, key: string): boolean {
+ return scrubChild(ctx, owner, key)
+}
+
+/**
+ * rrweb/network@1 payload at `owner[key]`: `{ requests: CapturedNetworkRequest[] }`.
+ * Per request: `name` is a Resource Timing URL (URL-scrub); request/response
+ * bodies and every header value are free text. Falls back to the generic field
+ * scrub if the shape is off.
+ */
+export function scrubNetworkPlugin(ctx: ScrubContext, owner: Record<string, unknown>, key: string): boolean {
+ const payload = owner[key]
+ if (!isObject(payload)) {
+ return scrubGenericField(ctx, owner, key)
+ }
+ const reqs = payload.requests
+ if (!Array.isArray(reqs)) {
+ return false
+ }
+ let changed = false
+ for (const req of reqs) {
+ if (!isObject(req)) {
+ continue
+ }
+ changed = scrubFieldWith(ctx, req, 'name', scrubUrl) || changed
+ for (const field of NETWORK_BODY_FIELDS) {
+ changed = scrubFieldWith(ctx, req, field, scrubText) || changed
+ }
+ for (const field of NETWORK_HEADER_FIELDS) {
+ const hdrs = req[field]
+ if (isObject(hdrs)) {
+ for (const k of Object.keys(hdrs)) {
+ changed = scrubFieldWith(ctx, hdrs, k, scrubText) || changed
+ }
+ }
+ }
+ }
+ return changed
+}
+
+/** rrweb/console@1 payload at `owner[key]`: `{ level, payload: string[], trace: string[] }`. */
+export function scrubConsolePlugin(ctx: ScrubContext, owner: Record<string, unknown>, key: string): boolean {
+ const payload = owner[key]
+ if (!isObject(payload)) {
+ return scrubGenericField(ctx, owner, key)
+ }
+ let changed = false
+ for (const field of CONSOLE_FIELDS) {
+ const arr = payload[field]
+ if (Array.isArray(arr)) {
+ for (let i = 0; i < arr.length; i++) {
+ // Console frames can hold URLs (stack traces); scrub URL-aware, not as plain text.
+ changed = scrubFieldWith(ctx, arr, i, scrubStringLeaf) || changed
+ }
+ }
+ }
+ return changed
+}
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/config.ts b/nodejs/src/ingestion/pipelines/sessionreplay/config.ts
index dd37495a6ba3..f084849c1aa5 100644
--- a/nodejs/src/ingestion/pipelines/sessionreplay/config.ts
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/config.ts
@@ -8,6 +8,7 @@ import {
KAFKA_SESSION_RECORDING_SNAPSHOT_ITEM_DLQ,
KAFKA_SESSION_RECORDING_SNAPSHOT_ITEM_EVENTS,
KAFKA_SESSION_RECORDING_SNAPSHOT_ITEM_OVERFLOW,
+ KAFKA_SESSION_REPLAY_ML_BLOCK_METADATA,
} from '~/common/config/kafka-topics'
import { isDevEnv } from '~/common/utils/env-utils'
import { INGESTION_DOWNSTREAM_PRODUCER, type IngestionDownstreamProducer } from '~/ingestion/common/producers'
@@ -173,6 +174,9 @@ export type SessionReplayOutputsConfig = {
INGESTION_SESSIONREPLAY_OUTPUT_SESSION_FEATURES_TOPIC: string
INGESTION_SESSIONREPLAY_OUTPUT_SESSION_FEATURES_PRODUCER: SessionReplayProducerName
+
+ INGESTION_SESSIONREPLAY_OUTPUT_ML_BLOCK_METADATA_TOPIC: string
+ INGESTION_SESSIONREPLAY_OUTPUT_ML_BLOCK_METADATA_PRODUCER: SessionReplayProducerName
}
export function getDefaultSessionReplayOutputsConfig(): SessionReplayOutputsConfig {
@@ -192,5 +196,7 @@ export function getDefaultSessionReplayOutputsConfig(): SessionReplayOutputsConf
INGESTION_SESSIONREPLAY_OUTPUT_REPLAY_EVENTS_PRODUCER: INGESTION_SESSIONREPLAY_PRODUCER,
INGESTION_SESSIONREPLAY_OUTPUT_SESSION_FEATURES_TOPIC: KAFKA_CLICKHOUSE_SESSION_REPLAY_FEATURES,
INGESTION_SESSIONREPLAY_OUTPUT_SESSION_FEATURES_PRODUCER: INGESTION_SESSIONREPLAY_PRODUCER,
+ INGESTION_SESSIONREPLAY_OUTPUT_ML_BLOCK_METADATA_TOPIC: KAFKA_SESSION_REPLAY_ML_BLOCK_METADATA,
+ INGESTION_SESSIONREPLAY_OUTPUT_ML_BLOCK_METADATA_PRODUCER: INGESTION_SESSIONREPLAY_PRODUCER,
}
}
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/consumer.ts b/nodejs/src/ingestion/pipelines/sessionreplay/consumer.ts
index 23e54b717be3..a47b0fb3855a 100644
--- a/nodejs/src/ingestion/pipelines/sessionreplay/consumer.ts
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/consumer.ts
@@ -1,4 +1,3 @@
-import { S3Client, S3ClientConfig } from '@aws-sdk/client-s3'
import { CODES, Message, TopicPartition, TopicPartitionOffset, features, librdkafkaVersion } from 'node-rdkafka'
import { buildIntegerMatcher } from '~/common/config/config'
@@ -18,6 +17,7 @@ import { IngestionConsumerConfig } from '~/ingestion/config'
import { BatchPipelineUnwrapper } from '~/ingestion/framework/batch-pipeline-unwrapper'
import { TopHog } from '~/ingestion/framework/tophog/tophog'
import {
+ SessionReplayPipelineConfig,
SessionReplayPipelineInput,
SessionReplayPipelineOutput,
createSessionReplayPipeline,
@@ -27,9 +27,13 @@ import { getBlockEncryptor } from '~/ingestion/pipelines/sessionreplay/shared/cr
import { SessionFeatureStore } from '~/ingestion/pipelines/sessionreplay/shared/features/session-feature-store'
import { getKeyStore } from '~/ingestion/pipelines/sessionreplay/shared/keystore'
import { MemoryCachedKeyStore } from '~/ingestion/pipelines/sessionreplay/shared/keystore/cache'
-import { SessionMetadataStore } from '~/ingestion/pipelines/sessionreplay/shared/metadata/session-metadata-store'
+import {
+ SessionMetadataSink,
+ SessionMetadataStore,
+} from '~/ingestion/pipelines/sessionreplay/shared/metadata/session-metadata-store'
import { ReplayEventsOutput, SessionFeaturesOutput } from '~/ingestion/pipelines/sessionreplay/shared/outputs'
import { RetentionService } from '~/ingestion/pipelines/sessionreplay/shared/retention/retention-service'
+import { buildSessionRecordingS3Client } from '~/ingestion/pipelines/sessionreplay/shared/s3-client'
import { TeamService } from '~/ingestion/pipelines/sessionreplay/shared/teams/team-service'
import { KeyStore, RecordingEncryptor } from '~/ingestion/pipelines/sessionreplay/shared/types'
import { HealthCheckResult, PluginServerService, RedisPool, ValueMatcher } from '~/types'
@@ -59,6 +63,27 @@ export type SessionRecordingIngesterConfig = SessionRecordingConfig &
'INGESTION_PIPELINE' | 'INGESTION_LANE'
>
+/** Builds the session replay pipeline for a deployment (default or ML mirror). */
+export type SessionReplayPipelineFactory = (
+ config: SessionReplayPipelineConfig
+) => BatchPipelineUnwrapper<
+ SessionReplayPipelineInput,
+ SessionReplayPipelineOutput,
+ { message: Message },
+ OverflowOutput
+>
+
+/** Collaborators a deployment can inject to vary ingester behavior; anything omitted uses the primary default. */
+export interface SessionRecordingIngesterCollaborators {
+ fileStorage?: SessionBatchFileStorage
+ metadataStore?: SessionMetadataSink
+ consoleLogStore?: SessionConsoleLogStore
+ featureStore?: SessionFeatureStore
+ keyStore?: KeyStore
+ encryptor?: RecordingEncryptor
+ createPipeline?: SessionReplayPipelineFactory
+}
+
export class SessionRecordingIngester {
kafkaConsumer: KafkaConsumer
topic: string
@@ -94,6 +119,7 @@ export class SessionRecordingIngester {
private readonly topHog: TopHog
private readonly keyStore: KeyStore
private readonly encryptor: RecordingEncryptor
+ private readonly createPipeline: SessionReplayPipelineFactory
constructor(
private config: SessionRecordingIngesterConfig,
@@ -108,7 +134,8 @@ export class SessionRecordingIngester {
| SessionFeaturesOutput
>,
redisPool: RedisPool,
- restrictionRedisPool: RedisPool
+ restrictionRedisPool: RedisPool,
+ collaborators: SessionRecordingIngesterCollaborators = {}
) {
this.topic = config.INGESTION_SESSION_REPLAY_CONSUMER_CONSUME_TOPIC
this.consumerGroupId = config.INGESTION_SESSION_REPLAY_CONSUMER_GROUP_ID
@@ -128,28 +155,8 @@ export class SessionRecordingIngester {
this.restrictionRedisPool = restrictionRedisPool
this.outputs = outputs
- let s3Client: S3Client | null = null
- if (
- config.SESSION_RECORDING_V2_S3_ENDPOINT &&
- config.SESSION_RECORDING_V2_S3_REGION &&
- config.SESSION_RECORDING_V2_S3_BUCKET &&
- config.SESSION_RECORDING_V2_S3_PREFIX
- ) {
- const s3Config: S3ClientConfig = {
- region: config.SESSION_RECORDING_V2_S3_REGION,
- endpoint: config.SESSION_RECORDING_V2_S3_ENDPOINT,
- forcePathStyle: true,
- }
-
- if (config.SESSION_RECORDING_V2_S3_ACCESS_KEY_ID && config.SESSION_RECORDING_V2_S3_SECRET_ACCESS_KEY) {
- s3Config.credentials = {
- accessKeyId: config.SESSION_RECORDING_V2_S3_ACCESS_KEY_ID,
- secretAccessKey: config.SESSION_RECORDING_V2_S3_SECRET_ACCESS_KEY,
- }
- }
-
- s3Client = new S3Client(s3Config)
- }
+ // Only needed to build the default file storage; skip it when storage is injected.
+ const s3Client = collaborators.fileStorage ? null : buildSessionRecordingS3Client(config)
this.topHog = new TopHog({
outputs,
@@ -167,20 +174,27 @@ export class SessionRecordingIngester {
const retentionService = new RetentionService(this.redisPool, this.teamService)
const offsetManager = new KafkaOffsetManager(this.commitOffsets.bind(this), this.topic)
- const metadataStore = new SessionMetadataStore(outputs)
- const consoleLogStore = new SessionConsoleLogStore(outputs, {
- messageLimit: this.config.SESSION_RECORDING_V2_CONSOLE_LOG_STORE_SYNC_BATCH_LIMIT,
- })
- const featureStore = new SessionFeatureStore(outputs, this.config.SESSION_RECORDING_FEATURES_ENABLED)
- this.fileStorage = s3Client
- ? new RetentionAwareStorage(
- s3Client,
- this.config.SESSION_RECORDING_V2_S3_BUCKET,
- this.config.SESSION_RECORDING_V2_S3_PREFIX,
- this.config.SESSION_RECORDING_V2_S3_TIMEOUT_MS,
- retentionService
- )
- : new BlackholeSessionBatchFileStorage()
+ this.createPipeline = collaborators.createPipeline ?? createSessionReplayPipeline
+ const metadataStore = collaborators.metadataStore ?? new SessionMetadataStore(outputs)
+ const consoleLogStore =
+ collaborators.consoleLogStore ??
+ new SessionConsoleLogStore(outputs, {
+ messageLimit: this.config.SESSION_RECORDING_V2_CONSOLE_LOG_STORE_SYNC_BATCH_LIMIT,
+ })
+ const featureStore =
+ collaborators.featureStore ??
+ new SessionFeatureStore(outputs, this.config.SESSION_RECORDING_FEATURES_ENABLED)
+ this.fileStorage =
+ collaborators.fileStorage ??
+ (s3Client
+ ? new RetentionAwareStorage(
+ s3Client,
+ this.config.SESSION_RECORDING_V2_S3_BUCKET,
+ this.config.SESSION_RECORDING_V2_S3_PREFIX,
+ this.config.SESSION_RECORDING_V2_S3_TIMEOUT_MS,
+ retentionService
+ )
+ : new BlackholeSessionBatchFileStorage())
const sessionTracker = new SessionTracker(
this.redisPool,
@@ -196,12 +210,15 @@ export class SessionRecordingIngester {
})
const region = config.SESSION_RECORDING_V2_S3_REGION ?? 'us-east-1'
- const keyStore = getKeyStore(retentionService, region, {
- kmsEndpoint: config.SESSION_RECORDING_KMS_ENDPOINT,
- dynamoDBEndpoint: config.SESSION_RECORDING_DYNAMODB_ENDPOINT,
- })
- this.keyStore = new MemoryCachedKeyStore(keyStore)
- this.encryptor = getBlockEncryptor(this.keyStore)
+ this.keyStore =
+ collaborators.keyStore ??
+ new MemoryCachedKeyStore(
+ getKeyStore(retentionService, region, {
+ kmsEndpoint: config.SESSION_RECORDING_KMS_ENDPOINT,
+ dynamoDBEndpoint: config.SESSION_RECORDING_DYNAMODB_ENDPOINT,
+ })
+ )
+ this.encryptor = collaborators.encryptor ?? getBlockEncryptor(this.keyStore)
this.sessionBatchManager = new SessionBatchManager({
maxBatchSizeBytes: this.config.SESSION_RECORDING_MAX_BATCH_SIZE_KB * 1024,
@@ -284,7 +301,7 @@ export class SessionRecordingIngester {
this.eventIngestionRestrictionManager = started.value
this.stopEventIngestionRestrictionManager = started.stop
- this.sessionReplayPipeline = createSessionReplayPipeline({
+ this.sessionReplayPipeline = this.createPipeline({
outputs: this.outputs,
eventIngestionRestrictionManager: this.eventIngestionRestrictionManager,
overflowEnabled: this.overflowEnabled(),
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/block-metadata-batcher.test.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/block-metadata-batcher.test.ts
new file mode 100644
index 000000000000..5f9df5e33b5e
--- /dev/null
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/block-metadata-batcher.test.ts
@@ -0,0 +1,110 @@
+import { Message } from 'node-rdkafka'
+
+import { BlockMetadataBatcher, OffsetStore } from './block-metadata-batcher'
+import { BlockMetadataParquetStore } from './block-metadata-parquet-store'
+import { MlBlockMetadataRow } from './block-metadata-row'
+
+const row = (sessionId: string): MlBlockMetadataRow => ({
+ session_id: sessionId,
+ team_id: 't1',
+ distinct_id: 'd1',
+ block_url: 's3://b/k?range=bytes=0-9',
+ block_s3_key: 's3://b/k',
+ block_byte_start: 0,
+ block_byte_end: 9,
+ block_length: 10,
+ first_ts_ms: 1_000,
+ last_ts_ms: 2_000,
+ event_count: 1,
+ message_count: 1,
+ click_count: 0,
+ keypress_count: 0,
+ mouse_activity_count: 0,
+ active_milliseconds: 0,
+ console_log_count: 0,
+ console_warn_count: 0,
+ console_error_count: 0,
+ size: 10,
+ first_url: null,
+ urls: [],
+ snapshot_source: null,
+ snapshot_library: null,
+ retention_period_days: null,
+})
+
+const msg = (offset: number, partition = 0, value: Buffer = Buffer.from(JSON.stringify(row(`s${offset}`)))): Message =>
+ ({ topic: 'ml_block_metadata', partition, offset, value }) as unknown as Message
+
+/** A message whose value parses as JSON but isn't a valid row, so the parser drops it (offsets still advance). */
+const skippedMsg = (offset: number, partition = 0): Message =>
+ msg(offset, partition, Buffer.from(JSON.stringify({ session_id: `s${offset}` })))
+
+describe('BlockMetadataBatcher', () => {
+ let store: jest.Mocked<BlockMetadataParquetStore>
+ let offsets: jest.Mocked<OffsetStore>
+
+ const makeBatcher = (flushIntervalMs: number, maxRows: number, startMs = 0): BlockMetadataBatcher =>
+ new BlockMetadataBatcher(store, offsets, { flushIntervalMs, maxRows }, startMs)
+
+ beforeEach(() => {
+ store = { write: jest.fn().mockResolvedValue(undefined) } as unknown as jest.Mocked<BlockMetadataParquetStore>
+ offsets = { offsetsStore: jest.fn() }
+ })
+
+ it('accumulates across batches and flushes once at the row cap', async () => {
+ const batcher = makeBatcher(60_000, 3)
+ await batcher.handleBatch([msg(0), msg(1)], 0)
+ expect(store.write).not.toHaveBeenCalled() // 2 < 3, still buffered
+
+ await batcher.handleBatch([msg(2), msg(3)], 0)
+ expect(store.write).toHaveBeenCalledTimes(1)
+ expect(store.write.mock.calls[0][0]).toHaveLength(4) // all four rolled into one object
+ })
+
+ it('flushes the buffer once the interval elapses, even on an empty poll', async () => {
+ const batcher = makeBatcher(1_000, 1_000_000, 0)
+ await batcher.handleBatch([msg(0)], 500)
+ expect(store.write).not.toHaveBeenCalled()
+
+ await batcher.handleBatch([], 1_000) // empty poll past the interval
+ expect(store.write).toHaveBeenCalledTimes(1)
+ expect(store.write.mock.calls[0][0]).toHaveLength(1)
+ })
+
+ it('stores the next offset per partition only after a successful write', async () => {
+ const batcher = makeBatcher(60_000, 2)
+ await batcher.handleBatch([msg(5, 0), msg(9, 1)], 0)
+
+ expect(offsets.offsetsStore).toHaveBeenCalledTimes(1)
+ const stored = offsets.offsetsStore.mock.calls[0][0].sort((a, b) => a.partition - b.partition)
+ expect(stored).toEqual([
+ { topic: 'ml_block_metadata', partition: 0, offset: 6 },
+ { topic: 'ml_block_metadata', partition: 1, offset: 10 },
+ ])
+ })
+
+ it('does not store offsets when the write fails (so the window replays)', async () => {
+ store.write.mockRejectedValueOnce(new Error('s3 down'))
+ const batcher = makeBatcher(60_000, 1)
+ await expect(batcher.handleBatch([msg(0)], 0)).rejects.toThrow('s3 down')
+ expect(offsets.offsetsStore).not.toHaveBeenCalled()
+ })
+
+ it('starts a fresh window after flushing', async () => {
+ const batcher = makeBatcher(1_000, 1_000_000, 0)
+ await batcher.handleBatch([msg(0)], 1_000) // flushes (interval elapsed)
+ expect(store.write).toHaveBeenCalledTimes(1)
+
+ await batcher.handleBatch([msg(1)], 1_500) // new window, interval not elapsed
+ expect(store.write).toHaveBeenCalledTimes(1)
+ })
+
+ it('commits offsets for a skipped-only batch without writing (so it does not replay forever)', async () => {
+ const batcher = makeBatcher(1_000, 1_000_000, 0)
+ await batcher.handleBatch([skippedMsg(7, 0)], 1_000) // all rows dropped by the parser, but offset must advance
+
+ expect(store.write).not.toHaveBeenCalled()
+ expect(offsets.offsetsStore).toHaveBeenCalledTimes(1)
+ expect(offsets.offsetsStore.mock.calls[0][0]).toEqual([{ topic: 'ml_block_metadata', partition: 0, offset: 8 }])
+ })
+})
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/block-metadata-batcher.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/block-metadata-batcher.ts
new file mode 100644
index 000000000000..f00b8433af2d
--- /dev/null
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/block-metadata-batcher.ts
@@ -0,0 +1,74 @@
+/** Accumulates block-metadata across Kafka batches and flushes one Parquet object per time/row threshold. */
+import { Message, TopicPartitionOffset } from 'node-rdkafka'
+
+import { findOffsetsToCommit } from '~/common/kafka/consumer/consumer-v1'
+
+import { parseBlockMetadataMessages } from './block-metadata-message'
+import { BlockMetadataParquetStore } from './block-metadata-parquet-store'
+import { MlBlockMetadataRow } from './block-metadata-row'
+
+/** The subset of the Kafka consumer the batcher needs: storing offsets it has durably written. */
+export interface OffsetStore {
+ offsetsStore(offsets: TopicPartitionOffset[]): void
+}
+
+export interface BlockMetadataBatcherOptions {
+ flushIntervalMs: number
+ maxRows: number
+}
+
+export class BlockMetadataBatcher {
+ private buffer: MlBlockMetadataRow[] = []
+ private pendingOffsets = new Map<string, TopicPartitionOffset>()
+ private lastFlushMs: number
+
+ constructor(
+ private readonly store: BlockMetadataParquetStore,
+ private readonly offsetStore: OffsetStore,
+ private readonly options: BlockMetadataBatcherOptions,
+ nowMs: number
+ ) {
+ this.lastFlushMs = nowMs
+ }
+
+ /** Buffers a batch and flushes once the buffer is old enough or large enough. */
+ public async handleBatch(messages: Message[], nowMs: number): Promise<void> {
+ for (const row of parseBlockMetadataMessages(messages)) {
+ this.buffer.push(row)
+ }
+ // Track the next offset to read per partition (highest seen + 1), accumulated across batches.
+ for (const offset of findOffsetsToCommit(messages)) {
+ this.pendingOffsets.set(`${offset.topic}:${offset.partition}`, offset)
+ }
+ if (this.shouldFlush(nowMs)) {
+ await this.flush(nowMs)
+ }
+ }
+
+ private shouldFlush(nowMs: number): boolean {
+ if (this.buffer.length >= this.options.maxRows) {
+ return true
+ }
+ // Flush on the interval whenever there's anything to commit — including offsets for batches that
+ // produced no rows (all skipped/malformed), so those don't replay forever.
+ const hasPending = this.buffer.length > 0 || this.pendingOffsets.size > 0
+ return hasPending && nowMs - this.lastFlushMs >= this.options.flushIntervalMs
+ }
+
+ /**
+ * Writes the buffered rows (if any) as one Parquet object, then stores the consumed offsets.
+ * Throws (without storing offsets) if the write fails, so the consumer replays the window (at-least-once).
+ */
+ public async flush(nowMs: number): Promise<void> {
+ this.lastFlushMs = nowMs
+ if (this.buffer.length > 0) {
+ await this.store.write(this.buffer)
+ this.buffer = []
+ }
+ if (this.pendingOffsets.size > 0) {
+ // Commit after the write lands so a failed write replays; skipped-only batches still advance here.
+ this.offsetStore.offsetsStore([...this.pendingOffsets.values()])
+ this.pendingOffsets.clear()
+ }
+ }
+}
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/block-metadata-columns.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/block-metadata-columns.ts
new file mode 100644
index 000000000000..e2bfb47a3954
--- /dev/null
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/block-metadata-columns.ts
@@ -0,0 +1,72 @@
+/** Single source of truth for the ML block-metadata columns: drives the Parquet schema, the row→record
+ * mapping (in parquet-writer.ts), and the poison-row validator below. Kept free of the Parquet dependency
+ * so the message-parsing path doesn't pull it in. */
+import { MlBlockMetadataRow } from './block-metadata-row'
+
+export type ParquetType = 'UTF8' | 'INT32' | 'INT64' | 'TIMESTAMP_MILLIS'
+
+export interface BlockMetadataColumn {
+ /** Field name on the JSON wire row (MlBlockMetadataRow). */
+ row: keyof MlBlockMetadataRow
+ /** Column name in the Parquet schema; differs from `row` only for the renamed timestamps. */
+ parquet: string
+ type: ParquetType
+ /** Nullable column — not required to be present or typed on a parsed row. */
+ optional?: boolean
+ /** Repeated UTF8 column (string array). */
+ repeated?: boolean
+}
+
+export const COLUMNS: BlockMetadataColumn[] = [
+ { row: 'session_id', parquet: 'session_id', type: 'UTF8' },
+ { row: 'team_id', parquet: 'team_id', type: 'UTF8' },
+ { row: 'distinct_id', parquet: 'distinct_id', type: 'UTF8' },
+ { row: 'block_url', parquet: 'block_url', type: 'UTF8' },
+ { row: 'block_s3_key', parquet: 'block_s3_key', type: 'UTF8' },
+ { row: 'block_byte_start', parquet: 'block_byte_start', type: 'INT64', optional: true },
+ { row: 'block_byte_end', parquet: 'block_byte_end', type: 'INT64', optional: true },
+ { row: 'block_length', parquet: 'block_length', type: 'INT64' },
+ { row: 'first_ts_ms', parquet: 'first_ts', type: 'TIMESTAMP_MILLIS' },
+ { row: 'last_ts_ms', parquet: 'last_ts', type: 'TIMESTAMP_MILLIS' },
+ { row: 'event_count', parquet: 'event_count', type: 'INT32' },
+ { row: 'message_count', parquet: 'message_count', type: 'INT32' },
+ { row: 'click_count', parquet: 'click_count', type: 'INT32' },
+ { row: 'keypress_count', parquet: 'keypress_count', type: 'INT32' },
+ { row: 'mouse_activity_count', parquet: 'mouse_activity_count', type: 'INT32' },
+ { row: 'active_milliseconds', parquet: 'active_milliseconds', type: 'INT32' },
+ { row: 'console_log_count', parquet: 'console_log_count', type: 'INT32' },
+ { row: 'console_warn_count', parquet: 'console_warn_count', type: 'INT32' },
+ { row: 'console_error_count', parquet: 'console_error_count', type: 'INT32' },
+ { row: 'size', parquet: 'size', type: 'INT64' },
+ { row: 'first_url', parquet: 'first_url', type: 'UTF8', optional: true },
+ { row: 'urls', parquet: 'urls', type: 'UTF8', repeated: true },
+ { row: 'snapshot_source', parquet: 'snapshot_source', type: 'UTF8', optional: true },
+ { row: 'snapshot_library', parquet: 'snapshot_library', type: 'UTF8', optional: true },
+ { row: 'retention_period_days', parquet: 'retention_period_days', type: 'INT32', optional: true },
+]
+
+/** Guards against a poison row crashing the Parquet writer (e.g. `BigInt(undefined)`); our producer always emits these. */
+export function isWellFormedRow(row: unknown): row is MlBlockMetadataRow {
+ if (typeof row !== 'object' || row === null) {
+ return false
+ }
+ const r = row as Record<string, unknown>
+ for (const col of COLUMNS) {
+ if (col.optional) {
+ continue
+ }
+ const value = r[col.row]
+ if (col.repeated) {
+ if (!Array.isArray(value)) {
+ return false
+ }
+ } else if (col.type === 'UTF8') {
+ if (typeof value !== 'string') {
+ return false
+ }
+ } else if (typeof value !== 'number' || !Number.isFinite(value)) {
+ return false
+ }
+ }
+ return true
+}
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/block-metadata-message.test.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/block-metadata-message.test.ts
new file mode 100644
index 000000000000..a90714845678
--- /dev/null
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/block-metadata-message.test.ts
@@ -0,0 +1,60 @@
+import { parseBlockMetadataMessages } from './block-metadata-message'
+import { MlBlockMetadataRow } from './block-metadata-row'
+
+const fullRow = (over: Partial<MlBlockMetadataRow> = {}): MlBlockMetadataRow => ({
+ session_id: 's1',
+ team_id: 't1',
+ distinct_id: 'd1',
+ block_url: 's3://b/k?range=bytes=0-9',
+ block_s3_key: 's3://b/k',
+ block_byte_start: 0,
+ block_byte_end: 9,
+ block_length: 10,
+ first_ts_ms: 1_000,
+ last_ts_ms: 2_000,
+ event_count: 3,
+ message_count: 1,
+ click_count: 0,
+ keypress_count: 0,
+ mouse_activity_count: 0,
+ active_milliseconds: 0,
+ console_log_count: 0,
+ console_warn_count: 0,
+ console_error_count: 0,
+ size: 100,
+ first_url: null,
+ urls: [],
+ snapshot_source: null,
+ snapshot_library: null,
+ retention_period_days: null,
+ ...over,
+})
+
+const msg = (value: unknown): { value: Buffer | null } => ({
+ value: value === null ? null : Buffer.from(typeof value === 'string' ? value : JSON.stringify(value)),
+})
+
+describe('parseBlockMetadataMessages', () => {
+ it('parses well-formed rows and preserves their fields', () => {
+ const rows = parseBlockMetadataMessages([msg(fullRow({ session_id: 'a', event_count: 3 })), msg(fullRow())])
+ expect(rows).toHaveLength(2)
+ expect(rows[0]).toMatchObject({ session_id: 'a', event_count: 3 })
+ })
+
+ it('skips null values and malformed JSON without throwing', () => {
+ const rows = parseBlockMetadataMessages([msg(null), msg('not json{'), msg(fullRow({ session_id: 'ok' }))])
+ expect(rows).toHaveLength(1)
+ expect(rows[0].session_id).toBe('ok')
+ })
+
+ it('skips shape-invalid rows (poison-pill guard) without throwing', () => {
+ const rows = parseBlockMetadataMessages([
+ msg({ session_id: 'a', event_count: 3 }), // missing required numeric fields + urls
+ msg(fullRow({ event_count: 'oops' as unknown as number })), // wrong type
+ msg(fullRow({ urls: 'not-an-array' as unknown as string[] })),
+ msg(fullRow({ session_id: 'good' })),
+ ])
+ expect(rows).toHaveLength(1)
+ expect(rows[0].session_id).toBe('good')
+ })
+})
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/block-metadata-message.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/block-metadata-message.ts
new file mode 100644
index 000000000000..575ae641d3c7
--- /dev/null
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/block-metadata-message.ts
@@ -0,0 +1,29 @@
+/** Parses block-metadata Kafka messages (JSON rows produced by MlBlockMetadataSink) back into rows. */
+import { parseJSON } from '~/common/utils/json-parse'
+import { logger } from '~/common/utils/logger'
+
+import { isWellFormedRow } from './block-metadata-columns'
+import { MlBlockMetadataRow } from './block-metadata-row'
+
+export function parseBlockMetadataMessages(messages: readonly { value: Buffer | null }[]): MlBlockMetadataRow[] {
+ const rows: MlBlockMetadataRow[] = []
+ for (const message of messages) {
+ if (!message.value) {
+ continue
+ }
+ let row: unknown
+ try {
+ row = parseJSON(message.value.toString('utf8'))
+ } catch (error) {
+ // Skip malformed rows rather than wedge the partition; they're rare and non-fatal for training data.
+ logger.warn('🪶', 'ml_parquet_metadata_parse_failed', { error: String(error) })
+ continue
+ }
+ if (!isWellFormedRow(row)) {
+ logger.warn('🪶', 'ml_parquet_metadata_row_invalid')
+ continue
+ }
+ rows.push(row)
+ }
+ return rows
+}
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/block-metadata-parquet-store.test.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/block-metadata-parquet-store.test.ts
new file mode 100644
index 000000000000..3cf22d2f9f82
--- /dev/null
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/block-metadata-parquet-store.test.ts
@@ -0,0 +1,94 @@
+import { PutObjectCommandInput, S3Client } from '@aws-sdk/client-s3'
+import { ParquetReader } from '@dsnp/parquetjs'
+
+import { BlockMetadataParquetStore } from './block-metadata-parquet-store'
+import { MlBlockMetadataRow } from './block-metadata-row'
+
+const row = (sessionId: string, teamId: string): MlBlockMetadataRow => ({
+ session_id: sessionId,
+ team_id: teamId,
+ distinct_id: 'did-pseudo',
+ block_url: `s3://ml-bucket/key-${sessionId}?range=bytes=0-9`,
+ block_s3_key: `s3://ml-bucket/key-${sessionId}`,
+ block_byte_start: 0,
+ block_byte_end: 9,
+ block_length: 10,
+ first_ts_ms: 1_000,
+ last_ts_ms: 2_000,
+ event_count: 4,
+ message_count: 2,
+ click_count: 1,
+ keypress_count: 0,
+ mouse_activity_count: 1,
+ active_milliseconds: 500,
+ console_log_count: 0,
+ console_warn_count: 0,
+ console_error_count: 0,
+ size: 100,
+ first_url: 'https://x/[redacted]',
+ urls: ['https://x/[redacted]'],
+ snapshot_source: 'web',
+ snapshot_library: 'web',
+ retention_period_days: 30,
+})
+
+async function readRows(body: PutObjectCommandInput['Body']): Promise<Record<string, any>[]> {
+ const reader = await ParquetReader.openBuffer(body as Buffer)
+ const cursor = reader.getCursor()
+ const rows: Record<string, any>[] = []
+ let r: unknown
+ while ((r = await cursor.next())) {
+ rows.push(r as Record<string, any>)
+ }
+ await reader.close()
+ return rows
+}
+
+describe('BlockMetadataParquetStore', () => {
+ let puts: PutObjectCommandInput[]
+ let s3: S3Client
+
+ beforeEach(() => {
+ puts = []
+ s3 = {
+ send: jest.fn((cmd: { input: PutObjectCommandInput }) => {
+ puts.push(cmd.input)
+ return Promise.resolve({})
+ }),
+ } as unknown as S3Client
+ })
+
+ it('writes one dt-partitioned Parquet object that round-trips', async () => {
+ const store = new BlockMetadataParquetStore(s3, 'ml-bucket', 'block-metadata', 'pod-1')
+ await store.write([row('s1', 't1'), row('s2', 't1')])
+
+ expect(puts).toHaveLength(1)
+ expect(puts[0].Bucket).toBe('ml-bucket')
+ expect(puts[0].Key).toMatch(/^block-metadata\/dt=\d{4}-\d{2}-\d{2}\/part-pod-1-\d+-\d+\.parquet$/)
+
+ const rows = await readRows(puts[0].Body)
+ expect(rows).toHaveLength(2)
+ expect(Number(rows[0].block_byte_end)).toBe(9)
+ expect(rows[0].snapshot_source).toBe('web')
+ })
+
+ it('sorts rows by (team_id, session_id)', async () => {
+ const store = new BlockMetadataParquetStore(s3, 'ml-bucket', 'block-metadata', 'pod-1')
+ await store.write([row('s9', 't3'), row('s1', 't1'), row('s5', 't2'), row('s2', 't1')])
+ const rows = await readRows(puts[0].Body)
+ const keys = rows.map((r) => `${r.team_id}|${r.session_id}`)
+ expect(keys).toEqual([...keys].sort())
+ })
+
+ it('writes nothing for an empty batch', async () => {
+ const store = new BlockMetadataParquetStore(s3, 'ml-bucket', 'block-metadata', 'pod-1')
+ await store.write([])
+ expect(puts).toHaveLength(0)
+ })
+
+ it('propagates upload failures so the caller can replay from Kafka', async () => {
+ s3 = { send: jest.fn(() => Promise.reject(new Error('s3 down'))) } as unknown as S3Client
+ const store = new BlockMetadataParquetStore(s3, 'ml-bucket', 'block-metadata', 'pod-1')
+ await expect(store.write([row('s1', 't1')])).rejects.toThrow('s3 down')
+ })
+})
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/block-metadata-parquet-store.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/block-metadata-parquet-store.ts
new file mode 100644
index 000000000000..8a8f16f25fbc
--- /dev/null
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/block-metadata-parquet-store.ts
@@ -0,0 +1,62 @@
+/** Sorts, encodes, and uploads a batch of block-metadata rows as one dt-partitioned Parquet object in the ML bucket. */
+import { PutObjectCommand, S3Client } from '@aws-sdk/client-s3'
+import { randomUUID } from 'crypto'
+
+import { logger } from '~/common/utils/logger'
+
+import { MlBlockMetadataRow } from './block-metadata-row'
+import { rowsToParquetBuffer } from './parquet-writer'
+
+const cmp = (a: string, b: string): number => (a < b ? -1 : a > b ? 1 : 0)
+
+export class BlockMetadataParquetStore {
+ private seq = 0
+ private readonly nodeId: string
+
+ constructor(
+ private readonly s3Client: S3Client,
+ private readonly bucket: string,
+ private readonly prefix: string,
+ nodeId?: string
+ ) {
+ // Stable per-pod id so concurrent writers can't collide on a key.
+ this.nodeId = nodeId || process.env.HOSTNAME || randomUUID().slice(0, 8)
+ }
+
+ /** Writes the rows as one Parquet object. Throws on failure so the caller can replay from Kafka (at-least-once). */
+ public async write(rows: MlBlockMetadataRow[]): Promise<void> {
+ if (rows.length === 0) {
+ return
+ }
+ // Sorting clusters a recording's blocks together for better compression and reads.
+ rows.sort((a, b) => cmp(a.team_id, b.team_id) || cmp(a.session_id, b.session_id))
+ const body = await rowsToParquetBuffer(rows)
+ const key = this.objectKey(minEventDate(rows))
+ await this.s3Client.send(
+ new PutObjectCommand({
+ Bucket: this.bucket,
+ Key: key,
+ Body: body,
+ ContentType: 'application/vnd.apache.parquet',
+ })
+ )
+ logger.info('🪶', 'ml_parquet_metadata_written', { rows: rows.length, bytes: body.length, key })
+ }
+
+ /** Partition by event date (`dt=`), but keep a write-time stamp + seq + pod id in the name for uniqueness. */
+ private objectKey(dt: string): string {
+ this.seq += 1
+ return `${this.prefix}/dt=${dt}/part-${this.nodeId}-${Date.now()}-${this.seq}.parquet`
+ }
+}
+
+/** Partition by the earliest event time in the batch (rows can span a window, so the min wins). */
+function minEventDate(rows: MlBlockMetadataRow[]): string {
+ let minMs = rows[0].first_ts_ms
+ for (const row of rows) {
+ if (row.first_ts_ms < minMs) {
+ minMs = row.first_ts_ms
+ }
+ }
+ return new Date(minMs).toISOString().slice(0, 10)
+}
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/block-metadata-row.test.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/block-metadata-row.test.ts
new file mode 100644
index 000000000000..8e7334801325
--- /dev/null
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/block-metadata-row.test.ts
@@ -0,0 +1,66 @@
+import { DateTime } from 'luxon'
+
+import {
+ SessionBlockMetadata,
+ createNoopBlockMetadata,
+} from '~/ingestion/pipelines/sessionreplay/shared/metadata/session-block-metadata'
+
+import { parseBlockUrl, toBlockMetadataRow } from './block-metadata-row'
+import { PSEUDONYM_SESSION, PSEUDONYM_TEAM, pseudonymize } from './pseudonymize'
+
+const SECRET = 'test-secret'
+
+const block = (over: Partial<SessionBlockMetadata> = {}): SessionBlockMetadata => ({
+ ...createNoopBlockMetadata('sess-1', 7),
+ distinctId: '[email protected]',
+ blockUrl: 's3://ml-bucket/session_recordings/key-abc?range=bytes=100-250',
+ startDateTime: DateTime.fromMillis(1_000),
+ endDateTime: DateTime.fromMillis(2_000),
+ eventCount: 5,
+ messageCount: 3,
+ urls: ['https://a/[redacted]'],
+ ...over,
+})
+
+describe('ml-mirror block-metadata-row', () => {
+ describe('parseBlockUrl', () => {
+ it('splits the object key from the byte range', () => {
+ expect(parseBlockUrl('s3://b/key?range=bytes=100-250')).toEqual({ key: 's3://b/key', start: 100, end: 250 })
+ })
+
+ it('returns null range when there is no range marker', () => {
+ expect(parseBlockUrl('s3://b/key')).toEqual({ key: 's3://b/key', start: null, end: null })
+ })
+ })
+
+ describe('toBlockMetadataRow', () => {
+ it('pseudonymizes ids and never carries the raw values', () => {
+ const row = toBlockMetadataRow(block(), SECRET)!
+ expect(row.team_id).toBe(pseudonymize(SECRET, PSEUDONYM_TEAM, '7'))
+ expect(row.session_id).toBe(pseudonymize(SECRET, PSEUDONYM_SESSION, 'sess-1'))
+ expect(row.distinct_id).not.toContain('[email protected]')
+ expect(row.session_id).not.toBe('sess-1')
+ })
+
+ it('maps block fields and the parsed byte range', () => {
+ const row = toBlockMetadataRow(block(), SECRET)!
+ expect(row).toMatchObject({
+ block_s3_key: 's3://ml-bucket/session_recordings/key-abc',
+ block_byte_start: 100,
+ block_byte_end: 250,
+ first_ts_ms: 1_000,
+ last_ts_ms: 2_000,
+ event_count: 5,
+ message_count: 3,
+ urls: ['https://a/[redacted]'],
+ })
+ })
+
+ it.each([
+ ['a deletion marker', block({ isDeleted: true })],
+ ['a block with no url', block({ blockUrl: null })],
+ ])('returns null for %s', (_label, b) => {
+ expect(toBlockMetadataRow(b, SECRET)).toBeNull()
+ })
+ })
+})
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/block-metadata-row.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/block-metadata-row.ts
new file mode 100644
index 000000000000..26f362b270a7
--- /dev/null
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/block-metadata-row.ts
@@ -0,0 +1,82 @@
+/** One anonymized block's metadata as a flat row for the ML Parquet dataset; ids are pseudonyms. */
+import { SessionBlockMetadata } from '~/ingestion/pipelines/sessionreplay/shared/metadata/session-block-metadata'
+
+import { PSEUDONYM_DISTINCT_ID, PSEUDONYM_SESSION, PSEUDONYM_TEAM, pseudonymize } from './pseudonymize'
+
+export interface MlBlockMetadataRow {
+ session_id: string
+ team_id: string
+ distinct_id: string
+ block_url: string
+ block_s3_key: string
+ block_byte_start: number | null
+ block_byte_end: number | null
+ block_length: number
+ first_ts_ms: number
+ last_ts_ms: number
+ event_count: number
+ message_count: number
+ click_count: number
+ keypress_count: number
+ mouse_activity_count: number
+ active_milliseconds: number
+ console_log_count: number
+ console_warn_count: number
+ console_error_count: number
+ size: number
+ first_url: string | null
+ urls: string[]
+ snapshot_source: string | null
+ snapshot_library: string | null
+ retention_period_days: number | null
+}
+
+const RANGE_MARKER = '?range=bytes='
+
+/** Splits a `s3://bucket/key?range=bytes=start-end` block URL into the object key and byte range. */
+export function parseBlockUrl(blockUrl: string): { key: string; start: number | null; end: number | null } {
+ const idx = blockUrl.indexOf(RANGE_MARKER)
+ if (idx < 0) {
+ return { key: blockUrl, start: null, end: null }
+ }
+ const key = blockUrl.slice(0, idx)
+ const [startStr, endStr] = blockUrl.slice(idx + RANGE_MARKER.length).split('-')
+ const start = Number(startStr)
+ const end = Number(endStr)
+ return { key, start: Number.isFinite(start) ? start : null, end: Number.isFinite(end) ? end : null }
+}
+
+/** Maps a flush's block metadata to a row, or null for deletion/no-op markers that reference no block. */
+export function toBlockMetadataRow(block: SessionBlockMetadata, secret: string | Buffer): MlBlockMetadataRow | null {
+ if (!block.blockUrl || block.isDeleted) {
+ return null
+ }
+ const { key, start, end } = parseBlockUrl(block.blockUrl)
+ return {
+ session_id: pseudonymize(secret, PSEUDONYM_SESSION, block.sessionId),
+ team_id: pseudonymize(secret, PSEUDONYM_TEAM, String(block.teamId)),
+ distinct_id: pseudonymize(secret, PSEUDONYM_DISTINCT_ID, block.distinctId),
+ block_url: block.blockUrl,
+ block_s3_key: key,
+ block_byte_start: start,
+ block_byte_end: end,
+ block_length: block.blockLength,
+ first_ts_ms: block.startDateTime.toMillis(),
+ last_ts_ms: block.endDateTime.toMillis(),
+ event_count: block.eventCount,
+ message_count: block.messageCount,
+ click_count: block.clickCount,
+ keypress_count: block.keypressCount,
+ mouse_activity_count: block.mouseActivityCount,
+ active_milliseconds: block.activeMilliseconds,
+ console_log_count: block.consoleLogCount,
+ console_warn_count: block.consoleWarnCount,
+ console_error_count: block.consoleErrorCount,
+ size: block.size,
+ first_url: block.firstUrl,
+ urls: block.urls ?? [],
+ snapshot_source: block.snapshotSource,
+ snapshot_library: block.snapshotLibrary,
+ retention_period_days: block.retentionPeriodDays,
+ }
+}
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/config.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/config.ts
new file mode 100644
index 000000000000..d58123a51279
--- /dev/null
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/config.ts
@@ -0,0 +1,38 @@
+/** ML-mirror-specific config knobs, layered on top of the shared session-recording config. */
+export type MlMirrorConfig = {
+ /** S3 key prefix under the bucket for the block-metadata Parquet dataset (used by the sink). */
+ SESSION_RECORDING_ML_METADATA_PREFIX: string
+ /** Optional S3 key of the `{ text, url }` allow-list document; empty → in-binary defaults. */
+ SESSION_RECORDING_ML_ALLOW_LIST_S3_KEY: string
+ /** Plaintext HMAC secret to pseudonymize ids; for local dev only — prod uses the KMS-wrapped key below. */
+ SESSION_RECORDING_ML_PSEUDONYM_SECRET: string
+ /** Base64 KMS-encrypted pseudonym key (envelope); decrypted once at startup, never persisted. Preferred over the plaintext secret. */
+ SESSION_RECORDING_ML_PSEUDONYM_WRAPPED_KEY: string
+ /** AWS region for the KMS Decrypt call; empty → the SDK default credential/region chain. */
+ SESSION_RECORDING_ML_PSEUDONYM_KMS_REGION: string
+ /** Expected key fingerprint; if set, startup fails when the resolved key's fingerprint differs (enforces never-rotate). */
+ SESSION_RECORDING_ML_PSEUDONYM_KEY_FINGERPRINT: string
+ /** Consumer group id for the Parquet-sink deployment that drains the metadata topic. */
+ SESSION_RECORDING_ML_PARQUET_SINK_GROUP_ID: string
+ /**
+ * The sink rolls up rows and writes one Parquet object at least this often (fewer, larger S3 objects).
+ * Must stay comfortably below `max.poll.interval.ms` (300s) — the flush runs inline on the poll loop.
+ */
+ SESSION_RECORDING_ML_PARQUET_FLUSH_INTERVAL_MS: number
+ /** Row cap that forces a flush before the interval elapses (bounds the sink's memory). */
+ SESSION_RECORDING_ML_PARQUET_MAX_ROWS: number
+}
+
+export function getDefaultMlMirrorConfig(): MlMirrorConfig {
+ return {
+ SESSION_RECORDING_ML_METADATA_PREFIX: 'block-metadata',
+ SESSION_RECORDING_ML_ALLOW_LIST_S3_KEY: '',
+ SESSION_RECORDING_ML_PSEUDONYM_SECRET: '',
+ SESSION_RECORDING_ML_PSEUDONYM_WRAPPED_KEY: '',
+ SESSION_RECORDING_ML_PSEUDONYM_KMS_REGION: '',
+ SESSION_RECORDING_ML_PSEUDONYM_KEY_FINGERPRINT: '',
+ SESSION_RECORDING_ML_PARQUET_SINK_GROUP_ID: 'session-replay-ml-parquet-sink',
+ SESSION_RECORDING_ML_PARQUET_FLUSH_INTERVAL_MS: 60 * 1000,
+ SESSION_RECORDING_ML_PARQUET_MAX_ROWS: 250_000,
+ }
+}
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/metadata-roundtrip.test.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/metadata-roundtrip.test.ts
new file mode 100644
index 000000000000..89ee1964503c
--- /dev/null
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/metadata-roundtrip.test.ts
@@ -0,0 +1,104 @@
+import { PutObjectCommandInput, S3Client } from '@aws-sdk/client-s3'
+import { ParquetReader } from '@dsnp/parquetjs'
+import { DateTime } from 'luxon'
+import { Message } from 'node-rdkafka'
+
+import { IngestionOutputs } from '~/common/outputs/ingestion-outputs'
+import {
+ SessionBlockMetadata,
+ createNoopBlockMetadata,
+} from '~/ingestion/pipelines/sessionreplay/shared/metadata/session-block-metadata'
+import { MlBlockMetadataOutput } from '~/ingestion/pipelines/sessionreplay/shared/outputs'
+
+import { BlockMetadataBatcher, OffsetStore } from './block-metadata-batcher'
+import { BlockMetadataParquetStore } from './block-metadata-parquet-store'
+import { MlBlockMetadataSink } from './ml-block-metadata-sink'
+import { PSEUDONYM_DISTINCT_ID, PSEUDONYM_SESSION, PSEUDONYM_TEAM, pseudonymize } from './pseudonymize'
+
+const SECRET = 'roundtrip-secret'
+
+const block = (sessionId: string, teamId: number, distinctId: string): SessionBlockMetadata => ({
+ ...createNoopBlockMetadata(sessionId, teamId),
+ distinctId,
+ blockUrl: `s3://ml-bucket/key-${sessionId}?range=bytes=10-42`,
+ startDateTime: DateTime.fromMillis(1_700_000_000_000),
+ endDateTime: DateTime.fromMillis(1_700_000_005_000),
+ eventCount: 5,
+ messageCount: 2,
+ clickCount: 1,
+ urls: ['https://example.com/[redacted]'],
+ snapshotSource: 'web',
+})
+
+async function readRows(body: PutObjectCommandInput['Body']): Promise<Record<string, any>[]> {
+ const reader = await ParquetReader.openBuffer(body as Buffer)
+ const cursor = reader.getCursor()
+ const rows: Record<string, any>[] = []
+ let row: unknown
+ while ((row = await cursor.next())) {
+ rows.push(row as Record<string, any>)
+ }
+ await reader.close()
+ return rows
+}
+
+// End-to-end across both new deployments' metadata path: the mirror's producer serializes block metadata to the
+// Kafka topic, and the sink's parser → batcher → Parquet store turns those exact bytes into an object in the ML bucket.
+describe('ML metadata producer → sink round-trip', () => {
+ it('pseudonymizes on the way out and recovers the same rows from the written Parquet', async () => {
+ // --- Mirror (producer) side: block metadata → Kafka message bytes ---
+ const produced: { key?: unknown; value: Buffer | null }[] = []
+ const outputs = {
+ queueMessages: jest.fn((_output, messages) => {
+ produced.push(...messages)
+ return Promise.resolve()
+ }),
+ } as unknown as IngestionOutputs<MlBlockMetadataOutput>
+
+ await new MlBlockMetadataSink(outputs, SECRET).storeSessionBlocks([
+ block('sess-A', 1, 'person-1'),
+ block('sess-B', 2, 'person-2'),
+ ])
+ expect(produced).toHaveLength(2)
+
+ // --- Sink (consumer) side: those exact bytes → parser → batcher → Parquet in S3 ---
+ const puts: PutObjectCommandInput[] = []
+ const s3 = {
+ send: jest.fn((cmd: { input: PutObjectCommandInput }) => {
+ puts.push(cmd.input)
+ return Promise.resolve({})
+ }),
+ } as unknown as S3Client
+ const store = new BlockMetadataParquetStore(s3, 'ml-bucket', 'block-metadata', 'pod-1')
+ const offsetStore: OffsetStore = { offsetsStore: jest.fn() }
+ const batcher = new BlockMetadataBatcher(store, offsetStore, { flushIntervalMs: 60_000, maxRows: 1_000 }, 0)
+
+ const messages = produced.map(
+ (m, i) => ({ topic: 'ml_block_metadata', partition: 0, offset: i, value: m.value }) as Message
+ )
+ await batcher.handleBatch(messages, 0)
+ await batcher.flush(1) // force the window out
+
+ expect(puts).toHaveLength(1)
+ const rows = await readRows(puts[0].Body)
+ expect(rows).toHaveLength(2)
+
+ const bySession = new Map(rows.map((r) => [r.session_id, r]))
+ const a = bySession.get(pseudonymize(SECRET, PSEUDONYM_SESSION, 'sess-A'))!
+ expect(a).toBeDefined()
+ expect(a.team_id).toBe(pseudonymize(SECRET, PSEUDONYM_TEAM, '1'))
+ expect(a.distinct_id).toBe(pseudonymize(SECRET, PSEUDONYM_DISTINCT_ID, 'person-1'))
+ // Raw ids never survive the trip (BigInt-safe stringify, since INT64 fields read back as bigint).
+ expect(a.session_id).not.toBe('sess-A')
+ const serialized = JSON.stringify(a, (_key, value) => (typeof value === 'bigint' ? value.toString() : value))
+ expect(serialized).not.toContain('person-1')
+ // Real block fields round-trip through JSON → Parquet → read.
+ expect(Number(a.block_byte_start)).toBe(10)
+ expect(Number(a.block_byte_end)).toBe(42)
+ expect(a.event_count).toBe(5)
+ expect(a.urls).toEqual(['https://example.com/[redacted]'])
+
+ // Offsets advanced only after the write landed.
+ expect(offsetStore.offsetsStore).toHaveBeenCalledWith([{ topic: 'ml_block_metadata', partition: 0, offset: 2 }])
+ })
+})
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/ml-block-metadata-sink.test.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/ml-block-metadata-sink.test.ts
new file mode 100644
index 000000000000..8b4fc8750d5a
--- /dev/null
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/ml-block-metadata-sink.test.ts
@@ -0,0 +1,67 @@
+import { DateTime } from 'luxon'
+
+import { IngestionOutputs } from '~/common/outputs/ingestion-outputs'
+import { parseJSON } from '~/common/utils/json-parse'
+import {
+ SessionBlockMetadata,
+ createNoopBlockMetadata,
+} from '~/ingestion/pipelines/sessionreplay/shared/metadata/session-block-metadata'
+import { ML_BLOCK_METADATA_OUTPUT, MlBlockMetadataOutput } from '~/ingestion/pipelines/sessionreplay/shared/outputs'
+
+import { MlBlockMetadataSink } from './ml-block-metadata-sink'
+import { PSEUDONYM_SESSION, pseudonymize } from './pseudonymize'
+
+const SECRET = 'test-secret'
+
+const block = (sessionId: string, teamId: number, over: Partial<SessionBlockMetadata> = {}): SessionBlockMetadata => ({
+ ...createNoopBlockMetadata(sessionId, teamId),
+ distinctId: '[email protected]',
+ blockUrl: `s3://ml-bucket/key-${sessionId}?range=bytes=0-9`,
+ startDateTime: DateTime.fromMillis(1_000),
+ endDateTime: DateTime.fromMillis(2_000),
+ eventCount: 4,
+ urls: ['https://x/[redacted]'],
+ ...over,
+})
+
+describe('MlBlockMetadataSink', () => {
+ let outputs: jest.Mocked<IngestionOutputs<MlBlockMetadataOutput>>
+ let sink: MlBlockMetadataSink
+
+ beforeEach(() => {
+ outputs = { queueMessages: jest.fn().mockResolvedValue(undefined) } as unknown as jest.Mocked<
+ IngestionOutputs<MlBlockMetadataOutput>
+ >
+ sink = new MlBlockMetadataSink(outputs, SECRET)
+ })
+
+ it('produces pseudonymized rows to the ML topic, keyed by the session pseudonym', async () => {
+ await sink.storeSessionBlocks([block('s1', 7)])
+
+ expect(outputs.queueMessages).toHaveBeenCalledTimes(1)
+ const [output, messages] = outputs.queueMessages.mock.calls[0]
+ expect(output).toBe(ML_BLOCK_METADATA_OUTPUT)
+ expect(messages[0].key).toBe(pseudonymize(SECRET, PSEUDONYM_SESSION, 's1'))
+
+ const row = parseJSON((messages[0].value as Buffer).toString())
+ expect(row.session_id).toBe(pseudonymize(SECRET, PSEUDONYM_SESSION, 's1'))
+ expect(row.session_id).not.toBe('s1')
+ expect(row.distinct_id).not.toContain('[email protected]')
+ expect(row.block_byte_end).toBe(9)
+ })
+
+ it('skips deletion and url-less markers', async () => {
+ await sink.storeSessionBlocks([
+ block('s1', 1),
+ block('s2', 1, { isDeleted: true }),
+ block('s3', 1, { blockUrl: null }),
+ ])
+ const [, messages] = outputs.queueMessages.mock.calls[0]
+ expect(messages).toHaveLength(1)
+ })
+
+ it('still calls queueMessages for an all-skipped batch', async () => {
+ await sink.storeSessionBlocks([block('s1', 1, { isDeleted: true })])
+ expect(outputs.queueMessages).toHaveBeenCalledWith(ML_BLOCK_METADATA_OUTPUT, [])
+ })
+})
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/ml-block-metadata-sink.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/ml-block-metadata-sink.ts
new file mode 100644
index 000000000000..83a21dbba3fb
--- /dev/null
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/ml-block-metadata-sink.ts
@@ -0,0 +1,31 @@
+/** Produces anonymized, pseudonymized block metadata to the ML Kafka topic for the Parquet sink to consume. */
+import { IngestionOutputs } from '~/common/outputs/ingestion-outputs'
+import {
+ KafkaMetadataSink,
+ MetadataRecord,
+} from '~/ingestion/pipelines/sessionreplay/shared/metadata/kafka-metadata-sink'
+import { SessionBlockMetadata } from '~/ingestion/pipelines/sessionreplay/shared/metadata/session-block-metadata'
+import { ML_BLOCK_METADATA_OUTPUT, MlBlockMetadataOutput } from '~/ingestion/pipelines/sessionreplay/shared/outputs'
+
+import { toBlockMetadataRow } from './block-metadata-row'
+
+export class MlBlockMetadataSink extends KafkaMetadataSink<MlBlockMetadataOutput> {
+ constructor(
+ outputs: IngestionOutputs<MlBlockMetadataOutput>,
+ private readonly pseudonymSecret: string | Buffer
+ ) {
+ super(outputs, ML_BLOCK_METADATA_OUTPUT)
+ }
+
+ protected toRecords(blocks: SessionBlockMetadata[]): MetadataRecord[] {
+ const records: MetadataRecord[] = []
+ for (const block of blocks) {
+ const row = toBlockMetadataRow(block, this.pseudonymSecret)
+ if (row) {
+ // Keyed by the pseudonymous session id so a recording's blocks land on one partition.
+ records.push({ key: row.session_id, value: row })
+ }
+ }
+ return records
+ }
+}
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/ml-mirror-pipeline.test.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/ml-mirror-pipeline.test.ts
new file mode 100644
index 000000000000..4c1ad6c3d0db
--- /dev/null
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/ml-mirror-pipeline.test.ts
@@ -0,0 +1,211 @@
+import { DateTime } from 'luxon'
+import { Message } from 'node-rdkafka'
+
+import { DLQ_OUTPUT, INGESTION_WARNINGS_OUTPUT, OVERFLOW_OUTPUT } from '~/common/outputs'
+import { IngestionOutputs } from '~/common/outputs/ingestion-outputs'
+import { EventIngestionRestrictionManager } from '~/common/utils/event-ingestion-restrictions'
+import { PromiseScheduler } from '~/common/utils/promise-scheduler'
+import { createApplyEventRestrictionsStep, createParseHeadersStep } from '~/ingestion/common/steps/event-preprocessing'
+import { TopHogRegistry } from '~/ingestion/framework/extensions/tophog'
+import { ok } from '~/ingestion/framework/results'
+import { runSessionReplayPipeline } from '~/ingestion/pipelines/sessionreplay'
+import { defaultAllowLists } from '~/ingestion/pipelines/sessionreplay/anonymize/default-dict'
+import { SessionBatchManager } from '~/ingestion/pipelines/sessionreplay/sessions/session-batch-manager'
+import { SessionBatchRecorder } from '~/ingestion/pipelines/sessionreplay/sessions/session-batch-recorder'
+import { TeamService } from '~/ingestion/pipelines/sessionreplay/shared/teams/team-service'
+import { TeamForReplay } from '~/ingestion/pipelines/sessionreplay/teams/types'
+import { createMockIngestionOutputs } from '~/tests/helpers/mock-ingestion-outputs'
+
+import { createMlMirrorReplayPipeline } from './ml-mirror-pipeline'
+
+jest.mock('~/ingestion/common/steps/event-preprocessing', () => ({
+ createParseHeadersStep: jest.fn(),
+ createApplyEventRestrictionsStep: jest.fn(),
+}))
+
+const mockCreateParseHeadersStep = createParseHeadersStep as jest.Mock
+const mockCreateApplyEventRestrictionsStep = createApplyEventRestrictionsStep as jest.Mock
+
+function createMockTopHog(): TopHogRegistry {
+ const recorder = { record: jest.fn() }
+ return {
+ registerSum: jest.fn().mockReturnValue(recorder),
+ registerMax: jest.fn().mockReturnValue(recorder),
+ registerAverage: jest.fn().mockReturnValue(recorder),
+ } as unknown as TopHogRegistry
+}
+
+describe('ml-mirror-pipeline', () => {
+ let recordMock: jest.Mock
+ let mockSessionBatchManager: jest.Mocked<SessionBatchManager>
+ let mockTeamService: TeamService
+ let topHog: TopHogRegistry
+ let promiseScheduler: PromiseScheduler
+ let outputs: jest.Mocked<
+ IngestionOutputs<typeof DLQ_OUTPUT | typeof OVERFLOW_OUTPUT | typeof INGESTION_WARNINGS_OUTPUT>
+ >
+ const scrubContext = { allow: defaultAllowLists() }
+ const now = DateTime.now()
+
+ const team = (aiTrainingOptedIn: boolean): TeamForReplay => ({
+ teamId: 1,
+ consoleLogIngestionEnabled: false,
+ aiTrainingOptedIn,
+ })
+
+ beforeEach(() => {
+ jest.clearAllMocks()
+ outputs = createMockIngestionOutputs()
+
+ recordMock = jest.fn().mockResolvedValue(undefined)
+ const recorder = { record: recordMock } as unknown as jest.Mocked<SessionBatchRecorder>
+ mockSessionBatchManager = {
+ getCurrentBatch: jest.fn().mockReturnValue(recorder),
+ shouldFlush: jest.fn().mockReturnValue(false),
+ flush: jest.fn().mockResolvedValue(undefined),
+ discardPartitions: jest.fn(),
+ } as unknown as jest.Mocked<SessionBatchManager>
+
+ topHog = createMockTopHog()
+ promiseScheduler = new PromiseScheduler()
+
+ mockCreateParseHeadersStep.mockReturnValue((input: { message: Message }) => {
+ const headers: Record<string, string> = {}
+ for (const header of input.message.headers || []) {
+ for (const [key, value] of Object.entries(header)) {
+ headers[key] = Buffer.isBuffer(value) ? value.toString() : (value as string)
+ }
+ }
+ return Promise.resolve(ok({ ...input, headers }))
+ })
+ mockCreateApplyEventRestrictionsStep.mockReturnValue((input: unknown) => Promise.resolve(ok(input)))
+ })
+
+ function buildPipeline(): ReturnType<typeof createMlMirrorReplayPipeline> {
+ return createMlMirrorReplayPipeline({
+ outputs,
+ eventIngestionRestrictionManager: {} as unknown as EventIngestionRestrictionManager,
+ overflowEnabled: false,
+ promiseScheduler,
+ teamService: mockTeamService,
+ topHog,
+ sessionBatchManager: mockSessionBatchManager,
+ isDebugLoggingEnabled: () => false,
+ scrubContext,
+ })
+ }
+
+ function message(sessionId: string): Message {
+ const payload = JSON.stringify({
+ distinct_id: 'user-123',
+ data: JSON.stringify({
+ event: '$snapshot_items',
+ properties: {
+ $session_id: sessionId,
+ $window_id: 'window-1',
+ $snapshot_items: [
+ {
+ type: 3,
+ timestamp: now.toMillis(),
+ data: { source: 5, id: 1, text: 'Hello SecretName', isChecked: false },
+ },
+ ],
+ },
+ }),
+ })
+ return {
+ partition: 0,
+ offset: 1,
+ topic: 'test-topic',
+ value: Buffer.from(payload),
+ key: Buffer.from('k'),
+ timestamp: Date.now(),
+ headers: [{ token: Buffer.from('test-token') }, { session_id: Buffer.from(sessionId) }],
+ size: payload.length,
+ } as unknown as Message
+ }
+
+ function fullSnapshotMessage(sessionId: string): Message {
+ const snapshot = {
+ type: 2,
+ timestamp: now.toMillis(),
+ data: {
+ node: {
+ type: 0,
+ id: 1,
+ childNodes: [
+ {
+ type: 2,
+ id: 2,
+ tagName: 'a',
+ attributes: {
+ href: 'https://example.com/u/abc/edit',
+ 'data-note': 'Smithson lives nearby',
+ },
+ childNodes: [{ type: 3, id: 3, textContent: 'Hello SecretName' }],
+ },
+ ],
+ },
+ initialOffset: { top: 0, left: 0 },
+ },
+ }
+ const payload = JSON.stringify({
+ distinct_id: 'user-123',
+ data: JSON.stringify({
+ event: '$snapshot_items',
+ properties: { $session_id: sessionId, $window_id: 'window-1', $snapshot_items: [snapshot] },
+ }),
+ })
+ return {
+ partition: 0,
+ offset: 1,
+ topic: 'test-topic',
+ value: Buffer.from(payload),
+ key: Buffer.from('k'),
+ timestamp: Date.now(),
+ headers: [{ token: Buffer.from('test-token') }, { session_id: Buffer.from(sessionId) }],
+ size: payload.length,
+ } as unknown as Message
+ }
+
+ it('anonymizes events before recording for an opted-in team', async () => {
+ mockTeamService = {
+ getTeamByToken: jest.fn().mockResolvedValue(team(true)),
+ getRetentionPeriodByTeamId: jest.fn().mockResolvedValue(30),
+ } as unknown as TeamService
+
+ await runSessionReplayPipeline(buildPipeline(), [message('sess-1')])
+
+ expect(recordMock).toHaveBeenCalledTimes(1)
+ const recorded = recordMock.mock.calls[0][0]
+ // The Input event's text was scrubbed before it reached the recorder.
+ expect(recorded.message.eventsByWindowId['window-1'][0].data.text).toBe('Hello **********')
+ })
+
+ it('drops sessions for a team that did not opt into AI training', async () => {
+ mockTeamService = {
+ getTeamByToken: jest.fn().mockResolvedValue(team(false)),
+ getRetentionPeriodByTeamId: jest.fn().mockResolvedValue(30),
+ } as unknown as TeamService
+
+ await runSessionReplayPipeline(buildPipeline(), [message('sess-2')])
+
+ expect(recordMock).not.toHaveBeenCalled()
+ })
+
+ it('scrubs a FullSnapshot (text, url, free-text data-*) end-to-end before recording', async () => {
+ mockTeamService = {
+ getTeamByToken: jest.fn().mockResolvedValue(team(true)),
+ getRetentionPeriodByTeamId: jest.fn().mockResolvedValue(30),
+ } as unknown as TeamService
+
+ await runSessionReplayPipeline(buildPipeline(), [fullSnapshotMessage('sess-3')])
+
+ expect(recordMock).toHaveBeenCalledTimes(1)
+ const node = recordMock.mock.calls[0][0].message.eventsByWindowId['window-1'][0].data.node.childNodes[0]
+ expect(node.childNodes[0].textContent).toBe('Hello **********') // DOM text
+ expect(node.attributes.href).toContain('https://example.com/') // authority kept...
+ expect(node.attributes.href).not.toContain('abc') // ...path segments redacted
+ expect(node.attributes['data-note']).not.toContain('Smithson') // free-text data-* scrubbed
+ })
+})
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
new file mode 100644
index 000000000000..e21b15460d67
--- /dev/null
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/ml-mirror-pipeline.ts
@@ -0,0 +1,125 @@
+/** The primary session replay pipeline plus an AI-training opt-in filter and an anonymize step. */
+import { Message } from 'node-rdkafka'
+
+import { OverflowOutput } from '~/common/outputs'
+import { createApplyEventRestrictionsStep, createParseHeadersStep } from '~/ingestion/common/steps/event-preprocessing'
+import { BatchPipelineUnwrapper } from '~/ingestion/framework/batch-pipeline-unwrapper'
+import { newBatchPipelineBuilder } from '~/ingestion/framework/builders'
+import { createTopHogWrapper, sum, timer } from '~/ingestion/framework/extensions/tophog'
+import { createUnwrapper } from '~/ingestion/framework/helpers'
+import { PipelineConfig } from '~/ingestion/framework/result-handling-pipeline'
+import {
+ SessionReplayPipelineConfig,
+ SessionReplayPipelineInput,
+ SessionReplayPipelineOutput,
+} from '~/ingestion/pipelines/sessionreplay'
+import { createAiTrainingOptInFilterStep } from '~/ingestion/pipelines/sessionreplay/ai-training-optin-filter-step'
+import { createAnonymizeStep } from '~/ingestion/pipelines/sessionreplay/anonymize-step'
+import { ScrubContext } from '~/ingestion/pipelines/sessionreplay/anonymize/config'
+import { createParseMessageStep } from '~/ingestion/pipelines/sessionreplay/parse-message-step'
+import { createRecordSessionEventStep } from '~/ingestion/pipelines/sessionreplay/record-session-event-step'
+import { createTeamFilterStep } from '~/ingestion/pipelines/sessionreplay/team-filter-step'
+
+export type MlMirrorReplayPipelineConfig = SessionReplayPipelineConfig & {
+ /** Shared, immutable scrub context (allow lists + tunables). */
+ scrubContext: ScrubContext
+}
+
+export function createMlMirrorReplayPipeline(
+ config: MlMirrorReplayPipelineConfig
+): BatchPipelineUnwrapper<
+ SessionReplayPipelineInput,
+ SessionReplayPipelineOutput,
+ { message: Message },
+ OverflowOutput
+> {
+ const {
+ outputs,
+ eventIngestionRestrictionManager,
+ overflowEnabled,
+ promiseScheduler,
+ teamService,
+ topHog,
+ sessionBatchManager,
+ isDebugLoggingEnabled,
+ scrubContext,
+ } = config
+
+ const pipelineConfig: PipelineConfig<OverflowOutput> = { outputs, promiseScheduler }
+ const topHogWrapper = createTopHogWrapper(topHog)
+
+ const pipeline = newBatchPipelineBuilder<SessionReplayPipelineInput, { message: Message }>()
+ .messageAware((b) =>
+ b
+ .sequentially((b) =>
+ b
+ .pipe(createParseHeadersStep())
+ .pipe(
+ createApplyEventRestrictionsStep(eventIngestionRestrictionManager, {
+ overflowEnabled,
+ preservePartitionLocality: true,
+ })
+ )
+ .pipe(createTeamFilterStep(teamService))
+ // Mirror only data from orgs that opted into AI training.
+ .pipe(createAiTrainingOptInFilterStep())
+ )
+ .filterMap(
+ (element) => ({
+ result: element.result,
+ context: {
+ ...element.context,
+ team: { id: element.result.value.team.teamId },
+ },
+ }),
+ (b) =>
+ 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) => ({
+ token: input.parsedMessage.token ?? 'unknown',
+ session_id: input.parsedMessage.session_id,
+ })),
+ ]
+ )
+ )
+ )
+ .gather()
+ )
+ .handleIngestionWarnings(outputs)
+ )
+ )
+ .handleResults(pipelineConfig)
+ .handleSideEffects(promiseScheduler, { await: false })
+ .gather()
+ .build()
+
+ return createUnwrapper(pipeline)
+}
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/parquet-writer.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/parquet-writer.ts
new file mode 100644
index 000000000000..d0d99db0b4d5
--- /dev/null
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/parquet-writer.ts
@@ -0,0 +1,64 @@
+/** Encodes block-metadata rows into a Snappy-compressed Parquet buffer for upload to the ML bucket. */
+import { ParquetSchema, ParquetWriter } from '@dsnp/parquetjs'
+import { Writable } from 'stream'
+
+import { COLUMNS } from './block-metadata-columns'
+import { MlBlockMetadataRow } from './block-metadata-row'
+
+type SchemaDef = ConstructorParameters<typeof ParquetSchema>[0]
+
+// Schema and record mapping both derive from the single COLUMNS table (which also drives the row validator).
+// Snappy on every column — compression is a per-field option in parquetjs, not a writer option.
+const SCHEMA = new ParquetSchema(
+ Object.fromEntries(
+ COLUMNS.map((col) => {
+ const def: Record<string, unknown> = { type: col.type, compression: 'SNAPPY' }
+ if (col.optional) {
+ def.optional = true
+ }
+ if (col.repeated) {
+ def.repeated = true
+ }
+ return [col.parquet, def]
+ })
+ ) as SchemaDef
+)
+
+const bigintOrNull = (n: unknown): bigint | null =>
+ n === null || n === undefined ? null : BigInt(Math.trunc(n as number))
+
+function toParquetRecord(row: MlBlockMetadataRow): Record<string, unknown> {
+ const record: Record<string, unknown> = {}
+ const r = row as unknown as Record<string, unknown>
+ for (const col of COLUMNS) {
+ const value = r[col.row]
+ if (col.type === 'TIMESTAMP_MILLIS') {
+ record[col.parquet] = new Date(value as number)
+ } else if (col.type === 'INT64') {
+ record[col.parquet] = bigintOrNull(value)
+ } else {
+ record[col.parquet] = value
+ }
+ }
+ return record
+}
+
+export async function rowsToParquetBuffer(rows: MlBlockMetadataRow[]): Promise<Buffer> {
+ const chunks: Buffer[] = []
+ const sink = new Writable({
+ write(chunk: Buffer, _encoding, callback) {
+ chunks.push(chunk)
+ callback()
+ },
+ })
+ // parquetjs types want an fs.WriteStream, but it only calls write/end/on at runtime, which Writable provides.
+ const writer = await ParquetWriter.openStream(
+ SCHEMA,
+ sink as unknown as Parameters<typeof ParquetWriter.openStream>[1]
+ )
+ for (const row of rows) {
+ await writer.appendRow(toParquetRecord(row))
+ }
+ await writer.close()
+ return Buffer.concat(chunks)
+}
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/pseudonym-key.test.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/pseudonym-key.test.ts
new file mode 100644
index 000000000000..c6fa93fc2c78
--- /dev/null
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/pseudonym-key.test.ts
@@ -0,0 +1,76 @@
+import { PseudonymKeyConfig, pseudonymKeyFingerprint, resolvePseudonymKey } from './pseudonym-key'
+
+const baseConfig = (over: Partial<PseudonymKeyConfig> = {}): PseudonymKeyConfig => ({
+ SESSION_RECORDING_ML_PSEUDONYM_SECRET: '',
+ SESSION_RECORDING_ML_PSEUDONYM_WRAPPED_KEY: '',
+ SESSION_RECORDING_ML_PSEUDONYM_KMS_REGION: '',
+ SESSION_RECORDING_ML_PSEUDONYM_KEY_FINGERPRINT: '',
+ ...over,
+})
+
+describe('ml-mirror pseudonym key', () => {
+ describe('pseudonymKeyFingerprint', () => {
+ it('is deterministic, 16-hex, and reveals nothing about the key', () => {
+ const fp = pseudonymKeyFingerprint('super-secret-key')
+ expect(fp).toBe(pseudonymKeyFingerprint('super-secret-key'))
+ expect(fp).toMatch(/^[0-9a-f]{16}$/)
+ expect(fp).not.toContain('super-secret-key')
+ expect(pseudonymKeyFingerprint('other')).not.toBe(fp)
+ })
+ })
+
+ describe('resolvePseudonymKey', () => {
+ const failDecrypt = () => Promise.reject(new Error('KMS should not be called'))
+
+ it('uses the plaintext env secret when no ciphertext is set (local dev)', async () => {
+ const key = await resolvePseudonymKey(
+ baseConfig({ SESSION_RECORDING_ML_PSEUDONYM_SECRET: 'dev' }),
+ failDecrypt
+ )
+ expect(key).toBe('dev')
+ })
+
+ it('prefers the KMS-decrypted key over the plaintext secret', async () => {
+ const decrypt = jest.fn().mockResolvedValue(Buffer.from('kms-key-bytes'))
+ const key = await resolvePseudonymKey(
+ baseConfig({
+ SESSION_RECORDING_ML_PSEUDONYM_SECRET: 'dev',
+ SESSION_RECORDING_ML_PSEUDONYM_WRAPPED_KEY: 'Y2lwaGVy',
+ }),
+ decrypt
+ )
+ expect(decrypt).toHaveBeenCalledWith('Y2lwaGVy', '')
+ expect((key as Buffer).toString()).toBe('kms-key-bytes')
+ })
+
+ it('fails closed when neither a ciphertext nor a plaintext secret is set', async () => {
+ await expect(resolvePseudonymKey(baseConfig(), failDecrypt)).rejects.toThrow(
+ 'SESSION_RECORDING_ML_PSEUDONYM_WRAPPED_KEY or SESSION_RECORDING_ML_PSEUDONYM_SECRET'
+ )
+ })
+
+ it('passes when the pinned fingerprint matches the resolved key', async () => {
+ const fingerprint = pseudonymKeyFingerprint('dev')
+ const key = await resolvePseudonymKey(
+ baseConfig({
+ SESSION_RECORDING_ML_PSEUDONYM_SECRET: 'dev',
+ SESSION_RECORDING_ML_PSEUDONYM_KEY_FINGERPRINT: fingerprint,
+ }),
+ failDecrypt
+ )
+ expect(key).toBe('dev')
+ })
+
+ it('fails closed when the pinned fingerprint does not match (rotation guard)', async () => {
+ await expect(
+ resolvePseudonymKey(
+ baseConfig({
+ SESSION_RECORDING_ML_PSEUDONYM_SECRET: 'rotated-key',
+ SESSION_RECORDING_ML_PSEUDONYM_KEY_FINGERPRINT: pseudonymKeyFingerprint('original-key'),
+ }),
+ failDecrypt
+ )
+ ).rejects.toThrow('fingerprint mismatch')
+ })
+ })
+})
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/pseudonym-key.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/pseudonym-key.ts
new file mode 100644
index 000000000000..3c22b1b146be
--- /dev/null
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/pseudonym-key.ts
@@ -0,0 +1,71 @@
+/** Resolves the pseudonymization key (KMS-wrapped in prod, plaintext env for local dev) and pins it against rotation. */
+import { DecryptCommand, KMSClient } from '@aws-sdk/client-kms'
+import { createHmac } from 'crypto'
+
+import { logger } from '~/common/utils/logger'
+
+export interface PseudonymKeyConfig {
+ SESSION_RECORDING_ML_PSEUDONYM_SECRET: string
+ SESSION_RECORDING_ML_PSEUDONYM_WRAPPED_KEY: string
+ SESSION_RECORDING_ML_PSEUDONYM_KMS_REGION: string
+ SESSION_RECORDING_ML_PSEUDONYM_KEY_FINGERPRINT: string
+}
+
+/** Decrypts a base64 KMS-wrapped key; injectable so tests don't hit KMS. */
+export type KeyDecryptor = (ciphertextBase64: string, region: string) => Promise<Buffer>
+
+const kmsDecrypt: KeyDecryptor = async (ciphertextBase64, region) => {
+ const client = new KMSClient(region ? { region } : {})
+ const result = await client.send(new DecryptCommand({ CiphertextBlob: Buffer.from(ciphertextBase64, 'base64') }))
+ if (!result.Plaintext) {
+ throw new Error('KMS Decrypt returned no plaintext for the pseudonym key')
+ }
+ return Buffer.from(result.Plaintext)
+}
+
+/**
+ * Non-reversible, domain-separated fingerprint of the key. Safe to log/store: it identifies the key without
+ * revealing it, so the dataset's identity space can be pinned to one key.
+ */
+export function pseudonymKeyFingerprint(secret: string | Buffer): string {
+ return createHmac('sha256', secret).update('pseudonym-key-fingerprint:v1').digest('hex').slice(0, 16)
+}
+
+/**
+ * Resolves the HMAC key: prefers the KMS-wrapped ciphertext (decrypted once, never persisted), else the plaintext
+ * env secret (local dev). Fails closed when no key is configured, or when a pinned fingerprint doesn't match the
+ * resolved key — a changed key would re-map every id and contaminate train/eval splits, so we refuse to start.
+ */
+export async function resolvePseudonymKey(
+ config: PseudonymKeyConfig,
+ decrypt: KeyDecryptor = kmsDecrypt
+): Promise<string | Buffer> {
+ let secret: string | Buffer
+ let source: 'kms' | 'env'
+ if (config.SESSION_RECORDING_ML_PSEUDONYM_WRAPPED_KEY) {
+ secret = await decrypt(
+ config.SESSION_RECORDING_ML_PSEUDONYM_WRAPPED_KEY,
+ config.SESSION_RECORDING_ML_PSEUDONYM_KMS_REGION
+ )
+ source = 'kms'
+ } else if (config.SESSION_RECORDING_ML_PSEUDONYM_SECRET) {
+ secret = config.SESSION_RECORDING_ML_PSEUDONYM_SECRET
+ source = 'env'
+ } else {
+ throw new Error(
+ 'SESSION_RECORDING_ML_PSEUDONYM_WRAPPED_KEY or SESSION_RECORDING_ML_PSEUDONYM_SECRET must be set for the ML mirror'
+ )
+ }
+
+ const fingerprint = pseudonymKeyFingerprint(secret)
+ const expected = config.SESSION_RECORDING_ML_PSEUDONYM_KEY_FINGERPRINT
+ if (expected && expected !== fingerprint) {
+ throw new Error(
+ `pseudonym key fingerprint mismatch (resolved ${fingerprint}, expected ${expected}) — refusing to start: ` +
+ 'a rotated/incorrect key would re-map ids and contaminate train/eval splits'
+ )
+ }
+
+ logger.info('🔑', 'ml_pseudonym_key_loaded', { source, fingerprint, pinned: Boolean(expected) })
+ return secret
+}
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/pseudonymize.test.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/pseudonymize.test.ts
new file mode 100644
index 000000000000..d827f25443bf
--- /dev/null
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/pseudonymize.test.ts
@@ -0,0 +1,23 @@
+import { PSEUDONYM_SESSION, PSEUDONYM_TEAM, pseudonymize } from './pseudonymize'
+
+describe('ml-mirror/pseudonymize', () => {
+ const secret = 'super-secret'
+
+ it('is deterministic: same input maps to the same value', () => {
+ expect(pseudonymize(secret, PSEUDONYM_TEAM, '42')).toBe(pseudonymize(secret, PSEUDONYM_TEAM, '42'))
+ })
+
+ it('domain-separates namespaces so a team id and session id with the same value differ', () => {
+ expect(pseudonymize(secret, PSEUDONYM_TEAM, '42')).not.toBe(pseudonymize(secret, PSEUDONYM_SESSION, '42'))
+ })
+
+ it('depends on the secret: a different secret produces a different value', () => {
+ expect(pseudonymize(secret, PSEUDONYM_TEAM, '42')).not.toBe(pseudonymize('other-secret', PSEUDONYM_TEAM, '42'))
+ })
+
+ it('does not contain the raw value', () => {
+ const out = pseudonymize(secret, PSEUDONYM_TEAM, 'team-12345')
+ expect(out).not.toContain('team-12345')
+ expect(out).toMatch(/^[0-9a-f]{32}$/)
+ })
+})
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/pseudonymize.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/pseudonymize.ts
new file mode 100644
index 000000000000..132a0a90d9e5
--- /dev/null
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/pseudonymize.ts
@@ -0,0 +1,17 @@
+import { createHmac } from 'crypto'
+
+/**
+ * Deterministic, non-reversible pseudonym for an identifier. Same input → same
+ * output (so the ML dataset can group by team/session/person), but without the
+ * secret (held only by the ingester, never in the ML account) it can't be mapped
+ * back. The namespace domain-separates ids so a teamId and sessionId with the
+ * same value don't collide.
+ */
+export function pseudonymize(secret: string | Buffer, namespace: string, value: string): string {
+ // Length-prefix the namespace so the join is unambiguous even if a value contains the delimiter.
+ return createHmac('sha256', secret).update(`${namespace.length}:${namespace}:${value}`).digest('hex').slice(0, 32)
+}
+
+export const PSEUDONYM_TEAM = 'team'
+export const PSEUDONYM_SESSION = 'session'
+export const PSEUDONYM_DISTINCT_ID = 'distinct_id'
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/outputs/registry.ts b/nodejs/src/ingestion/pipelines/sessionreplay/outputs/registry.ts
index 6164adc7719a..103a12defae8 100644
--- a/nodejs/src/ingestion/pipelines/sessionreplay/outputs/registry.ts
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/outputs/registry.ts
@@ -6,7 +6,11 @@ import {
TOPHOG_OUTPUT,
} from '~/common/outputs'
import { IngestionOutputsBuilder } from '~/common/outputs/ingestion-outputs-builder'
-import { REPLAY_EVENTS_OUTPUT, SESSION_FEATURES_OUTPUT } from '~/ingestion/pipelines/sessionreplay/shared/outputs'
+import {
+ ML_BLOCK_METADATA_OUTPUT,
+ REPLAY_EVENTS_OUTPUT,
+ SESSION_FEATURES_OUTPUT,
+} from '~/ingestion/pipelines/sessionreplay/shared/outputs'
/** Register all session replay outputs on the builder. Call `.build(registry, config)` to resolve. */
export function createOutputsRegistry() {
@@ -39,4 +43,8 @@ export function createOutputsRegistry() {
topicKey: 'INGESTION_SESSIONREPLAY_OUTPUT_SESSION_FEATURES_TOPIC',
producerKey: 'INGESTION_SESSIONREPLAY_OUTPUT_SESSION_FEATURES_PRODUCER',
})
+ .register(ML_BLOCK_METADATA_OUTPUT, {
+ topicKey: 'INGESTION_SESSIONREPLAY_OUTPUT_ML_BLOCK_METADATA_TOPIC',
+ producerKey: 'INGESTION_SESSIONREPLAY_OUTPUT_ML_BLOCK_METADATA_PRODUCER',
+ })
}
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/record-session-event-step.test.ts b/nodejs/src/ingestion/pipelines/sessionreplay/record-session-event-step.test.ts
index 1295314c3960..f80a27425459 100644
--- a/nodejs/src/ingestion/pipelines/sessionreplay/record-session-event-step.test.ts
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/record-session-event-step.test.ts
@@ -23,6 +23,7 @@ describe('createRecordSessionEventStep', () => {
const defaultTeam: TeamForReplay = {
teamId: 1,
consoleLogIngestionEnabled: false,
+ aiTrainingOptedIn: true,
}
const createParsedMessage = (overrides: Partial<ParsedMessageData> = {}): ParsedMessageData => ({
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/session-replay-pipeline.test.ts b/nodejs/src/ingestion/pipelines/sessionreplay/session-replay-pipeline.test.ts
index ba1cdad0ba81..5d8dab06466a 100644
--- a/nodejs/src/ingestion/pipelines/sessionreplay/session-replay-pipeline.test.ts
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/session-replay-pipeline.test.ts
@@ -91,6 +91,7 @@ describe('session-replay-pipeline', () => {
const defaultTeam: TeamForReplay = {
teamId: 1,
consoleLogIngestionEnabled: false,
+ aiTrainingOptedIn: true,
}
const now = DateTime.now()
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/sessions/session-batch-manager.ts b/nodejs/src/ingestion/pipelines/sessionreplay/sessions/session-batch-manager.ts
index f5db3f406c70..6ea09ffe2ac5 100644
--- a/nodejs/src/ingestion/pipelines/sessionreplay/sessions/session-batch-manager.ts
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/sessions/session-batch-manager.ts
@@ -1,7 +1,7 @@
import { logger } from '~/common/utils/logger'
import { KafkaOffsetManager } from '~/ingestion/pipelines/sessionreplay/kafka/offset-manager'
import { SessionFeatureStore } from '~/ingestion/pipelines/sessionreplay/shared/features/session-feature-store'
-import { SessionMetadataStore } from '~/ingestion/pipelines/sessionreplay/shared/metadata/session-metadata-store'
+import { SessionMetadataSink } from '~/ingestion/pipelines/sessionreplay/shared/metadata/session-metadata-store'
import { KeyStore, RecordingEncryptor } from '~/ingestion/pipelines/sessionreplay/shared/types'
import { SessionBatchFileStorage } from './session-batch-file-storage'
@@ -24,7 +24,7 @@ export interface SessionBatchManagerConfig {
/** Handles writing session batch files to storage */
fileStorage: SessionBatchFileStorage
/** Manages storing session metadata */
- metadataStore: SessionMetadataStore
+ metadataStore: SessionMetadataSink
/** Manages storing console logs */
consoleLogStore: SessionConsoleLogStore
/** Manages storing session features for ML scoring */
@@ -81,7 +81,7 @@ export class SessionBatchManager {
private readonly featuresRolloutPercentage: number
private readonly offsetManager: KafkaOffsetManager
private readonly fileStorage: SessionBatchFileStorage
- private readonly metadataStore: SessionMetadataStore
+ private readonly metadataStore: SessionMetadataSink
private readonly consoleLogStore: SessionConsoleLogStore
private readonly featureStore: SessionFeatureStore
private lastFlushTime: number
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 29b5a731b120..f09d67dc8e91 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
@@ -283,6 +283,7 @@ describe('SessionBatchRecorder', () => {
team: {
teamId,
consoleLogIngestionEnabled: false,
+ aiTrainingOptedIn: true,
},
message: {
distinct_id: distinctId,
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 6efccf12d84b..39f9ccc4fa36 100644
--- a/nodejs/src/ingestion/pipelines/sessionreplay/sessions/session-batch-recorder.ts
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/sessions/session-batch-recorder.ts
@@ -8,7 +8,7 @@ import {
SessionFeatureStore,
} from '~/ingestion/pipelines/sessionreplay/shared/features/session-feature-store'
import { SessionBlockMetadata } from '~/ingestion/pipelines/sessionreplay/shared/metadata/session-block-metadata'
-import { SessionMetadataStore } from '~/ingestion/pipelines/sessionreplay/shared/metadata/session-metadata-store'
+import { SessionMetadataSink } from '~/ingestion/pipelines/sessionreplay/shared/metadata/session-metadata-store'
import { KeyStore, RecordingEncryptor, SessionKey } from '~/ingestion/pipelines/sessionreplay/shared/types'
import { MessageWithTeam } from '~/ingestion/pipelines/sessionreplay/teams/types'
@@ -78,7 +78,7 @@ export class SessionBatchRecorder {
constructor(
private readonly offsetManager: KafkaOffsetManager,
private readonly storage: SessionBatchFileStorage,
- private readonly metadataStore: SessionMetadataStore,
+ private readonly metadataStore: SessionMetadataSink,
private readonly consoleLogStore: SessionConsoleLogStore,
private readonly featureStore: SessionFeatureStore,
private readonly sessionTracker: SessionTracker,
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 076135f8239b..e1ff051c1e55 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
@@ -47,6 +47,7 @@ describe('SessionConsoleLogRecorder', () => {
team: {
teamId,
consoleLogIngestionEnabled,
+ aiTrainingOptedIn: true,
},
message: {
distinct_id: distinctId,
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/sessions/session-console-log-store.ts b/nodejs/src/ingestion/pipelines/sessionreplay/sessions/session-console-log-store.ts
index 0e44eed7d9aa..236a4df5c212 100644
--- a/nodejs/src/ingestion/pipelines/sessionreplay/sessions/session-console-log-store.ts
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/sessions/session-console-log-store.ts
@@ -22,16 +22,19 @@ export class SessionConsoleLogStore {
private pendingMessages: ConsoleLogEntry[] = []
private readonly messageLimit: number
+ private readonly enabled: boolean
+
constructor(
private readonly outputs: IngestionOutputs<LogEntriesOutput>,
- options: { messageLimit: number }
+ options: { messageLimit: number; enabled?: boolean }
) {
this.messageLimit = options.messageLimit
+ this.enabled = options.enabled ?? true
logger.debug('session_console_log_store_created')
}
public async storeSessionConsoleLogs(logs: ConsoleLogEntry[]): Promise<void> {
- if (logs.length === 0) {
+ if (!this.enabled || logs.length === 0) {
return
}
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/shared/metadata/kafka-metadata-sink.ts b/nodejs/src/ingestion/pipelines/sessionreplay/shared/metadata/kafka-metadata-sink.ts
new file mode 100644
index 000000000000..857de3572ea1
--- /dev/null
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/shared/metadata/kafka-metadata-sink.ts
@@ -0,0 +1,36 @@
+import { IngestionOutputs } from '~/common/outputs/ingestion-outputs'
+
+import { SessionBlockMetadata } from './session-block-metadata'
+
+/** Sink for per-block session metadata at flush time (ClickHouse for the primary, the ML topic for the mirror). */
+export interface SessionMetadataSink {
+ storeSessionBlocks(blocks: SessionBlockMetadata[]): Promise<void>
+}
+
+/** A keyed record to be JSON-serialized onto a Kafka output. */
+export interface MetadataRecord {
+ key: string
+ value: unknown
+}
+
+/**
+ * Base sink that maps a flush's blocks to keyed records and produces them as JSON to one Kafka output.
+ * Subclasses supply the output and the per-block mapping; the produce mechanism is shared.
+ */
+export abstract class KafkaMetadataSink<O extends string> implements SessionMetadataSink {
+ constructor(
+ protected readonly outputs: IngestionOutputs<O>,
+ private readonly output: O
+ ) {}
+
+ protected abstract toRecords(blocks: SessionBlockMetadata[]): MetadataRecord[]
+
+ public async storeSessionBlocks(blocks: SessionBlockMetadata[]): Promise<void> {
+ const records = this.toRecords(blocks)
+ // queueMessages awaits delivery acks, so offsets commit only once the metadata is durably on Kafka.
+ await this.outputs.queueMessages(
+ this.output,
+ records.map((record) => ({ key: record.key, value: Buffer.from(JSON.stringify(record.value)) }))
+ )
+ }
+}
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/shared/metadata/session-metadata-store.ts b/nodejs/src/ingestion/pipelines/sessionreplay/shared/metadata/session-metadata-store.ts
index 5f1a8e423aa1..c0e5ec527102 100644
--- a/nodejs/src/ingestion/pipelines/sessionreplay/shared/metadata/session-metadata-store.ts
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/shared/metadata/session-metadata-store.ts
@@ -6,53 +6,46 @@ import { castTimestampOrNow } from '~/common/utils/utils'
import { REPLAY_EVENTS_OUTPUT, ReplayEventsOutput } from '~/ingestion/pipelines/sessionreplay/shared/outputs'
import { TimestampFormat } from '~/types'
+import { KafkaMetadataSink, MetadataRecord } from './kafka-metadata-sink'
import { SessionBlockMetadata } from './session-block-metadata'
-export class SessionMetadataStore {
- constructor(private outputs: IngestionOutputs<ReplayEventsOutput>) {
+export type { SessionMetadataSink } from './kafka-metadata-sink'
+
+export class SessionMetadataStore extends KafkaMetadataSink<ReplayEventsOutput> {
+ constructor(outputs: IngestionOutputs<ReplayEventsOutput>) {
+ super(outputs, REPLAY_EVENTS_OUTPUT)
logger.debug('🔍', 'session_metadata_store_created')
}
- public async storeSessionBlocks(blocks: SessionBlockMetadata[]): Promise<void> {
- logger.info('🔍', 'session_metadata_store_storing_blocks', { count: blocks.length })
-
- const events = blocks.map((metadata) => ({
- uuid: randomUUID(),
- session_id: metadata.sessionId,
- team_id: metadata.teamId,
- distinct_id: metadata.distinctId,
- batch_id: metadata.batchId,
- first_timestamp: castTimestampOrNow(metadata.startDateTime, TimestampFormat.ClickHouse),
- last_timestamp: castTimestampOrNow(metadata.endDateTime, TimestampFormat.ClickHouse),
- block_url: metadata.blockUrl,
- first_url: metadata.firstUrl,
- urls: metadata.urls || [],
- click_count: metadata.clickCount || 0,
- keypress_count: metadata.keypressCount || 0,
- mouse_activity_count: metadata.mouseActivityCount || 0,
- active_milliseconds: metadata.activeMilliseconds || 0,
- console_log_count: metadata.consoleLogCount || 0,
- console_warn_count: metadata.consoleWarnCount || 0,
- console_error_count: metadata.consoleErrorCount || 0,
- size: metadata.size || 0,
- message_count: metadata.messageCount || 0,
- snapshot_source: metadata.snapshotSource,
- snapshot_library: metadata.snapshotLibrary,
- event_count: metadata.eventCount || 0,
- retention_period_days: metadata.retentionPeriodDays,
- is_deleted: metadata.isDeleted ? 1 : 0,
+ protected toRecords(blocks: SessionBlockMetadata[]): MetadataRecord[] {
+ return blocks.map((metadata) => ({
+ key: metadata.sessionId,
+ value: {
+ uuid: randomUUID(),
+ session_id: metadata.sessionId,
+ team_id: metadata.teamId,
+ distinct_id: metadata.distinctId,
+ batch_id: metadata.batchId,
+ first_timestamp: castTimestampOrNow(metadata.startDateTime, TimestampFormat.ClickHouse),
+ last_timestamp: castTimestampOrNow(metadata.endDateTime, TimestampFormat.ClickHouse),
+ block_url: metadata.blockUrl,
+ first_url: metadata.firstUrl,
+ urls: metadata.urls || [],
+ click_count: metadata.clickCount || 0,
+ keypress_count: metadata.keypressCount || 0,
+ mouse_activity_count: metadata.mouseActivityCount || 0,
+ active_milliseconds: metadata.activeMilliseconds || 0,
+ console_log_count: metadata.consoleLogCount || 0,
+ console_warn_count: metadata.consoleWarnCount || 0,
+ console_error_count: metadata.consoleErrorCount || 0,
+ size: metadata.size || 0,
+ message_count: metadata.messageCount || 0,
+ snapshot_source: metadata.snapshotSource,
+ snapshot_library: metadata.snapshotLibrary,
+ event_count: metadata.eventCount || 0,
+ retention_period_days: metadata.retentionPeriodDays,
+ is_deleted: metadata.isDeleted ? 1 : 0,
+ },
}))
-
- // queueMessages awaits delivery acks for every message, so no separate flush is needed
- // to guarantee messages are on Kafka before the batch offset is committed.
- await this.outputs.queueMessages(
- REPLAY_EVENTS_OUTPUT,
- events.map((event) => ({
- key: event.session_id,
- value: Buffer.from(JSON.stringify(event)),
- }))
- )
-
- logger.info('🔍', 'session_metadata_store_blocks_stored', { count: events.length })
}
}
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/shared/outputs/index.ts b/nodejs/src/ingestion/pipelines/sessionreplay/shared/outputs/index.ts
index de9df5dea613..bf523ae09033 100644
--- a/nodejs/src/ingestion/pipelines/sessionreplay/shared/outputs/index.ts
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/shared/outputs/index.ts
@@ -7,3 +7,7 @@ export type ReplayEventsOutput = typeof REPLAY_EVENTS_OUTPUT
export const SESSION_FEATURES_OUTPUT = 'session_features' as const
export type SessionFeaturesOutput = typeof SESSION_FEATURES_OUTPUT
+
+// Anonymized block metadata for the ML mirror; only the mirror deployment produces to it.
+export const ML_BLOCK_METADATA_OUTPUT = 'ml_block_metadata' as const
+export type MlBlockMetadataOutput = typeof ML_BLOCK_METADATA_OUTPUT
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/shared/s3-client.ts b/nodejs/src/ingestion/pipelines/sessionreplay/shared/s3-client.ts
new file mode 100644
index 000000000000..b1c2c8f67c32
--- /dev/null
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/shared/s3-client.ts
@@ -0,0 +1,36 @@
+import { S3Client, S3ClientConfig } from '@aws-sdk/client-s3'
+
+/** The `SESSION_RECORDING_V2_S3_*` settings needed to build the recordings S3 client. */
+export interface SessionRecordingS3Config {
+ SESSION_RECORDING_V2_S3_ENDPOINT: string
+ SESSION_RECORDING_V2_S3_REGION: string
+ SESSION_RECORDING_V2_S3_BUCKET: string
+ SESSION_RECORDING_V2_S3_PREFIX: string
+ SESSION_RECORDING_V2_S3_ACCESS_KEY_ID: string
+ SESSION_RECORDING_V2_S3_SECRET_ACCESS_KEY: string
+}
+
+/** Builds the recordings S3 client from config, or null when the settings are incomplete. */
+export function buildSessionRecordingS3Client(config: SessionRecordingS3Config): S3Client | null {
+ if (
+ !config.SESSION_RECORDING_V2_S3_ENDPOINT ||
+ !config.SESSION_RECORDING_V2_S3_REGION ||
+ !config.SESSION_RECORDING_V2_S3_BUCKET ||
+ !config.SESSION_RECORDING_V2_S3_PREFIX
+ ) {
+ return null
+ }
+
+ const s3Config: S3ClientConfig = {
+ region: config.SESSION_RECORDING_V2_S3_REGION,
+ endpoint: config.SESSION_RECORDING_V2_S3_ENDPOINT,
+ forcePathStyle: true,
+ }
+ if (config.SESSION_RECORDING_V2_S3_ACCESS_KEY_ID && config.SESSION_RECORDING_V2_S3_SECRET_ACCESS_KEY) {
+ s3Config.credentials = {
+ accessKeyId: config.SESSION_RECORDING_V2_S3_ACCESS_KEY_ID,
+ secretAccessKey: config.SESSION_RECORDING_V2_S3_SECRET_ACCESS_KEY,
+ }
+ }
+ return new S3Client(s3Config)
+}
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/shared/teams/team-service.test.ts b/nodejs/src/ingestion/pipelines/sessionreplay/shared/teams/team-service.test.ts
index 68f67c78154c..574c6e5c620f 100644
--- a/nodejs/src/ingestion/pipelines/sessionreplay/shared/teams/team-service.test.ts
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/shared/teams/team-service.test.ts
@@ -13,8 +13,8 @@ describe('TeamService', () => {
fetchSpy = jest.spyOn(teamService as any, 'fetchTeamTokensWithRecordings').mockResolvedValue({
tokenMap: {
- 'valid-token': { teamId: 1, consoleLogIngestionEnabled: true },
- 'valid-token-2': { teamId: 2, consoleLogIngestionEnabled: false },
+ 'valid-token': { teamId: 1, consoleLogIngestionEnabled: true, aiTrainingOptedIn: true },
+ 'valid-token-2': { teamId: 2, consoleLogIngestionEnabled: false, aiTrainingOptedIn: false },
},
retentionMap: { 1: '30d', 2: '1y' },
})
@@ -30,6 +30,7 @@ describe('TeamService', () => {
expect(team).toEqual({
teamId: 1,
consoleLogIngestionEnabled: true,
+ aiTrainingOptedIn: true,
})
})
@@ -41,7 +42,7 @@ describe('TeamService', () => {
it('should return null if teamId is missing', async () => {
fetchSpy.mockResolvedValue({
tokenMap: {
- token: { teamId: null as any, consoleLogIngestionEnabled: true },
+ token: { teamId: null as any, consoleLogIngestionEnabled: true, aiTrainingOptedIn: true },
},
retentionMap: { 1: '30d', 2: '1y' },
})
@@ -90,6 +91,7 @@ describe('TeamService', () => {
expect(team).toEqual({
teamId: 1,
consoleLogIngestionEnabled: true,
+ aiTrainingOptedIn: true,
})
})
@@ -101,7 +103,7 @@ describe('TeamService', () => {
// Update mock data and capture the promise
const mockFetchPromise = Promise.resolve({
tokenMap: {
- 'valid-token': { teamId: 1, consoleLogIngestionEnabled: false },
+ 'valid-token': { teamId: 1, consoleLogIngestionEnabled: false, aiTrainingOptedIn: true },
},
retentionMap: { 1: '30d', 2: '1y' },
})
@@ -127,7 +129,7 @@ describe('TeamService', () => {
// Update mock data to remove the team
const mockFetchPromise = Promise.resolve({
tokenMap: {
- 'valid-token-2': { teamId: 2, consoleLogIngestionEnabled: false }, // Remove valid-token
+ 'valid-token-2': { teamId: 2, consoleLogIngestionEnabled: false, aiTrainingOptedIn: false }, // Remove valid-token
},
retentionMap: { 2: '1y' },
})
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/shared/teams/team-service.ts b/nodejs/src/ingestion/pipelines/sessionreplay/shared/teams/team-service.ts
index 2ca1ea7c69f5..baf9f6f89556 100644
--- a/nodejs/src/ingestion/pipelines/sessionreplay/shared/teams/team-service.ts
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/shared/teams/team-service.ts
@@ -59,13 +59,20 @@ export async function fetchTeamTokensWithRecordings(client: PostgresRouter): Pro
{
capture_console_log_opt_in: boolean
session_recording_retention_period: RetentionPeriod
+ is_ai_training_opted_in: boolean
} & Pick<Team, 'id' | 'api_token'>
>(
PostgresUse.COMMON_READ,
`
- SELECT id, api_token, capture_console_log_opt_in, session_recording_retention_period
- FROM posthog_team
- WHERE session_recording_opt_in = true
+ SELECT
+ t.id,
+ t.api_token,
+ t.capture_console_log_opt_in,
+ t.session_recording_retention_period,
+ COALESCE(o.is_ai_training_opted_in, false) AS is_ai_training_opted_in
+ FROM posthog_team t
+ LEFT JOIN posthog_organization o ON o.id = t.organization_id
+ WHERE t.session_recording_opt_in = true
`,
[],
'fetchTeamTokensWithRecordings'
@@ -76,6 +83,7 @@ export async function fetchTeamTokensWithRecordings(client: PostgresRouter): Pro
acc[row.api_token] = {
teamId: row.id,
consoleLogIngestionEnabled: row.capture_console_log_opt_in,
+ aiTrainingOptedIn: row.is_ai_training_opted_in,
}
return acc
},
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/shared/teams/types.ts b/nodejs/src/ingestion/pipelines/sessionreplay/shared/teams/types.ts
index 0199ebf917d8..312149baf425 100644
--- a/nodejs/src/ingestion/pipelines/sessionreplay/shared/teams/types.ts
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/shared/teams/types.ts
@@ -3,4 +3,6 @@ import { TeamId } from '~/types'
export interface TeamForReplay {
teamId: TeamId
consoleLogIngestionEnabled: boolean
+ /** Whether the team's organization opted into using its data for AI training. */
+ aiTrainingOptedIn: boolean
}
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/team-filter-step.test.ts b/nodejs/src/ingestion/pipelines/sessionreplay/team-filter-step.test.ts
index 46ffec4ca056..9c24c8fbc1ef 100644
--- a/nodejs/src/ingestion/pipelines/sessionreplay/team-filter-step.test.ts
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/team-filter-step.test.ts
@@ -12,6 +12,7 @@ describe('createTeamFilterStep', () => {
const defaultTeam: TeamForReplay = {
teamId: 1,
consoleLogIngestionEnabled: false,
+ aiTrainingOptedIn: true,
}
it('should enrich message with team context when team is valid', async () => {
diff --git a/nodejs/src/servers/ingestion-session-replay-ml-mirror-server.test.ts b/nodejs/src/servers/ingestion-session-replay-ml-mirror-server.test.ts
new file mode 100644
index 000000000000..93a4ca46c94a
--- /dev/null
+++ b/nodejs/src/servers/ingestion-session-replay-ml-mirror-server.test.ts
@@ -0,0 +1,29 @@
+import { KAFKA_SESSION_REPLAY_ML_BLOCK_METADATA } from '~/common/config/kafka-topics'
+import { getDefaultSessionRecordingConfig } from '~/ingestion/pipelines/sessionreplay/config'
+
+import { buildMlMirrorServerConfig } from './ingestion-session-replay-ml-mirror-server'
+
+describe('buildMlMirrorServerConfig', () => {
+ it('defaults the mirror to its own consumer group, distinct from the primary ingester', () => {
+ const config = buildMlMirrorServerConfig({})
+ expect(config.INGESTION_SESSION_REPLAY_CONSUMER_GROUP_ID).toBe('session-replay-ml-mirror')
+ // Regression guard for the group-id collision: must not inherit the primary default.
+ expect(config.INGESTION_SESSION_REPLAY_CONSUMER_GROUP_ID).not.toBe(
+ getDefaultSessionRecordingConfig().INGESTION_SESSION_REPLAY_CONSUMER_GROUP_ID
+ )
+ })
+
+ it('wires the ML metadata topic and a flush interval safely under max.poll.interval.ms', () => {
+ const config = buildMlMirrorServerConfig({})
+ expect(config.INGESTION_SESSIONREPLAY_OUTPUT_ML_BLOCK_METADATA_TOPIC).toBe(
+ KAFKA_SESSION_REPLAY_ML_BLOCK_METADATA
+ )
+ expect(config.SESSION_RECORDING_ML_METADATA_PREFIX).toBe('block-metadata')
+ expect(config.SESSION_RECORDING_ML_PARQUET_FLUSH_INTERVAL_MS).toBeLessThan(300_000)
+ })
+
+ it('lets an explicit override win over the mirror default', () => {
+ const config = buildMlMirrorServerConfig({ INGESTION_SESSION_REPLAY_CONSUMER_GROUP_ID: 'custom-group' })
+ expect(config.INGESTION_SESSION_REPLAY_CONSUMER_GROUP_ID).toBe('custom-group')
+ })
+})
diff --git a/nodejs/src/servers/ingestion-session-replay-ml-mirror-server.ts b/nodejs/src/servers/ingestion-session-replay-ml-mirror-server.ts
new file mode 100644
index 000000000000..d752e678f881
--- /dev/null
+++ b/nodejs/src/servers/ingestion-session-replay-ml-mirror-server.ts
@@ -0,0 +1,170 @@
+import { GetObjectCommand, S3Client } from '@aws-sdk/client-s3'
+
+import { initializePrometheusLabels } from '~/common/api/router'
+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 { getDefaultKafkaDownstreamProducerEnvConfig } from '~/ingestion/common/producers'
+import { getDefaultIngestionConsumerConfig } from '~/ingestion/config'
+import { AllowListFetcher, loadAllowLists } from '~/ingestion/pipelines/sessionreplay/anonymize/allow-list-loader'
+import { ScrubContext } from '~/ingestion/pipelines/sessionreplay/anonymize/config'
+import {
+ type SessionReplayProducerName,
+ getDefaultSessionRecordingApiConfig,
+ getDefaultSessionRecordingConfig,
+ getDefaultSessionReplayOutputsConfig,
+} from '~/ingestion/pipelines/sessionreplay/config'
+import {
+ SessionRecordingIngester,
+ SessionRecordingIngesterCollaborators,
+} from '~/ingestion/pipelines/sessionreplay/consumer'
+import { MlMirrorConfig, getDefaultMlMirrorConfig } from '~/ingestion/pipelines/sessionreplay/ml-mirror/config'
+import { MlBlockMetadataSink } from '~/ingestion/pipelines/sessionreplay/ml-mirror/ml-block-metadata-sink'
+import { createMlMirrorReplayPipeline } from '~/ingestion/pipelines/sessionreplay/ml-mirror/ml-mirror-pipeline'
+import { resolvePseudonymKey } from '~/ingestion/pipelines/sessionreplay/ml-mirror/pseudonym-key'
+import { createProducerRegistry } from '~/ingestion/pipelines/sessionreplay/outputs/producer-registry'
+import { createOutputsRegistry } from '~/ingestion/pipelines/sessionreplay/outputs/registry'
+import { BlackholeSessionBatchFileStorage } from '~/ingestion/pipelines/sessionreplay/sessions/blackhole-session-batch-writer'
+import { S3SessionBatchFileStorage } from '~/ingestion/pipelines/sessionreplay/sessions/s3-session-batch-writer'
+import { SessionConsoleLogStore } from '~/ingestion/pipelines/sessionreplay/sessions/session-console-log-store'
+import { CleartextRecordingEncryptor } from '~/ingestion/pipelines/sessionreplay/shared/crypto/cleartext-encryptor'
+import { SessionFeatureStore } from '~/ingestion/pipelines/sessionreplay/shared/features/session-feature-store'
+import { CleartextKeyStore } from '~/ingestion/pipelines/sessionreplay/shared/keystore/cleartext-keystore'
+import { getDefaultKafkaSessionreplayProducerEnvConfig } from '~/ingestion/pipelines/sessionreplay/shared/outputs/producer-config'
+import { buildSessionRecordingS3Client } from '~/ingestion/pipelines/sessionreplay/shared/s3-client'
+
+import { RedisPool } from '../types'
+import { CleanupResources, NodeServer, ServerLifecycle } from './base-server'
+import { IngestionSessionReplayServerConfig, buildSessionReplayRedisPools } from './ingestion-session-replay-server'
+
+/** Full config for an ML mirror deployment: the primary replay config plus ML knobs. */
+export type IngestionSessionReplayMlMirrorServerConfig = IngestionSessionReplayServerConfig & MlMirrorConfig
+
+/** Assembles the ML-mirror config; shared by the mirror ingester and the Parquet-sink deployments. */
+export function buildMlMirrorServerConfig(
+ config: Partial<IngestionSessionReplayMlMirrorServerConfig>
+): IngestionSessionReplayMlMirrorServerConfig {
+ return {
+ ...defaultConfig,
+ ...overrideConfigWithEnv(getDefaultIngestionConsumerConfig()),
+ ...overrideConfigWithEnv(getDefaultKafkaDownstreamProducerEnvConfig()),
+ ...overrideConfigWithEnv(getDefaultKafkaSessionreplayProducerEnvConfig()),
+ ...overrideConfigWithEnv({
+ ...getDefaultSessionRecordingConfig(),
+ // Distinct default group id so the mirror gets its own copy of every recording rather than
+ // splitting the snapshot topic's partitions with the primary ingester (still env-overridable).
+ INGESTION_SESSION_REPLAY_CONSUMER_GROUP_ID: 'session-replay-ml-mirror',
+ }),
+ ...overrideConfigWithEnv(getDefaultSessionRecordingApiConfig()),
+ ...overrideConfigWithEnv(getDefaultSessionReplayOutputsConfig()),
+ ...overrideConfigWithEnv(getDefaultMlMirrorConfig()),
+ ...config,
+ }
+}
+
+export class IngestionSessionReplayMlMirrorServer implements NodeServer {
+ readonly lifecycle: ServerLifecycle
+ private config: IngestionSessionReplayMlMirrorServerConfig
+
+ private postgres?: PostgresRouter
+ private producerRegistry?: KafkaProducerRegistry<SessionReplayProducerName>
+ private redisPool?: RedisPool
+ private restrictionRedisPool?: RedisPool
+
+ constructor(config: Partial<IngestionSessionReplayMlMirrorServerConfig> = {}) {
+ this.config = buildMlMirrorServerConfig(config)
+ this.lifecycle = new ServerLifecycle(this.config)
+ }
+
+ async start(): Promise<void> {
+ return this.lifecycle.start(
+ () => this.startServices(),
+ () => this.getCleanupResources()
+ )
+ }
+
+ async stop(error?: Error): Promise<void> {
+ return this.lifecycle.stop(() => this.getCleanupResources(), error)
+ }
+
+ private async startServices(): Promise<void> {
+ initializePrometheusLabels(this.config.INGESTION_PIPELINE, this.config.INGESTION_LANE)
+
+ this.postgres = new PostgresRouter(this.config, this.config.PLUGIN_SERVER_MODE ?? undefined)
+ this.producerRegistry = await createProducerRegistry(this.config.KAFKA_CLIENT_RACK).build(this.config)
+ const outputs = createOutputsRegistry().build(this.producerRegistry, this.config)
+
+ const pools = buildSessionReplayRedisPools(this.config)
+ this.redisPool = pools.redisPool
+ this.restrictionRedisPool = pools.restrictionRedisPool
+
+ const s3Client = buildSessionRecordingS3Client(this.config)
+ const bucket = this.config.SESSION_RECORDING_V2_S3_BUCKET
+ const prefix = this.config.SESSION_RECORDING_V2_S3_PREFIX
+
+ const pseudonymSecret = await resolvePseudonymKey(this.config)
+
+ // Anonymized blocks are written unencrypted, in a single prefix (no retention sharding).
+ const fileStorage = s3Client
+ ? 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)),
+ }
+
+ // Block metadata is produced to Kafka; the dedicated Parquet-sink deployment writes it to the ML bucket.
+ const metadataStore = new MlBlockMetadataSink(outputs, pseudonymSecret)
+
+ // Cleartext crypto: no encryption, deletions not honored (every session stays cleartext).
+ const keyStore = new CleartextKeyStore()
+ const collaborators: SessionRecordingIngesterCollaborators = {
+ fileStorage,
+ metadataStore,
+ // Console logs and ML features are not mirrored.
+ consoleLogStore: new SessionConsoleLogStore(outputs, {
+ messageLimit: this.config.SESSION_RECORDING_V2_CONSOLE_LOG_STORE_SYNC_BATCH_LIMIT,
+ enabled: false,
+ }),
+ featureStore: new SessionFeatureStore(outputs, false),
+ keyStore,
+ encryptor: new CleartextRecordingEncryptor(keyStore),
+ createPipeline: (pipelineConfig) => createMlMirrorReplayPipeline({ ...pipelineConfig, scrubContext }),
+ }
+
+ const ingester = new SessionRecordingIngester(
+ this.config,
+ this.postgres,
+ outputs,
+ this.redisPool,
+ this.restrictionRedisPool,
+ collaborators
+ )
+ await ingester.start()
+ this.lifecycle.services.push(ingester.service)
+ }
+
+ private buildAllowListFetcher(s3Client: S3Client | null, bucket: string): AllowListFetcher | undefined {
+ const key = this.config.SESSION_RECORDING_ML_ALLOW_LIST_S3_KEY
+ if (!s3Client || !key) {
+ return undefined
+ }
+ return async () => {
+ const response = await s3Client.send(new GetObjectCommand({ Bucket: bucket, Key: key }))
+ const body = await response.Body?.transformToString()
+ return body ? parseJSON(body) : {}
+ }
+ }
+
+ private getCleanupResources(): CleanupResources {
+ return {
+ kafkaProducers: [],
+ redisPools: [this.redisPool, this.restrictionRedisPool].filter(Boolean) as RedisPool[],
+ postgres: this.postgres,
+ additionalCleanup: async () => {
+ await this.producerRegistry?.disconnectAll()
+ },
+ }
+ }
+}
diff --git a/nodejs/src/servers/ingestion-session-replay-ml-parquet-sink-server.test.ts b/nodejs/src/servers/ingestion-session-replay-ml-parquet-sink-server.test.ts
new file mode 100644
index 000000000000..4f076400b5ba
--- /dev/null
+++ b/nodejs/src/servers/ingestion-session-replay-ml-parquet-sink-server.test.ts
@@ -0,0 +1,33 @@
+import { S3Client } from '@aws-sdk/client-s3'
+
+import { buildMlMirrorServerConfig } from './ingestion-session-replay-ml-mirror-server'
+import { buildSinkConsumerConfig, requireS3Client } from './ingestion-session-replay-ml-parquet-sink-server'
+
+describe('Parquet sink wiring', () => {
+ describe('buildSinkConsumerConfig', () => {
+ it('uses manual offsets so a flush commits only after the S3 write (at-least-once)', () => {
+ const config = buildSinkConsumerConfig(buildMlMirrorServerConfig({}))
+ expect(config.autoOffsetStore).toBe(false)
+ expect(config.autoCommit).toBe(true)
+ expect(config.callEachBatchWhenEmpty).toBe(true)
+ })
+
+ it('consumes the ML metadata topic under the sink group id', () => {
+ const merged = buildMlMirrorServerConfig({})
+ const config = buildSinkConsumerConfig(merged)
+ expect(config.topic).toBe(merged.INGESTION_SESSIONREPLAY_OUTPUT_ML_BLOCK_METADATA_TOPIC)
+ expect(config.groupId).toBe(merged.SESSION_RECORDING_ML_PARQUET_SINK_GROUP_ID)
+ })
+ })
+
+ describe('requireS3Client', () => {
+ it('throws when S3 is not configured (the sink writes unencrypted, must not silently no-op)', () => {
+ expect(() => requireS3Client(null)).toThrow('SESSION_RECORDING_V2_S3_')
+ })
+
+ it('passes a configured client through', () => {
+ const client = {} as S3Client
+ expect(requireS3Client(client)).toBe(client)
+ })
+ })
+})
diff --git a/nodejs/src/servers/ingestion-session-replay-ml-parquet-sink-server.ts b/nodejs/src/servers/ingestion-session-replay-ml-parquet-sink-server.ts
new file mode 100644
index 000000000000..bb3af39d7144
--- /dev/null
+++ b/nodejs/src/servers/ingestion-session-replay-ml-parquet-sink-server.ts
@@ -0,0 +1,106 @@
+import { S3Client } from '@aws-sdk/client-s3'
+
+import { initializePrometheusLabels } from '~/common/api/router'
+import { KafkaConsumer, KafkaConsumerConfig } from '~/common/kafka/consumer/consumer-v1'
+import { logger } from '~/common/utils/logger'
+import { BlockMetadataBatcher } from '~/ingestion/pipelines/sessionreplay/ml-mirror/block-metadata-batcher'
+import { BlockMetadataParquetStore } from '~/ingestion/pipelines/sessionreplay/ml-mirror/block-metadata-parquet-store'
+import { buildSessionRecordingS3Client } from '~/ingestion/pipelines/sessionreplay/shared/s3-client'
+
+import { CleanupResources, NodeServer, ServerLifecycle } from './base-server'
+import {
+ IngestionSessionReplayMlMirrorServerConfig,
+ buildMlMirrorServerConfig,
+} from './ingestion-session-replay-ml-mirror-server'
+
+/** The Parquet sink writes unencrypted data, so a misconfigured (absent) S3 client must fail loudly, not silently no-op. */
+export function requireS3Client(client: S3Client | null): S3Client {
+ if (!client) {
+ throw new Error('SESSION_RECORDING_V2_S3_* must be configured for the ML Parquet sink')
+ }
+ return client
+}
+
+/**
+ * Manual offsets + callEachBatchWhenEmpty: the batcher rolls rows up across batches and stores offsets only after a
+ * flush lands in S3, so a failed write replays the window (at-least-once) and idle polls still flush.
+ */
+export function buildSinkConsumerConfig(config: IngestionSessionReplayMlMirrorServerConfig): KafkaConsumerConfig {
+ return {
+ topic: config.INGESTION_SESSIONREPLAY_OUTPUT_ML_BLOCK_METADATA_TOPIC,
+ groupId: config.SESSION_RECORDING_ML_PARQUET_SINK_GROUP_ID,
+ autoCommit: true,
+ autoOffsetStore: false,
+ callEachBatchWhenEmpty: true,
+ }
+}
+
+/** Drains the ML block-metadata topic, rolling rows up into one Parquet object per flush interval in the ML bucket. */
+export class IngestionSessionReplayMlParquetSinkServer implements NodeServer {
+ readonly lifecycle: ServerLifecycle
+ private config: IngestionSessionReplayMlMirrorServerConfig
+
+ constructor(config: Partial<IngestionSessionReplayMlMirrorServerConfig> = {}) {
+ this.config = buildMlMirrorServerConfig(config)
+ this.lifecycle = new ServerLifecycle(this.config)
+ }
+
+ async start(): Promise<void> {
+ return this.lifecycle.start(
+ () => this.startServices(),
+ () => this.getCleanupResources()
+ )
+ }
+
+ async stop(error?: Error): Promise<void> {
+ return this.lifecycle.stop(() => this.getCleanupResources(), error)
+ }
+
+ private async startServices(): Promise<void> {
+ initializePrometheusLabels(this.config.INGESTION_PIPELINE, this.config.INGESTION_LANE)
+
+ const s3Client = requireS3Client(buildSessionRecordingS3Client(this.config))
+ const store = new BlockMetadataParquetStore(
+ s3Client,
+ this.config.SESSION_RECORDING_V2_S3_BUCKET,
+ this.config.SESSION_RECORDING_ML_METADATA_PREFIX
+ )
+
+ const consumer = new KafkaConsumer(buildSinkConsumerConfig(this.config))
+ const batcher = new BlockMetadataBatcher(
+ store,
+ consumer,
+ {
+ flushIntervalMs: this.config.SESSION_RECORDING_ML_PARQUET_FLUSH_INTERVAL_MS,
+ maxRows: this.config.SESSION_RECORDING_ML_PARQUET_MAX_ROWS,
+ },
+ Date.now()
+ )
+ await consumer.connect((messages) => {
+ consumer.heartbeat()
+ return batcher.handleBatch(messages, Date.now())
+ })
+
+ this.lifecycle.services.push({
+ id: 'session-replay-ml-parquet-sink',
+ // Flush the buffer so a graceful restart doesn't re-process it, then disconnect.
+ // A failed final flush is non-fatal (the window replays on restart) but must be visible.
+ onShutdown: async () => {
+ try {
+ await batcher.flush(Date.now())
+ } catch (error) {
+ logger.warn('🪶', 'ml_parquet_sink_shutdown_flush_failed', { error: String(error) })
+ }
+ await consumer.disconnect()
+ },
+ healthcheck: () => consumer.isHealthy(),
+ })
+ }
+
+ private getCleanupResources(): CleanupResources {
+ return {
+ kafkaProducers: [],
+ redisPools: [],
+ }
+ }
+}
diff --git a/nodejs/src/servers/ingestion-session-replay-server.ts b/nodejs/src/servers/ingestion-session-replay-server.ts
index 85b47d5c8dd0..b1fb4e7676e0 100644
--- a/nodejs/src/servers/ingestion-session-replay-server.ts
+++ b/nodejs/src/servers/ingestion-session-replay-server.ts
@@ -54,6 +54,44 @@ export type IngestionSessionReplayServerConfig = BaseServerConfig &
'LOG_LEVEL' | 'PLUGIN_SERVER_MODE' | 'HEALTHCHECK_MAX_STALE_SECONDS' | 'KAFKA_HEALTHCHECK_SECONDS'
>
+/** Builds the session-recording and restriction Redis pools a replay deployment needs. */
+export function buildSessionReplayRedisPools(config: IngestionSessionReplayServerConfig): {
+ redisPool: RedisPool
+ restrictionRedisPool: RedisPool
+} {
+ const redisPool = createRedisPoolFromConfig({
+ connection: config.POSTHOG_SESSION_RECORDING_REDIS_HOST
+ ? {
+ url: config.POSTHOG_SESSION_RECORDING_REDIS_HOST,
+ options: { port: config.POSTHOG_SESSION_RECORDING_REDIS_PORT ?? 6379 },
+ name: 'session-recording-redis',
+ }
+ : { url: config.REDIS_URL, name: 'session-recording-redis-fallback' },
+ poolMinSize: config.REDIS_POOL_MIN_SIZE,
+ poolMaxSize: config.REDIS_POOL_MAX_SIZE,
+ })
+
+ const restrictionRedisPool = createRedisPoolFromConfig({
+ connection: config.INGESTION_REDIS_HOST
+ ? {
+ url: config.INGESTION_REDIS_HOST,
+ options: { port: config.INGESTION_REDIS_PORT },
+ name: 'ingestion-redis',
+ }
+ : config.POSTHOG_REDIS_HOST
+ ? {
+ url: config.POSTHOG_REDIS_HOST,
+ options: { port: config.POSTHOG_REDIS_PORT, password: config.POSTHOG_REDIS_PASSWORD },
+ name: 'ingestion-redis',
+ }
+ : { url: config.REDIS_URL, name: 'ingestion-redis' },
+ poolMinSize: config.REDIS_POOL_MIN_SIZE,
+ poolMaxSize: config.REDIS_POOL_MAX_SIZE,
+ })
+
+ return { redisPool, restrictionRedisPool }
+}
+
export class IngestionSessionReplayServer implements NodeServer {
readonly lifecycle: ServerLifecycle
private config: IngestionSessionReplayServerConfig
@@ -99,37 +137,9 @@ export class IngestionSessionReplayServer implements NodeServer {
const outputs = createOutputsRegistry().build(this.producerRegistry, this.config)
logger.info('👍', 'Kafka ready')
- // Session recording uses its own Redis instance with fallback to default
- this.redisPool = createRedisPoolFromConfig({
- connection: this.config.POSTHOG_SESSION_RECORDING_REDIS_HOST
- ? {
- url: this.config.POSTHOG_SESSION_RECORDING_REDIS_HOST,
- options: { port: this.config.POSTHOG_SESSION_RECORDING_REDIS_PORT ?? 6379 },
- name: 'session-recording-redis',
- }
- : { url: this.config.REDIS_URL, name: 'session-recording-redis-fallback' },
- poolMinSize: this.config.REDIS_POOL_MIN_SIZE,
- poolMaxSize: this.config.REDIS_POOL_MAX_SIZE,
- })
-
- // Restriction manager needs to read from the same Redis as Django writes to
- this.restrictionRedisPool = createRedisPoolFromConfig({
- connection: this.config.INGESTION_REDIS_HOST
- ? {
- url: this.config.INGESTION_REDIS_HOST,
- options: { port: this.config.INGESTION_REDIS_PORT },
- name: 'ingestion-redis',
- }
- : this.config.POSTHOG_REDIS_HOST
- ? {
- url: this.config.POSTHOG_REDIS_HOST,
- options: { port: this.config.POSTHOG_REDIS_PORT, password: this.config.POSTHOG_REDIS_PASSWORD },
- name: 'ingestion-redis',
- }
- : { url: this.config.REDIS_URL, name: 'ingestion-redis' },
- poolMinSize: this.config.REDIS_POOL_MIN_SIZE,
- poolMaxSize: this.config.REDIS_POOL_MAX_SIZE,
- })
+ const pools = buildSessionReplayRedisPools(this.config)
+ this.redisPool = pools.redisPool
+ this.restrictionRedisPool = pools.restrictionRedisPool
const ingester = new SessionRecordingIngester(
this.config,
diff --git a/nodejs/tests/ingestion/pipelines/sessionreplay/sessions/session-batch-file-format.integration.test.ts b/nodejs/tests/ingestion/pipelines/sessionreplay/sessions/session-batch-file-format.integration.test.ts
index 5c564540d6b0..b80ac24a18b5 100644
--- a/nodejs/tests/ingestion/pipelines/sessionreplay/sessions/session-batch-file-format.integration.test.ts
+++ b/nodejs/tests/ingestion/pipelines/sessionreplay/sessions/session-batch-file-format.integration.test.ts
@@ -191,6 +191,7 @@ describe('session recording integration', () => {
team: {
teamId,
consoleLogIngestionEnabled: false,
+ aiTrainingOptedIn: true,
},
message: {
distinct_id: 'distinct_id',
diff --git a/nodejs/tests/ingestion/pipelines/sessionreplay/sessions/session-encryption.integration.test.ts b/nodejs/tests/ingestion/pipelines/sessionreplay/sessions/session-encryption.integration.test.ts
index 34eda4498df1..bcfdbef92eaa 100644
--- a/nodejs/tests/ingestion/pipelines/sessionreplay/sessions/session-encryption.integration.test.ts
+++ b/nodejs/tests/ingestion/pipelines/sessionreplay/sessions/session-encryption.integration.test.ts
@@ -179,6 +179,7 @@ describe('session recording encryption integration', () => {
team: {
teamId,
consoleLogIngestionEnabled: false,
+ aiTrainingOptedIn: true,
},
message: {
distinct_id: 'distinct_id',
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 620cb6f1f098..fee46f7b8461 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -1457,6 +1457,9 @@ importers:
'@connectrpc/connect-node':
specifier: ^2.1.1
version: 2.1.1(@bufbuild/[email protected])(@connectrpc/[email protected](@bufbuild/[email protected]))
+ '@dsnp/parquetjs':
+ specifier: ^1.8.7
+ version: 1.8.7
'@google-cloud/pubsub':
specifier: 4.11.0
version: 4.11.0([email protected])
@@ -1637,6 +1640,9 @@ importers:
re2:
specifier: ^1.22.1
version: 1.22.1
+ sharp:
+ specifier: ^0.34.5
+ version: 0.34.5
snappy:
specifier: ^7.2.2
version: 7.2.2
@@ -6415,6 +6421,10 @@ packages:
peerDependencies:
react: 18.3.1
+ resolution: {integrity: sha512-3DkkN3FKJ++BQy8PE3LONoVSVBONG7hld9D+VqBp1Dcfw2PGSnWyg20NET5cJkiygWK2y2H1ra8GWk3yixzuuA==}
+ engines: {node: '>=18.18.2'}
+
'@earendil-works/[email protected]':
resolution: {integrity: sha512-LHygOgsW2pgXKb3IkXkOAeZPovHr9VF+EixgXVsDNuB4jmhEOXgshy/zksZ7slkUAx10OQ9W1Ed/2jsnhd1NqA==}
engines: {node: '>=22.19.0'}
@@ -6442,9 +6452,6 @@ packages:
'@emnapi/[email protected]':
resolution: {integrity: sha512-55coeOFKHv1ywEcUXJtWU5f+Jr/W5tZDvZig8DLKSwUN1JpROQ4rk/SNOQiFWmaR/VKF4zuFyW1B8JduOSv6Pg==}
- '@emnapi/[email protected]':
- resolution: {integrity: sha512-mehfKSMWjjNol8659Z8KxEMrdSJDDot5SXMq00dM8BN4o+CLNXQ0xH2V7EchNHV4RmbZLmmPdEaXZc5H2FXmDg==}
-
'@emnapi/[email protected]':
resolution: {integrity: sha512-3U4+MIWHImeyu1wnmVygh5WlgfYDtyf0k8AbLhMFxOipihf6nrWC4syIm/SwEeec0mNSafiiNnMJwbza/Is6Lw==}
@@ -12609,6 +12616,9 @@ packages:
resolution: {integrity: sha512-1ZX9fcN4Rvkvgv4E6PAY5WXUFWFcRWxZa3EW83UjycOB9ljJCedb2CupIP4RZMEwF/M3eTcCihbBRgwtGbg5Rg==}
+ '@types/[email protected]':
+ resolution: {integrity: sha512-xf/JsSlnXQ+mzvc0IpXemcrO4BrCfpgNpMco+GLcXkFk01k/gW9lGJu+Vof0ZSvHK6DsHJDPSbjFPs36QkWXqw==}
+
resolution: {integrity: sha512-NiTwl8YN3v/1YCKrDFSmCTkVxFDylueEqsOFdgF+vPsm+AlyJKGAo5yzX1FiOxPsZiN6/r8gJitYx2EaSuBmmg==}
@@ -12666,6 +12676,9 @@ packages:
resolution: {integrity: sha512-JCB8C6SnDoQf0cNycqd/35A7MjcnK+ZTqE7judS6o7utxUCg6imJg3QK2qzHKszlTjcj2cn+NwMB2i96ubpj7w==}
+ '@types/[email protected]':
+ resolution: {integrity: sha512-hroOstUScF6zhIi+5+x0dzqrHA1EJi+Irri6b1fxolMTqqHIV/Cg77EtnQcZqZCu8hR3mX2BzIxN4/GzI68Kfw==}
+
resolution: {integrity: sha512-GZHUBZR9hckSUhrxmp1nG6NwdpM9fCunJwyThLW1X3AyHgd9IlHb6VANpQQqDr2o/qQp6McZ3y/IA2rVzKzSbw==}
@@ -12754,6 +12767,9 @@ packages:
resolution: {integrity: sha512-SBwbxYoyPIvxHbeHxTZX2Pe/74F/tX2/D3mMvzabdeJ25bBojfW0TyB8BHrbq/9zaaKICJZjLP+8r6AeZMFCuQ==}
+ '@types/[email protected]':
+ resolution: {integrity: sha512-bDX6d5a5ZDWC81tgDv224n/3PKNYfIQJTPHzlbk4vBWJrYXF6Tg1ncaVmP/c3JbGN2AK9p7zmHorJC2D6oejGQ==}
+
resolution: {integrity: sha512-Q5vtl1W5ue16D+nIaW8JWebSSraJVlK+EthKn7e7UcD4KWsaSJ8BqGPXNaPghgtcn/fhvrN17Tv8ksUsQpiplw==}
@@ -13305,6 +13321,9 @@ packages:
resolution: {integrity: sha512-A9gOqLdi6cV4ibazAjcQufGj0B1y/vDqYrcuP6d/6x8P27gRS8643Dj9o1dEKtB6O7fwxb2FgBmJS2mX7gpvdw==}
engines: {node: '>=14.6'}
+ '@xterm/[email protected]':
+ resolution: {integrity: sha512-hqJHYaQb5OptNunnyAnkHyM8aCjZ1MEIDTQu1iIbbTD/xops91NB5yq1ZK/dC2JDbVWtF23zUtl9JE2NqwT87A==}
+
resolution: {integrity: sha512-DX8nKgqcGwsc0eJSqYt5lwP4DH5FlHnmuWWBRy7X0NcaGR0ZtuyeESgMwTYVEtxmsNGY+qit4QYT/MIYTOTPeA==}
@@ -13320,6 +13339,11 @@ packages:
'@xyflow/[email protected]':
resolution: {integrity: sha512-1YpBo0WgmZLR5wQw9Jvk3Tu0gISi/oYc4uSimrDuAsA/G2rGleulLrKkM59uuT/QU5m6DYC2VdBDAzjSNMGuBA==}
+ '@zenfs/[email protected]':
+ resolution: {integrity: sha512-jFihhedKitw1X9rlImtaca4KTs1Xk9awo4GxUemqt2ucE1jLi10lyRfFFbiYXZsFDkuCWGHwEQwv7BeDIEXMbQ==}
+ engines: {node: '>= 18'}
+ hasBin: true
+
resolution: {integrity: sha512-j2afSsaIENvHZN2B8GOpF566vZ5WVk5opAiMTvWgaQT8DkbOqsTfvNAvHoRGU2zzP8cPoqys+xHTRDWW8L+/BA==}
deprecated: Use your platform's native atob() and btoa() methods instead
@@ -13631,6 +13655,9 @@ packages:
resolution: {integrity: sha512-hsU18Ae8CDTR6Kgu9DYf0EbCr/a5iGL0rytQDobUcdpYOKokk8LEjVphnXkDkgpi0wYVsqrXuP0bZxJaTqdgoA==}
engines: {node: '>= 0.4'}
+ resolution: {integrity: sha512-csOlWGAcRFJaI6m+F2WKdnMKr4HhdhFVBk0H/QbJFMCr+uO2kwohwXQPxw/9OCxp05r5ghVBFSyioixx3gfkNQ==}
+
resolution: {integrity: sha512-1A94B18jkJ3DYq284ohPxoXbfTA5HsQ7/Mf4DEhcyLx3Bz27Rh59iScbB6EPiP+B+joue6YCxcMXSbFC1tZKwA==}
@@ -13919,6 +13946,13 @@ packages:
resolution: {integrity: sha512-cKV8tMCEpQs4hK/ik71d6LrPOnpkpGBR0wzxqr68g2m/LB2GxVYQroAjMJZRVM1Y4BCjCKc3vAamxSzOY2RP+w==}
+ resolution: {integrity: sha512-U3K72/JAi3jITpdhZBqzSUq+DUY697tLxOuFXB+FpAE/Ug+5C3VZrv4uA674EUZHxNAuQ9wETXNqQkxZD6oL4A==}
+ engines: {node: '>=v18.0.0'}
+
+ resolution: {integrity: sha512-0F2z/VSnLbmEeBcUrSuDH5l0HxTXdQQzLjkmBR4cYfvg1zJrKSlmIZFqyFR8oX0NrwPhy3c3HQ6i3OxMbew4Tg==}
+
resolution: {integrity: sha512-9o5UecI3GhkpM6DrXr69PblIuWxPKk9Y0jHBRhdocZ2y7YECBFCsHm79Pr3OyR2AvjhDkabFJaDJMYRazHgsow==}
@@ -13955,6 +13989,10 @@ packages:
resolution: {integrity: sha512-gQxTNE/GAfIIrmHLUE3oJyp5FO6HRBfhjnw4/wMmA63ZGDJnWBmgY/lyQBpnDUkGmAhbSe39tx2d/iTOAfglwQ==}
+ resolution: {integrity: sha512-MTxGsqgYTwfshYWTRdmZRC+M7FnG1b4y7RO7p2k3X24Wq0yv1m77Wsj0BzlPzd/IowgESfsruQCUToa7vbOpPQ==}
+ engines: {node: '>=16.20.1'}
+
resolution: {integrity: sha512-gvW7InbIyF8AicrqWoptdW08pUxuhq8BEgowNajy9RhiE86fmGAGl+bLKo6oB8QP0CkqHLowfN0oJdKC/J6LbA==}
@@ -16698,6 +16736,9 @@ packages:
engines: {node: '>=18'}
hasBin: true
+ resolution: {integrity: sha512-u8BMiMa05OPBgd32CKTead0CVTsFVgwFk23nNXo1teKPF6Sxcu0lXxEzP//zTcaKzXbGgPDXGmj/woyv+I4C5w==}
+
resolution: {integrity: sha512-Xj6dv+PsbtwyPpEflsejS+oIZxmMlV44zAhG479uYu89MsjcYOhCFnNyKrkJrihbsiasQyY0afoCl/9BLR65bg==}
engines: {node: '>= 0.4'}
@@ -17025,6 +17066,11 @@ packages:
resolution: {integrity: sha512-WhB9zCku7EGTj/HQQRz5aUQEUeoQZH2bWcltRErOpymJ4boYE6wL9Tbr23krRPSZ+C5zqNSrSw+Cc7sZZ4b7vg==}
engines: {node: '>=0.10.0'}
+ resolution: {integrity: sha512-BhBvN2MBpWTaSHdWRb/bwdZJ1WaehQ2L1KngkCkfLUGF0mAWAT1sQUQacEmQ0jXkFw/czDXPNQSL5u2/Krsz1w==}
+ peerDependencies:
+ ws: '*'
+
resolution: {integrity: sha512-PIeMbHqMt4DnUP3MA/Flc0HElYjMXArsw1qwJZcm9sqR8mq3l8NYizFMty0pWwE/tzIGH3EKK5+jes5mAr85yw==}
@@ -20161,6 +20207,14 @@ packages:
resolution: {integrity: sha512-oTUZM/NAZS8p7ANR3SHh30kXB+zK2r2BPcEn/awJIbOvq82WoMN4p62AWWp3Hhw50G0xMsw1mhIBLqHw64EcNQ==}
+ resolution: {integrity: sha512-kV/CThkXo6xyFEZUugw/+pIOywXcDbFYgSct5cT3gqlbkBE1SJdwy6UQoZvodiWF/ckQLZyDE/Bu1M6gVu5lVw==}
+ engines: {node: '>=0.6.0', teleport: '>=0.2.0'}
+ deprecated: |-
+ You or someone you depend on is using Q, the JavaScript Promise library that gave JavaScript developers strong feelings about promises. They can almost certainly migrate to the native JavaScript promise now. Thank you literally everyone for joining me in this bet against the odds. Be excellent to each other.
+
+ (For a CapTP with native promises, see @endo/eventual-send and @endo/captp)
+
resolution: {integrity: sha512-QpgqWi8rD9DsS9EP3z7BT+5lY5SFhsqGjpgW5DY/i3mK4M9DTBNz3ErMi8BWYEfI3L0d8GIbGmcdFAS1uIRGjA==}
peerDependencies:
@@ -20683,6 +20737,10 @@ packages:
resolution: {integrity: sha512-MuEnA0lbSi7JS8XM+WNJlWZkHAAdm7gETHdFK//Q/mChGyj2akEFtdLZh32jSdkWGbRwCW9pn6g3LWDdDeZnBQ==}
engines: {node: ^12.22.0 || ^14.17.0 || >=16.0.0}
+ resolution: {integrity: sha512-oIGGmcpTLwPga8Bn6/Z75SVaH1z5dUut2ibSyAMVhmUggWpmDn2dapB0n7f8nwaSiRtepAsfJyfXIO5DCVAODg==}
+ engines: {node: ^12.22.0 || ^14.17.0 || >=16.0.0}
+
resolution: {integrity: sha512-hOS089on8RduqdbhvQ5Z37A0ESjsqz6qnRcffsMU3495FuTdqSm+7bhJ29JvIOsBDEEnan5DPu9t3To9VRlMzA==}
engines: {node: '>=8.10.0'}
@@ -21323,6 +21381,9 @@ packages:
resolution: {integrity: sha512-iADMq1kY0v3vJmGTuKcFWSXt15qYUz7wFkArOrsSg0IFfI3nJqIJvK2/ZbEIndg7erIJLtAVX2nSOqPz7DcwbA==}
engines: {node: '>= 10'}
+ resolution: {integrity: sha512-u5iEEXkMe2EInQio6Wv9LWHOQYRDbD2O9hzS27GpT/lwfIQhTCnHCTqedqHIHe9ZcvQo+9au6vngQayipz1NYw==}
+
resolution: {integrity: sha512-HehCEsotFqbPW9sJ8WVYB6UbmIMv7kUUORIF2Nncq4VQvBfNBLibW9YZR5dlYCSUhwcD628pRllm7n+E+YTzJw==}
engines: {node: '>= 14'}
@@ -21991,6 +22052,10 @@ packages:
resolution: {integrity: sha512-kaDqm1DET9pp3NXwR8382WHbnpXnRkN9xGN9dQt3B2+dmXiW8X1SOwmFOxAErEQ47ObhZ96J6yhZNXuyCOL7KA==}
+ resolution: {integrity: sha512-AW8rwHYjeqXisS8B1iwko2gkNMFwSRJ+bO/W0xTGqRspTD3lGHwZx438+pHdOJ3GwpRAnK7TKbjqPOrHAa7ZwQ==}
+ engines: {node: '>= 10.18.0'}
+
resolution: {integrity: sha512-WKexMoJj3vEuK0yFEapj8y64V0A6xcuPuK9Gt1d0R+dzCSJc0lHqQytAbSB4cDAK0dWh4T0E2ETkoLE2WZ41OQ==}
@@ -22669,6 +22734,9 @@ packages:
resolution: {integrity: sha512-6Z7Ma2aVEWisaL6TvBCy7P8rm2LQoPv6dJ7ecIaIixHcwfbJ0x7mWdbcwlIM5IGQxPZSFYeqRCqlOOeKoJYMkw==}
engines: {node: '>= 4'}
+ resolution: {integrity: sha512-GQINDTb/ocyz4acQj3GXAe0wipYxws6L+9ouqaq10KlInTk9DGvW9TJd0pYa/Xu3cppNnZuB4T/sBuSXpcN2ng==}
+
resolution: {integrity: sha512-pMZTvIkT1d+TFGvDOqodOclx0QWkkgi6Tdoa8gC8ffGAAqz9pzPTZWAybbsHHoED/ztMtkv/VoYTYyShUn81hA==}
engines: {node: '>= 0.4.0'}
@@ -23274,6 +23342,17 @@ packages:
resolution: {integrity: sha512-+QU2zd6OTD8XWIJCbffaiQeH9U73qIqafo1x6V1snCWYGJf6cVE0cDR4D8xRzcEnfI21IFrUPzPGtcPf8AC+Rw==}
engines: {node: ^14.17.0 || ^16.13.0 || >=18.0.0}
+ resolution: {integrity: sha512-G0gACQIjFmv7NqpaOAXEpe9nEtRYD6ZCy2Ip/B4EzR08qEwnf/wYJoQd3cjosPdnJsHkeh0j2tzOaIBZIOC1yA==}
+ peerDependencies:
+ bufferutil: ^4.0.1
+ utf-8-validate: ^5.0.2
+ peerDependenciesMeta:
+ bufferutil:
+ optional: true
+ utf-8-validate:
+ optional: true
+
resolution: {integrity: sha512-zS54Oen9bITtp7kp2XM3AydrCIq1D+HwJOuH+c+e4LfpL/lotP5osijd+UoMnxwAam1GN8R4KtLAyIrIcBNpiA==}
engines: {node: '>=8.3.0'}
@@ -23351,6 +23430,9 @@ packages:
resolution: {integrity: sha512-LKYU1iAXJXUgAXn9URjiu+MWhyUXHsvfp7mcuYm9dSUKK0/CjtrUwFAxD82/mCWbtLsGjFIad0wIsod4zrTAEQ==}
engines: {node: '>=0.4'}
+ resolution: {integrity: sha512-147y/6YNh+tlp6nd/2pWq38i9h6mz/EuQ6njIrmW8D1BS5nCqs0P6DG+m6zTGnNz5I+uhZ0SHxBs9BsPrwcKDA==}
+
resolution: {integrity: sha512-AkTuIuVTET12tpsVIQo+ZU6f/qDmKuRUcjaqR+OIvm+aCBsZ95i7UVY5WJ9TMsSaZ0DA2WxoZ4acu0sPH+OKAw==}
@@ -26428,6 +26510,26 @@ snapshots:
react: 18.3.1
tslib: 2.8.1
+ dependencies:
+ '@aws-sdk/client-s3': 3.975.0
+ '@types/node-int64': 0.4.32
+ '@types/thrift': 0.10.17
+ '@zenfs/core': 1.11.4
+ brotli-wasm: 3.0.1
+ bson: 6.10.3
+ int53: 1.0.0
+ long: 5.3.2
+ node-int64: 0.4.0
+ snappyjs: 0.7.0
+ thrift: 0.21.0
+ varint: 6.0.0
+ xxhash-wasm: 1.1.0
+ transitivePeerDependencies:
+ - aws-crt
+ - bufferutil
+ - utf-8-validate
+
dependencies:
'@earendil-works/pi-ai': 0.75.5(@modelcontextprotocol/[email protected](@cfworker/[email protected])([email protected]))([email protected])([email protected])
@@ -26494,11 +26596,6 @@ snapshots:
tslib: 2.8.1
optional: true
- '@emnapi/[email protected]':
- dependencies:
- tslib: 2.8.1
- optional: true
-
'@emnapi/[email protected]':
dependencies:
tslib: 2.8.1
@@ -28435,7 +28532,7 @@ snapshots:
'@napi-rs/[email protected]':
dependencies:
'@emnapi/core': 1.3.1
- '@emnapi/runtime': 1.8.1
+ '@emnapi/runtime': 1.11.0
'@tybys/wasm-util': 0.9.0
optional: true
@@ -33476,6 +33573,10 @@ snapshots:
'@types/node': 22.18.8
form-data: 4.0.5
+ '@types/[email protected]':
+ dependencies:
+ '@types/node': 22.18.8
+
dependencies:
'@types/node': 22.18.8
@@ -33544,6 +33645,8 @@ snapshots:
'@types/[email protected]': {}
+ '@types/[email protected]': {}
+
'@types/[email protected]': {}
'@types/[email protected]': {}
@@ -33653,6 +33756,12 @@ snapshots:
dependencies:
'@types/jest': 30.0.0
+ '@types/[email protected]':
+ dependencies:
+ '@types/node': 22.18.8
+ '@types/node-int64': 0.4.32
+ '@types/q': 1.5.8
+
'@types/[email protected]': {}
'@types/[email protected]': {}
@@ -34334,6 +34443,9 @@ snapshots:
'@xmldom/[email protected]': {}
+ '@xterm/[email protected]':
+ optional: true
+
'@xtuc/[email protected]': {}
'@xtuc/[email protected]': {}
@@ -34359,6 +34471,14 @@ snapshots:
d3-selection: 3.0.0
d3-zoom: 3.0.0
+ '@zenfs/[email protected]':
+ dependencies:
+ '@types/node': 22.18.8
+ buffer: 6.0.3
+ eventemitter3: 5.0.1
+ readable-stream: 4.7.0
+ utilium: 1.10.1
+
@@ -34719,6 +34839,8 @@ snapshots:
+
dependencies:
tslib: 2.8.1
@@ -35086,6 +35208,10 @@ snapshots:
+
+
@@ -35151,6 +35277,8 @@ snapshots:
dependencies:
node-int64: 0.4.0
+
@@ -38477,6 +38605,8 @@ snapshots:
+
dependencies:
get-intrinsic: 1.3.0
@@ -38776,6 +38906,10 @@ snapshots:
+ dependencies:
+ ws: 5.2.5
+
@@ -43677,6 +43811,8 @@ snapshots:
+
dependencies:
react: 18.3.1
@@ -44351,6 +44487,14 @@ snapshots:
events: 3.3.0
process: 0.11.10
+ dependencies:
+ abort-controller: 3.0.0
+ buffer: 6.0.3
+ events: 3.3.0
+ process: 0.11.10
+ string_decoder: 1.3.0
+
dependencies:
picomatch: 2.3.2
@@ -45090,6 +45234,8 @@ snapshots:
'@napi-rs/snappy-win32-ia32-msvc': 7.2.2
'@napi-rs/snappy-win32-x64-msvc': 7.2.2
+
dependencies:
agent-base: 7.1.3
@@ -45941,6 +46087,17 @@ snapshots:
dependencies:
real-require: 0.2.0
+ dependencies:
+ browser-or-node: 1.3.0
+ isomorphic-ws: 4.0.1([email protected])
+ node-int64: 0.4.0
+ q: 1.5.1
+ ws: 5.2.5
+ transitivePeerDependencies:
+ - bufferutil
+ - utf-8-validate
+
@@ -46645,6 +46802,12 @@ snapshots:
+ dependencies:
+ eventemitter3: 5.0.1
+ optionalDependencies:
+ '@xterm/xterm': 5.5.0
+
@@ -47490,6 +47653,10 @@ snapshots:
imurmurhash: 0.1.4
signal-exit: 4.1.0
+ dependencies:
+ async-limiter: 1.0.1
+
@@ -47525,6 +47692,8 @@ snapshots:
+
dependencies:
cuint: 0.2.2