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): run the native ML scrub in the image-scrub consumer (#67436)

Robbiecb308ee90443
diff --git a/Dockerfile.ml-mirror-image-scrub b/Dockerfile.ml-mirror-image-scrub
index 0a82f7852917..3b9129d5110e 100644
--- a/Dockerfile.ml-mirror-image-scrub
+++ b/Dockerfile.ml-mirror-image-scrub
@@ -1,11 +1,15 @@
+# syntax=docker/dockerfile:1.7
#
# Dockerfile.ml-mirror-image-scrub - Session Replay ML-mirror image-scrub sidecar
#
-# An HTTP service that turns raw image bytes into scrubbed bytes (Stage 1 = sharp-only blur). The
-# plugin-server consumer owns Kafka + S3 and calls this over loopback; it runs as a sidecar container.
+# An HTTP service that turns raw image bytes into scrubbed bytes (NSFW gate + solid-fill of detected
+# faces, text, and QR/barcodes). The plugin-server consumer owns Kafka + S3 and calls this over
+# loopback; it runs as a sidecar container. The ML runtime ships in the image: the ONNX Runtime
+# (onnxruntime-node) native binary lands via its install script, zxing is wasm, and the three ONNX
+# models are baked in below — the sidecar makes no network fetches at startup.
#
-# Deliberately NOT the plugin-server workspace build: standalone so its (Stage-2) heavy ML deps stay out
-# of the main image. sharp ships prebuilt libvips; there is no Kafka/S3/ML runtime here in Stage 1.
+# Deliberately NOT the plugin-server workspace build: standalone so the heavy ML deps stay out of the
+# main image. sharp ships prebuilt libvips.
#
# Exact node version pinned to .nvmrc (24.13.0), matching the main Dockerfile's node stages, so the
# build is reproducible instead of drifting with the floating major tag; renovate bumps it. -bookworm-slim
@@ -17,8 +21,9 @@ SHELL ["/bin/bash", "-e", "-o", "pipefail", "-c"]
ARG COMMIT_HASH
RUN echo ${COMMIT_HASH:-unknown} > /code/commit.txt
-# Production deps only (sharp ships libvips prebuilt; prom-client/tsx are pure JS). Only this package is
-# copied (no root pnpm-workspace.yaml), so pnpm treats this dir as its own project root.
+# Production deps only (sharp/libvips and the ML natives ship prebuilt; prom-client/tsx are pure JS).
+# Only this package is copied (no root pnpm-workspace.yaml), so pnpm treats this dir as its own
+# project root.
COPY nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/package.json nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/pnpm-lock.yaml ./
RUN --mount=type=cache,id=pnpm,target=/tmp/pnpm-store-v24 \
corepack enable && \
@@ -29,9 +34,35 @@ COPY nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/
# Tests co-locate in src/ but must not ship in the runtime image.
RUN rm -f src/*.test.ts
+# The ONNX models (safety gate, face, text), pinned to immutable upstream refs and checksum-verified
+# by BuildKit; loadModels() reads them from WORKDIR-relative models/. Keep URLs + digests in sync
+# with dev/setup.ts (the dev-machine download path).
+ADD --checksum=sha256:f139598bc2af4e4b6fe98dec11574e30edfdd91fc94ac1425c18ace3bd5a866b \
+ https://huggingface.co/SWHL/RapidOCR/resolve/1cfba2e90fc938db55889873735088de210cc173/PP-OCRv4/en_PP-OCRv3_det_infer.onnx \
+ models/dbnet_det.onnx
+ADD --checksum=sha256:8f2383e4dd3cfbb4553ea8718107fc0423210dc964f9f4280604804ed2552fa4 \
+ https://github.com/opencv/opencv_zoo/raw/47534e27c9851bb1128ccc0102f1145e27f23f98/models/face_detection_yunet/face_detection_yunet_2023mar.onnx \
+ models/yunet.onnx
+ADD --checksum=sha256:8c28c49d9075f3ad15ebdc2961f02d5b3f99be944815b848b49c9f0e6f3fb689 \
+ https://huggingface.co/OwenElliott/image-safety-classifier-xs/resolve/54f4560bd9c5ee92d45dc30418a8f8680e80de6d/onnx/image-safety-classifier-xs.onnx \
+ models/safety.onnx
+
RUN groupadd -g 10001 posthog && \
useradd -u 10001 -g posthog -m -d /home/posthog posthog && \
chown -R posthog:posthog /code
+
+# One thread per native pool: the sidecar bounds parallelism by its request-concurrency ceiling
+# (IMAGE_SCRUB_CONCURRENCY), so per-op pools sized to host cores would oversubscribe a CPU-limited
+# pod. sharp is pinned at module load in src/blur.ts (sharp.concurrency(1) + cache(false), imported
+# by every scrub path); ORT is pinned per-session (ORT_THREADS).
+ENV OMP_NUM_THREADS=1
+
+# Prove at build time that the models parse, the native/wasm runtimes load, and a scrub runs end to
+# end — a broken model download or prebuilt-binary mismatch fails the image build, not the deploy.
+# --network=none doubles as a guarantee that startup has no network dependency, which is also why
+# tsx is invoked directly: `pnpm` goes through corepack, which wants to fetch pnpm per-user.
+RUN --network=none su posthog -c "node_modules/.bin/tsx src/smoke.ts"
+
USER posthog
ENV NODE_ENV=production
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/README.md b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/README.md
index 9219cb5b7564..1bb7b23c6892 100644
--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/README.md
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/README.md
@@ -11,3 +11,122 @@ It runs a simple http server, receives an image and replies with the scrubbed im
## HTTP contract
`POST /scrub` with the raw image bytes returns the scrubbed bytes (200). The status split is load-bearing and both sides must change together: the consumer permanently skips 413 (too large) and 422 (undecodable), and retries then replays 500 (transient) and 503 (busy). See `scrub-client.ts` for the consumer half.
+
+## The scrub
+
+Given an image, `advancedScrub` (`src/scrub.ts`):
+
+1. **Downscale**: every frame is capped at the `SCRUB_MAX_PIXELS` area budget (default 1600², aspect preserved) inside the decode.
+ This bounds the per-image memory working set, and — since text detection runs under the same area budget — the stored output never carries resolution the detectors didn't certify as clean.
+ An area budget rather than a long-side cap, so tall pages keep legible native resolution instead of being squashed.
+ Faces are detected on a letterboxed (never squashed) 640×640 input; frames beyond 3:1 aspect are tiled along their long axis (overlapping windows) so a face on a tall page stays above the detector's minimum size instead of shrinking past it.
+2. **NSFW/gore gate**: if the image is explicit or gory (NSFL + NSFW probability over `NSFW_THRESHOLD`), it collapses to a 1x1 blank.
+3. **Face redaction**: every detected face (YuNet) is filled with its **mean colour**.
+4. **Text redaction**: every detected text region (DBNet) gets the same fill, with a margin scaled to the box height (= font size).
+ We detect _where_ text is and never read it.
+5. **Code redaction**: every decodable QR/barcode (zxing) gets the same fill — a TOTP provisioning QR or ticket barcode is machine-readable PII that the face/text detectors can't see.
+
+The goal is to protect data labellers and reduce PII exposure.
+It does not need to be perfect; the self-verifying test (below) keeps it honest.
+
+**Why solid fill, not blur/mosaic.** Blur and pixelation are low-pass filters: they remove fine detail but keep coarse structure, so large text (titles, headings) stays legible to a capable reader — we confirmed an LLM could still read blurred titles and the opening sentence of a test page — and a mosaicked face can be re-smoothed back into something a detector finds again.
+A solid, quantized mean-colour fill removes the information entirely, so faces, text, and codes all get it.
+The fill's edges are feathered by blurring the fill's _colour_ only, never the mask, so nothing under a box is ever revealed.
+
+## This is native code, not ML-in-JS
+
+All model inference and image processing run in optimized native libraries.
+The TypeScript is orchestration plus lightweight output decoding (over small downscaled maps, not full images):
+
+| Stage | Library | Native engine |
+| ---------------------------------- | ------------------ | -------------------- |
+| NSFW/gore classify (SwiftFormer) | `onnxruntime-node` | ONNX Runtime (C++) |
+| Face detection (YuNet) | `onnxruntime-node` | ONNX Runtime (C++) |
+| Text detection (DBNet / PP-OCRv3) | `onnxruntime-node` | ONNX Runtime (C++) |
+| QR/barcode detection | `zxing-wasm` | zxing-cpp (C++/wasm) |
+| resize / blur / composite / encode | `sharp` | libvips (C++) |
+
+We do not train anything and run no neural nets in JS.
+The only hand-written JS is model-output decoding (DBNet threshold + dilation + connected components, YuNet anchor decode + NMS, tensor packing, mask fill), which runs over the small detection maps and is not the bottleneck.
+Everything model-shaped runs on ONE runtime (onnxruntime-node) on purpose: a second ML runtime would mean a second native-binary compatibility surface and a second set of failure modes (Node-version coupling, slow fallback backends).
+
+## Layout
+
+`src/` is production (ships in the sidecar image; tests co-locate as `*.test.ts` and are stripped from the image); `dev/` is everything non-production (benchmarks, the eval harness, data setup).
+Production never imports from `dev/`.
+
+```text
+src/ (production — ships)
+ main.ts entrypoint: load models -> start servers
+ server.ts the /scrub + /metrics listeners; scrub implementation injected
+ config.ts env-driven runtime config
+ blur.ts baseline blur (kept in sync with rust/replay-anonymizer-node/src/blur.rs)
+ scrub.ts the ML scrub pipeline: decode-once, NSFW gate, solid-fill of faces/text/codes
+ yunet.ts YuNet face detector (ONNX)
+ dbnet.ts DBNet text-region detector (ONNX)
+ qr.ts QR/barcode detector (zxing-wasm, loaded from node_modules — no egress)
+ src-image.ts decode the source once to raw RGB (area-capped), shared across stages
+ geometry.ts shared Box type + grid rounding
+ safety.ts NSFW/gore gate (SwiftFormer image-safety classifier, ONNX)
+ smoke.ts image-build-time smoke test: models load + one scrub, with networking disabled
+ env.ts validated numeric env knobs — invalid values refuse to start (never fail open)
+ metrics.ts Prometheus registry: HTTP outcomes + scrub outcome signals
+
+dev/ (non-production)
+ scrub-eval.ts OCR + face-redaction eval over downloaded images (npm run eval)
+ verify.ts quick OCR-readability check
+ bench.ts scale.ts worker-proc.ts latency + throughput benchmarks
+ make-corpus.ts synthetic screenshot corpus
+ setup.ts download ONNX models + sample test images (npm run setup)
+
+fixtures/ committed eval fixtures (e.g. a retina Wikipedia page: dense text + a face)
+models/ test-data/ corpus/ out/ downloaded/generated by setup (gitignored)
+```
+
+## Run
+
+```bash
+pnpm install --ignore-workspace # standalone package: own lockfile, outside the root workspace
+npm run setup # download ONNX models + sample test images, generate the corpus
+npm run test:unit # fast unit tests (no models/network)
+npm run eval # scrub-quality suite (text + face) over real images
+npm run bench # latency + per-stage breakdown
+npm run smoke # models load + one scrub end to end (what the image build runs)
+npm run start # the sidecar server (needs `npm run setup` for the models)
+```
+
+If the model/data downloads fail with a TLS chain error, your machine is missing an intermediate CA.
+Point `NODE_EXTRA_CA_CERTS` at a complete bundle (e.g. certifi's `cacert.pem`) rather than disabling certificate validation.
+
+## The self-verifying test
+
+The production path _detects_ text with DBNet (fast).
+The test _reads_ the scrubbed output with OCR (tesseract, a different model doing recognition not detection) and counts confident multi-character words.
+OCR generally reads degraded text better than people, so "OCR can't read it" is a conservative proxy for "a labeller can't".
+The face check re-runs YuNet at high sensitivity on the scrubbed output and asserts no face still sits (by IoU) where one was; a successfully solid-filled face is no longer detectable.
+
+The suite **gates** on session replay's representative domain (crisp rendered-UI text + faces) and **reports** on a harder scanned-document set:
+
+```text
+UI TEXT (gated): 12/12 clean, 0.0% leak [PASS] # rendered screenshots
+DOCUMENT TEXT (report): 18/20 clean, 5.2% worst [report] # faint fax/scan print, out of domain
+FACE: 88/88 faces redacted (100%)
+```
+
+Faint, low-contrast scanned-fax lines occasionally survive.
+That is contrast-limited not size-limited, so resolution alone won't catch every faded line, and it is outside the rendered-UI domain and within the "best-effort, not catastrophic if a little gets through" bar.
+Raise `DET_FACTOR` (env, default 0.75 of the long side) toward 1.0 to spend more CPU on text recall.
+
+## Models are baked into the image
+
+The three ONNX models (safety gate, YuNet, DBNet) are `ADD`ed in `Dockerfile.ml-mirror-image-scrub` (repo root) from commit-pinned upstream URLs with BuildKit `--checksum` verification (same pins + sha256 checks as `dev/setup.ts` — keep them in sync).
+zxing's wasm loads from `node_modules`.
+A build-time smoke test (`src/smoke.ts`) then loads the models and runs one scrub with networking disabled, so a broken model, a native-binary mismatch, or an accidental runtime network dependency fails the image build instead of crash-looping the deploy.
+The sidecar makes no network fetches at startup.
+
+## Observability
+
+Beyond the HTTP outcome counters (scrubbed/failed/undecodable/rejected/too-large/aborted, duration, output bytes), `/metrics` carries the outcome signals a privacy control needs:
+
+- `..._blanked_total` — NSFW-gate blanks are destructive and irreversible; alert on rate spikes.
+- `..._faces_redacted_total`, `..._text_boxes_redacted_total`, `..._codes_redacted_total` — a sustained zero rate under traffic means a detector outage (un-redacted output), not a clean stream.
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/dev/bench.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/dev/bench.ts
new file mode 100644
index 000000000000..e83ff14b040b
--- /dev/null
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/dev/bench.ts
@@ -0,0 +1,186 @@
+/* eslint-disable no-console -- CLI output script: console output is the whole point */
+/**
+ * Throughput benchmark. Runs the corpus through three pipelines and reports images/sec, MB/sec,
+ * p50/p95 latency, and the advanced per-stage breakdown:
+ * 1. blur only (current production baseline)
+ * 2. advanced + heuristic (model-free edge-density text detection)
+ * 3. advanced + dbnet (native ONNX text detection)
+ *
+ * Usage: tsx src/bench.ts [--reps N]
+ */
+import { readFile, readdir } from 'node:fs/promises'
+import { availableParallelism } from 'node:os'
+import sharp from 'sharp'
+
+import {
+ type Models,
+ type StageTimings,
+ type TextMode,
+ advancedScrub,
+ blurOnly,
+ disposeModels,
+ loadModels,
+} from '../src/scrub.ts'
+
+// One libvips thread per sharp op, so image-level concurrency parallelizes across cores instead of
+// each op grabbing every core and oversubscribing.
+sharp.concurrency(1)
+
+const OUT = new URL('../corpus/', import.meta.url).pathname
+const reps = Number(process.argv.includes('--reps') ? process.argv[process.argv.indexOf('--reps') + 1] : 3)
+const cores = availableParallelism()
+
+function pct(xs: number[], p: number): number {
+ const s = [...xs].sort((a, b) => a - b)
+ return s[Math.min(s.length - 1, Math.floor((p / 100) * s.length))]
+}
+const sum = (xs: number[]): number => xs.reduce((a, b) => a + b, 0)
+const fmt = (n: number): string => n.toFixed(1)
+
+interface Img {
+ f: string
+ buf: Buffer
+}
+interface Result {
+ mean: number
+ throughput: number
+ mbps: number
+ p50: number
+ p95: number
+ stages: StageTimings[]
+}
+
+async function runAdvanced(images: Img[], models: Models, mode: TextMode, totalBytes: number): Promise<Result> {
+ await advancedScrub(images[0].buf, models, mode) // warmup
+ const lat: number[] = []
+ const stages: StageTimings[] = []
+ const t0 = performance.now()
+ for (let r = 0; r < reps; r++) {
+ for (const img of images) {
+ const { t } = await advancedScrub(img.buf, models, mode)
+ lat.push(t.totalMs)
+ stages.push(t)
+ }
+ }
+ const wall = (performance.now() - t0) / 1000
+ return {
+ mean: sum(lat) / lat.length,
+ throughput: lat.length / wall,
+ mbps: totalBytes / 1e6 / wall,
+ p50: pct(lat, 50),
+ p95: pct(lat, 95),
+ stages,
+ }
+}
+
+function reportAdvanced(label: string, r: Result, blanked: number, n: number): void {
+ const avg = (k: keyof StageTimings): number => sum(r.stages.map((s) => s[k] as number)) / r.stages.length
+ console.log(`=== ${label} ===`)
+ console.log(` throughput: ${fmt(r.throughput)} img/s/core ${fmt(r.mbps)} MB/s`)
+ console.log(` latency: p50 ${fmt(r.p50)}ms p95 ${fmt(r.p95)}ms mean ${fmt(r.mean)}ms`)
+ console.log(
+ ` blanked: ${blanked}/${n} avg faces ${fmt(avg('faces'))} avg text boxes ${fmt(avg('textBoxes'))}`
+ )
+ console.log(' per-stage mean (ms):')
+ console.log(` decode ${fmt(avg('decodeMs'))} (image in)`)
+ console.log(` nsfw ${fmt(avg('nsfwMs'))}`)
+ console.log(` face ${fmt(avg('faceMs'))}`)
+ console.log(` text ${fmt(avg('textMs'))}`)
+ console.log(` compose ${fmt(avg('composeMs'))}`)
+ console.log(` encode ${fmt(avg('encodeMs'))} (image out)\n`)
+}
+
+async function main(): Promise<void> {
+ const files = (await readdir(OUT)).filter((f) => f.endsWith('.png'))
+ const images = await Promise.all(files.map(async (f) => ({ f, buf: await readFile(OUT + f) })))
+ const totalBytes = sum(images.map((i) => i.buf.length)) * reps
+ const n = images.length * reps
+ console.log(
+ `corpus: ${images.length} images, ${reps} reps = ${n} runs, ${(totalBytes / 1e6).toFixed(1)} MB total\n`
+ )
+
+ // --- 1. baseline: blur only ---
+ await blurOnly(images[0].buf)
+ const blat: number[] = []
+ const bt0 = performance.now()
+ for (let r = 0; r < reps; r++) {
+ for (const img of images) {
+ const t = performance.now()
+ await blurOnly(img.buf)
+ blat.push(performance.now() - t)
+ }
+ }
+ const bwall = (performance.now() - bt0) / 1000
+ const blurMean = sum(blat) / blat.length
+ const blurThroughput = blat.length / bwall
+ console.log('=== BLUR ONLY (current production baseline) ===')
+ console.log(` throughput: ${fmt(blurThroughput)} img/s/core ${fmt(totalBytes / 1e6 / bwall)} MB/s`)
+ console.log(` latency: p50 ${fmt(pct(blat, 50))}ms p95 ${fmt(pct(blat, 95))}ms mean ${fmt(blurMean)}ms\n`)
+
+ // --- 2 + 3. advanced ---
+ console.log('loading models (nsfw + yunet + dbnet)...')
+ const tLoad = performance.now()
+ const models = await loadModels()
+ console.log(` models loaded in ${fmt((performance.now() - tLoad) / 1000)}s\n`)
+
+ const db = await runAdvanced(images, models, 'dbnet', totalBytes)
+ reportAdvanced('ADVANCED + DBNET text (native ONNX detection), single image at a time', db, 0, n)
+
+ // --- concurrency sweep: how much overlaps when we process images in parallel? ---
+ // sharp + the three ORT sessions run async on libuv worker threads
+ // thread, so it can't overlap in-process. This sweep shows the ceiling of in-process async.
+ console.log(`=== CONCURRENCY SWEEP (in-process async, ${cores} cores available) ===`)
+ let best = db.throughput
+ for (const c of [1, 2, 4, 8].filter((c) => c <= cores * 2)) {
+ const tp = await throughputAt(images, models, c)
+ best = Math.max(best, tp)
+ console.log(` concurrency ${c}: ${fmt(tp)} img/s (${fmt(tp / db.throughput)}x vs serial)`)
+ }
+
+ await disposeModels(models)
+
+ // --- headline ---
+ const dbScrub = db.mean - avgOf(db, 'decodeMs') - avgOf(db, 'encodeMs')
+ console.log('\n=== HEADLINE (native: onnxruntime-node) ===')
+ console.log(` blur baseline: ${fmt(blurMean)}ms/img ${fmt(blurThroughput)} img/s/core`)
+ console.log(
+ ` advanced (dbnet): ${fmt(db.mean)}ms/img ${fmt(db.throughput)} img/s/core ${fmt(db.mean / blurMean)}x blur`
+ )
+ console.log(
+ ` dbnet job: scrub ${fmt((dbScrub / db.mean) * 100)}% | decode+encode ${fmt(((avgOf(db, 'decodeMs') + avgOf(db, 'encodeMs')) / db.mean) * 100)}%`
+ )
+ console.log(` best in-process throughput: ${fmt(best)} img/s (async overlap of sharp+ORT)`)
+ console.log(` for full machine scaling use worker_threads/processes,`)
+ console.log(` ~${fmt(db.throughput)} img/s/core x ${cores} cores ≈ ${fmt(db.throughput * cores)} img/s/box.`)
+}
+
+async function throughputAt(images: Img[], models: Models, c: number): Promise<number> {
+ const tasks: Buffer[] = []
+ for (let r = 0; r < reps; r++) {
+ for (const img of images) {
+ tasks.push(img.buf)
+ }
+ }
+ let idx = 0
+ const worker = async (): Promise<void> => {
+ for (;;) {
+ const i = idx++
+ if (i >= tasks.length) {
+ return
+ }
+ await advancedScrub(tasks[i], models, 'dbnet')
+ }
+ }
+ const t0 = performance.now()
+ await Promise.all(Array.from({ length: c }, () => worker()))
+ return tasks.length / ((performance.now() - t0) / 1000)
+}
+
+function avgOf(r: Result, k: keyof StageTimings): number {
+ return sum(r.stages.map((s) => s[k] as number)) / r.stages.length
+}
+
+main().catch((e) => {
+ console.error(e)
+ process.exit(1)
+})
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/dev/make-corpus.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/dev/make-corpus.ts
new file mode 100644
index 000000000000..1a2e83cea873
--- /dev/null
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/dev/make-corpus.ts
@@ -0,0 +1,108 @@
+/* eslint-disable no-console -- CLI output script: console output is the whole point */
+/**
+ * Build a small, representative corpus of session-replay-ish images:
+ * - synthetic "screenshots" (text-heavy UI) at desktop + mobile sizes -> exercises the text path
+ * - a few real photos with faces (fetched; falls back to synthetic if offline) -> exercises faces
+ * Output: ./corpus/*.png (+ manifest.json with byte sizes)
+ */
+import { mkdir, writeFile } from 'node:fs/promises'
+import sharp from 'sharp'
+
+const OUT = new URL('../corpus/', import.meta.url).pathname
+
+function screenshotSvg(w: number, h: number, seed: number): Buffer {
+ const rows: string[] = []
+ const lines = [
+ 'Dashboard Settings Profile Billing Log out',
+ 'Total revenue $48,201.55 +12.4% MoM',
+ '[email protected] +1 (415) 555-0132',
+ 'Card ending 4242 Exp 08/27 CVC •••',
+ 'Order #A1B2C3 Ship to 1200 Market St, San Francisco CA 94103',
+ 'Invoice 2026-0042 Due 2026-07-15 Amount 1,299.00',
+ 'SSN 123-45-6789 DOB 1990-04-12 Acct 0098761234',
+ 'Search results for "quarterly forecast q3 2026"',
+ ]
+ let y = 40
+ for (let i = 0; i < 18; i++) {
+ const text = lines[(i + seed) % lines.length]
+ rows.push(
+ `<text x="32" y="${y}" font-family="Arial" font-size="${14 + ((i + seed) % 6)}" fill="#1f2937">${text}</text>`
+ )
+ y += Math.floor(h / 20)
+ }
+ return Buffer.from(
+ `<svg xmlns="http://www.w3.org/2000/svg" width="${w}" height="${h}">
+ <rect width="${w}" height="${h}" fill="#ffffff"/>
+ <rect width="${w}" height="56" fill="#111827"/>
+ <text x="32" y="36" font-family="Arial" font-size="22" fill="#ffffff">Acme Analytics</text>
+ ${rows.join('\n')}
+ </svg>`
+ )
+}
+
+async function fetchPhoto(url: string, w: number, h: number): Promise<Buffer | null> {
+ try {
+ const res = await fetch(url, { signal: AbortSignal.timeout(15000) })
+ if (!res.ok) {
+ return null
+ }
+ const buf = Buffer.from(await res.arrayBuffer())
+ return await sharp(buf).resize(w, h, { fit: 'cover' }).png().toBuffer()
+ } catch {
+ return null
+ }
+}
+
+async function main(): Promise<void> {
+ await mkdir(OUT, { recursive: true })
+ const manifest: { file: string; bytes: number; kind: string }[] = []
+
+ const sizes: [number, number, string][] = [
+ [1280, 720, 'desktop'],
+ [1440, 900, 'desktop'],
+ [375, 812, 'mobile'],
+ [390, 844, 'mobile'],
+ ]
+ let i = 0
+ for (const [w, h, kind] of sizes) {
+ for (let k = 0; k < 3; k++) {
+ const png = await sharp(screenshotSvg(w, h, i + k))
+ .png()
+ .toBuffer()
+ const file = `shot_${kind}_${w}x${h}_${k}.png`
+ await writeFile(OUT + file, png)
+ manifest.push({ file, bytes: png.length, kind: `screenshot_${kind}` })
+ i++
+ }
+ }
+
+ // Real faces. thispersondoesnotexist serves a fresh synthetic face each hit (no real person, CC-ish).
+ const faceUrls = [
+ 'https://thispersondoesnotexist.com/',
+ 'https://thispersondoesnotexist.com/',
+ 'https://thispersondoesnotexist.com/',
+ ]
+ let faceCount = 0
+ for (let f = 0; f < faceUrls.length; f++) {
+ const photo = await fetchPhoto(faceUrls[f], 512, 512)
+ if (photo) {
+ const file = `face_${f}.png`
+ await writeFile(OUT + file, photo)
+ manifest.push({ file, bytes: photo.length, kind: 'face_photo' })
+ faceCount++
+ }
+ }
+ if (faceCount === 0) {
+ console.warn(
+ '!! no face photos fetched (offline?). Face path will see 0 detections; numbers still valid for cost.'
+ )
+ }
+
+ await writeFile(OUT + 'manifest.json', JSON.stringify(manifest, null, 2))
+ console.log(`corpus: ${manifest.length} images (${faceCount} face photos) in ${OUT}`)
+}
+
+main().catch((e) => {
+ console.error(e)
+ process.exit(1)
+})
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/dev/scale.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/dev/scale.ts
new file mode 100644
index 000000000000..1a93ef7453f2
--- /dev/null
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/dev/scale.ts
@@ -0,0 +1,83 @@
+/* eslint-disable no-console -- CLI output script: console output is the whole point */
+/**
+ * Multi-process scaling test for BOTH pipelines under the same one-core-per-process pin, so the
+ * blur baseline and the advanced path are measured identically and the ratio holds at machine scale.
+ * Spawns W workers (each its own process), each grinds WORK_N images; aggregate img/s =
+ * sum(imgs) / max(processing-window).
+ *
+ * Usage: tsx src/scale.ts [w1 w2 ...] (default: 1 4 8 12)
+ */
+import { spawn } from 'node:child_process'
+import { availableParallelism } from 'node:os'
+
+const WORK_N = process.env.WORK_N ?? '40'
+const widths = process.argv
+ .slice(2)
+ .map(Number)
+ .filter((n) => n > 0)
+const levels = widths.length ? widths : [1, 4, 8, 12]
+const cores = availableParallelism()
+
+function runWorker(mode: string): Promise<{ imgs: number; ms: number }> {
+ return new Promise((resolve, reject) => {
+ const p = spawn('npx', ['tsx', 'dev/worker-proc.ts'], {
+ env: {
+ ...process.env,
+ MODE: mode,
+ WORK_N,
+ // pin every native thread pool to 1 so each worker process ≈ one core
+ TF_NUM_INTRAOP_THREADS: '1',
+ TF_NUM_INTEROP_THREADS: '1',
+ OMP_NUM_THREADS: '1',
+ OPENBLAS_NUM_THREADS: '1',
+ ORT_THREADS: '1',
+ UV_THREADPOOL_SIZE: '2',
+ },
+ })
+ let out = ''
+ let err = ''
+ p.stdout.on('data', (d) => (out += d))
+ p.stderr.on('data', (d) => (err += d))
+ p.on('close', (code) => {
+ const m = out.indexOf('@@R@@')
+ if (code !== 0 || m < 0) {
+ return reject(new Error(`worker exited ${code}: ${err.slice(-200)}`))
+ }
+ resolve(JSON.parse(out.slice(m + 5).trim()))
+ })
+ })
+}
+
+async function sweep(mode: string): Promise<number> {
+ console.log(`\n=== ${mode.toUpperCase()} (one core per process) ===`)
+ let single = 0
+ let best = 0
+ for (const w of levels) {
+ const results = await Promise.all(Array.from({ length: w }, () => runWorker(mode)))
+ const imgs = results.reduce((s, r) => s + r.imgs, 0)
+ const maxMs = Math.max(...results.map((r) => r.ms))
+ const agg = imgs / (maxMs / 1000)
+ if (w === 1) {
+ single = agg
+ }
+ best = Math.max(best, agg)
+ console.log(
+ ` ${String(w).padStart(2)} procs: ${agg.toFixed(1).padStart(7)} img/s (${(agg / single).toFixed(1)}x vs 1 proc)`
+ )
+ }
+ return best
+}
+
+async function main(): Promise<void> {
+ console.log(`machine: ${cores} cores; each worker processes ${WORK_N} images`)
+ const blur = await sweep('blur')
+ const adv = await sweep('advanced')
+ console.log(`\n=== RATIO at machine scale ===`)
+ console.log(` blur peak ${blur.toFixed(0)} img/s advanced peak ${adv.toFixed(0)} img/s`)
+ console.log(` advanced costs ${(blur / adv).toFixed(1)}x the blur baseline at full machine utilization.`)
+}
+
+main().catch((e) => {
+ console.error(e)
+ process.exit(1)
+})
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/dev/scrub-eval.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/dev/scrub-eval.ts
new file mode 100644
index 000000000000..a71198dd3b8c
--- /dev/null
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/dev/scrub-eval.ts
@@ -0,0 +1,180 @@
+/* eslint-disable no-console -- CLI output script: console output is the whole point */
+/**
+ * Test suite over many real images. Two independent checks, both end-to-end through advancedScrub:
+ *
+ * TEXT: OCR (tesseract, a different model than the production DBNet detector) reads the scrubbed
+ * image and counts confident multi-character words; near-zero means the text is gone.
+ *
+ * FACE: locate faces in the ORIGINAL with YuNet, scrub, then re-detect at high sensitivity on the
+ * output; a face still sitting (by IoU) where one was is a leak. A solid-filled face is no
+ * longer detectable, so this measures that redaction actually landed on the face.
+ *
+ * Gates on session replay's representative domain (rendered-UI text + faces) and reports on the
+ * harder scanned-document set. Committed fixtures (e.g. the Wikipedia page) run in both checks.
+ *
+ * npm run test (exits non-zero on a gated text leak or an un-redacted face)
+ */
+import { existsSync } from 'node:fs'
+import { readFile, readdir } from 'node:fs/promises'
+import { basename, join } from 'node:path'
+import sharp from 'sharp'
+import { type Worker, createWorker } from 'tesseract.js'
+
+import { type Models, advancedScrub, loadModels } from '../src/scrub.ts'
+import { decodeSrc } from '../src/src-image.ts'
+import { detectFacesYunet } from '../src/yunet.ts'
+
+const ROOT = new URL('..', import.meta.url).pathname
+const OCR_CONF = 60
+const OCR_UPSCALE = 2
+const OCR_MAX_LONG = 2200 // cap OCR input long side so retina fixtures don't become 30+ megapixels
+const TEXT_LEAK_MAX_PCT = 2 // allow a little sub-lexical OCR noise
+
+async function listImages(dir: string): Promise<string[]> {
+ const p = join(ROOT, dir)
+ if (!existsSync(p)) {
+ return []
+ }
+ return (await readdir(p)).filter((f) => /\.(png|jpg|jpeg)$/i.test(f)).map((f) => join(p, f))
+}
+
+interface Word {
+ text: string
+ confidence: number
+}
+
+async function readableWords(tess: Worker, img: Buffer, W: number, H: number): Promise<number> {
+ // Upscale small images for OCR sensitivity, but cap the long side so a retina screenshot
+ // doesn't balloon to tens of megapixels (slow, and it's already high-res).
+ const scale = Math.max(1, Math.min(OCR_UPSCALE, OCR_MAX_LONG / Math.max(W, H)))
+ const big = await sharp(img)
+ .resize(Math.round(W * scale), Math.round(H * scale), { fit: 'fill' })
+ .png()
+ .toBuffer()
+ const { data } = await tess.recognize(big, {}, { blocks: true })
+ const words = ((data as { words?: Word[] }).words ??
+ (data.blocks ?? []).flatMap((b: any) =>
+ (b.paragraphs ?? []).flatMap((p: any) => (p.lines ?? []).flatMap((l: any) => l.words ?? []))
+ )) as Word[]
+ return words.filter((w) => w.confidence >= OCR_CONF && /[A-Za-z0-9]{2,}/.test(w.text ?? '')).length
+}
+
+interface Box {
+ left: number
+ top: number
+ width: number
+ height: number
+}
+/** Intersection-over-union — used so a stray corner detection that merely touches a large face box
+ * doesn't count as "the face is still there". A real lingering face sits on top of the old one. */
+function iou(a: Box, b: Box): number {
+ const x1 = Math.max(a.left, b.left)
+ const y1 = Math.max(a.top, b.top)
+ const x2 = Math.min(a.left + a.width, b.left + b.width)
+ const y2 = Math.min(a.top + a.height, b.top + b.height)
+ const inter = Math.max(0, x2 - x1) * Math.max(0, y2 - y1)
+ return inter === 0 ? 0 : inter / (a.width * a.height + b.width * b.height - inter)
+}
+const SENSITIVE_FACE = 0.6 // re-detect threshold on the scrubbed image (below 0.7 prod, above noisy 0.4)
+const LEAK_IOU = 0.2
+
+async function testText(
+ models: Models,
+ tess: Worker,
+ files: string[],
+ label: string,
+ gate: boolean
+): Promise<{ pass: boolean }> {
+ let worst = 0
+ let fails = 0
+ for (const f of files) {
+ const buf = await readFile(f)
+ const { width: W, height: H } = await sharp(buf).metadata()
+ const orig = await readableWords(tess, buf, W!, H!)
+ const { out } = await advancedScrub(buf, models, 'dbnet')
+ const resid = await readableWords(tess, out, W!, H!)
+ const leak = (100 * resid) / Math.max(1, orig)
+ worst = Math.max(worst, leak)
+ const ok = leak <= TEXT_LEAK_MAX_PCT
+ if (!ok) {
+ fails++
+ }
+ console.log(
+ ` ${ok ? 'PASS' : 'leak'} text ${basename(f).padEnd(36)} orig=${String(orig).padStart(4)} scrubbed=${String(resid).padStart(3)} (${leak.toFixed(1)}%)`
+ )
+ }
+ const verdict = gate ? (fails === 0 ? 'PASS' : 'FAIL') : 'report'
+ console.log(
+ ` ${label}: ${files.length - fails}/${files.length} clean, worst leak ${worst.toFixed(1)}% [${verdict}]\n`
+ )
+ return { pass: !gate || fails === 0 }
+}
+
+async function testFaces(models: Models, files: string[]): Promise<{ pass: boolean }> {
+ let totalFaces = 0
+ let redacted = 0
+ let imgFails = 0
+ for (const f of files) {
+ const buf = await readFile(f)
+ const { width: W, height: H } = await sharp(buf).metadata()
+ const faces = await detectFacesYunet(models.yunet, await decodeSrc(buf), W!, H!)
+ if (faces.length === 0) {
+ continue
+ }
+ const { out } = await advancedScrub(buf, models, 'dbnet')
+ // Re-detect at high sensitivity on the scrubbed output; a face that's still detectable where
+ // one was is a leak. (A successfully solid-filled face is no longer detectable.)
+ const resid = await detectFacesYunet(models.yunet, await decodeSrc(out), W!, H!, { scoreMin: SENSITIVE_FACE })
+ const leaked = faces.filter((fb) => resid.some((rb) => iou(fb, rb) > LEAK_IOU))
+ const imgRedacted = faces.length - leaked.length
+ totalFaces += faces.length
+ redacted += imgRedacted
+ const ok = leaked.length === 0
+ if (!ok) {
+ imgFails++
+ }
+ console.log(
+ ` ${ok ? 'PASS' : 'LEAK'} face ${basename(f).padEnd(36)} faces=${String(faces.length).padStart(3)} still-detectable=${String(leaked.length).padStart(3)}`
+ )
+ }
+ const pct = totalFaces ? (100 * redacted) / totalFaces : 100
+ console.log(
+ ` FACE: ${redacted}/${totalFaces} faces redacted (${pct.toFixed(1)}%), ${imgFails} image(s) with a leak\n`
+ )
+ return { pass: imgFails === 0 }
+}
+
+async function main(): Promise<void> {
+ const models = await loadModels()
+ const tess = await createWorker('eng')
+
+ // GATE on session replay's representative domain: crisp rendered-UI text + faces.
+ // REPORT on the harder scanned-document set (faint fax/scan print is out of domain; the user's
+ // bar is best-effort, "not catastrophic if a little gets through").
+ // Committed challenge fixtures (e.g. a full retina Wikipedia page: dense text + a face + a
+ // heraldic crest + a flag) exercise text and face redaction together, so they go in both lists.
+ const fixtures = await listImages('fixtures')
+ const uiText = [...(await listImages('corpus')), ...fixtures]
+ const docText = await listImages('test-data/text')
+ const faceFiles = [...(await listImages('test-data/faces')), ...fixtures]
+ console.log(`UI text: ${uiText.length} document text: ${docText.length} faces: ${faceFiles.length}\n`)
+
+ const ui = uiText.length ? await testText(models, tess, uiText, 'UI TEXT (gated)', true) : { pass: true }
+ const docs = docText.length
+ ? await testText(models, tess, docText, 'DOCUMENT TEXT (report)', false)
+ : { pass: true }
+ const fc = faceFiles.length ? await testFaces(models, faceFiles) : { pass: true }
+
+ await tess.terminate()
+ void docs
+ const pass = ui.pass && fc.pass
+ console.log(pass ? '=== PASS (gated checks) ===' : '=== FAILURES ===')
+ if (!pass) {
+ process.exit(1)
+ }
+}
+
+main().catch((e) => {
+ console.error(e)
+ process.exit(1)
+})
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/dev/setup.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/dev/setup.ts
new file mode 100644
index 000000000000..e818889e7086
--- /dev/null
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/dev/setup.ts
@@ -0,0 +1,169 @@
+import { createHash } from 'node:crypto'
+import { existsSync } from 'node:fs'
+/**
+ * One-time setup: download the ONNX models and a bounded sample of real test images (faces + text),
+ * then generate the synthetic corpus. Nothing here is committed (see .gitignore) — rerun any time.
+ *
+ * npm run setup
+ *
+ * Test images come from the HuggingFace datasets-server REST API (no Python / `datasets` needed):
+ * /splits discovers a valid config+split, /rows returns rows whose image cells carry a `src` URL.
+ * The dataset list below is just defaults — swap in whatever faces/text sources you want.
+ */
+import { mkdir, writeFile } from 'node:fs/promises'
+import sharp from 'sharp'
+
+const ROOT = new URL('..', import.meta.url).pathname
+
+// The models decide what gets redacted, so they're pinned to immutable refs and digest-verified —
+// a mutable `main` URL would let an upstream change (or compromise) silently swap the privacy
+// control. Keep URLs + digests in sync with Dockerfile.ml-mirror-image-scrub (the image bakes the
+// same files at build time).
+const MODELS: { url: string; file: string; sha256: string }[] = [
+ {
+ url: 'https://huggingface.co/SWHL/RapidOCR/resolve/1cfba2e90fc938db55889873735088de210cc173/PP-OCRv4/en_PP-OCRv3_det_infer.onnx',
+ file: 'models/dbnet_det.onnx',
+ sha256: 'f139598bc2af4e4b6fe98dec11574e30edfdd91fc94ac1425c18ace3bd5a866b',
+ },
+ {
+ url: 'https://github.com/opencv/opencv_zoo/raw/47534e27c9851bb1128ccc0102f1145e27f23f98/models/face_detection_yunet/face_detection_yunet_2023mar.onnx',
+ file: 'models/yunet.onnx',
+ sha256: '8f2383e4dd3cfbb4553ea8718107fc0423210dc964f9f4280604804ed2552fa4',
+ },
+ {
+ url: 'https://huggingface.co/OwenElliott/image-safety-classifier-xs/resolve/54f4560bd9c5ee92d45dc30418a8f8680e80de6d/onnx/image-safety-classifier-xs.onnx',
+ file: 'models/safety.onnx',
+ sha256: '8c28c49d9075f3ad15ebdc2961f02d5b3f99be944815b848b49c9f0e6f3fb689',
+ },
+]
+
+// HuggingFace datasets to sample (verified reachable via datasets-server). Faces: real faces. Text:
+// dense text + PII-like fields. Swap in others (RICO/WebUI screenshots, COCO-Text/ICDAR scene text).
+// Verified: /rows returns an image whose asset URL actually fetches (some datasets' presigned
+// cached-asset URLs 403, e.g. flwrlabs/celeba — avoid those).
+const DATASETS: { dataset: string; dir: string; count: number }[] = [
+ { dataset: 'tonyassi/celebrity-1000', dir: 'test-data/faces', count: 50 }, // real celebrity faces
+ { dataset: 'logasja/lfw', dir: 'test-data/faces', count: 30 }, // Labeled Faces in the Wild
+ { dataset: 'nielsr/funsd', dir: 'test-data/text', count: 20 }, // forms — dense text + PII-like fields
+]
+
+const UA = 'Mozilla/5.0 posthog-replay-image-scrub' // HF + most CDNs reject requests without one
+
+async function get(url: string): Promise<Response> {
+ return fetch(url, { signal: AbortSignal.timeout(60000), headers: { 'user-agent': UA } })
+}
+
+const sleep = (ms: number): Promise<void> => new Promise((r) => setTimeout(r, ms))
+
+/** GET JSON with retries; the datasets-server intermittently returns HTML error pages on flaky links. */
+async function getJson(url: string, tries = 3): Promise<any> {
+ for (let i = 0; i < tries; i++) {
+ try {
+ const text = await (await get(url)).text()
+ return JSON.parse(text) // throws on an HTML error page -> retry
+ } catch (e) {
+ if (i === tries - 1) {
+ throw e
+ }
+ await sleep(1000 * (i + 1))
+ }
+ }
+}
+
+async function getBuf(url: string, tries = 3): Promise<Buffer> {
+ for (let i = 0; i < tries; i++) {
+ try {
+ const res = await get(url)
+ if (!res.ok) {
+ throw new Error(`status ${res.status}`)
+ }
+ return Buffer.from(await res.arrayBuffer())
+ } catch (e) {
+ if (i === tries - 1) {
+ throw e
+ }
+ await sleep(1000 * (i + 1))
+ }
+ }
+ throw new Error('unreachable')
+}
+
+async function downloadModels(): Promise<void> {
+ for (const m of MODELS) {
+ const dest = ROOT + m.file
+ if (existsSync(dest)) {
+ continue
+ }
+ const buf = await getBuf(m.url)
+ const digest = createHash('sha256').update(buf).digest('hex')
+ if (digest !== m.sha256) {
+ throw new Error(`${m.file}: sha256 mismatch (got ${digest}, want ${m.sha256}) — refusing to write`)
+ }
+ await mkdir(ROOT + 'models', { recursive: true })
+ await writeFile(dest, buf)
+ }
+}
+
+/** Find the first column in a datasets-server row whose value looks like an image ({ src }). */
+function imageUrlOf(row: Record<string, unknown>): string | null {
+ for (const v of Object.values(row)) {
+ if (v && typeof v === 'object' && typeof (v as { src?: unknown }).src === 'string') {
+ return (v as { src: string }).src
+ }
+ }
+ return null
+}
+
+async function downloadHf(dataset: string, dir: string, count: number): Promise<number> {
+ const splits = await getJson(`https://datasets-server.huggingface.co/splits?dataset=${encodeURIComponent(dataset)}`)
+ const list: { config: string; split: string }[] = splits?.splits ?? []
+ if (!list.length) {
+ throw new Error(`no splits for ${dataset}`)
+ }
+ const pick = list.find((s) => /val|test/.test(s.split)) ?? list[0]
+ const data = await getJson(
+ `https://datasets-server.huggingface.co/rows?dataset=${encodeURIComponent(dataset)}&config=${encodeURIComponent(pick.config)}&split=${encodeURIComponent(pick.split)}&offset=0&length=${count}`
+ )
+ const rows = data?.rows ?? []
+ await mkdir(ROOT + dir, { recursive: true })
+ let n = 0
+ for (const r of rows) {
+ const url = imageUrlOf(r.row ?? {})
+ if (!url) {
+ continue
+ }
+ try {
+ await sharp(await getBuf(url))
+ .png()
+ .toFile(`${ROOT}${dir}/${dataset.replace(/\W+/g, '_')}_${n}.png`)
+ n++
+ } catch {
+ // skip a bad row
+ }
+ }
+ return n
+}
+
+async function main(): Promise<void> {
+ await downloadModels()
+
+ let total = 0
+ for (const d of DATASETS) {
+ try {
+ const n = await downloadHf(d.dataset, d.dir, d.count)
+ total += n
+ } catch (e) {
+ console.warn(` ${d.dataset}: failed (${String(e)})`)
+ }
+ }
+ if (total === 0) {
+ console.warn('no HF images fetched (network?); the suite will still run on the synthetic corpus')
+ }
+
+ await import('./make-corpus.ts')
+}
+
+main().catch((e) => {
+ console.error(e)
+ process.exit(1)
+})
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/dev/verify.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/dev/verify.ts
new file mode 100644
index 000000000000..b6bb36da4d57
--- /dev/null
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/dev/verify.ts
@@ -0,0 +1,94 @@
+/* eslint-disable no-console -- CLI output script: console output is the whole point */
+/**
+ * Self-verifying test: a scrubbed image should contain no READABLE text. We scrub with PRODUCTION
+ * settings, then run OCR (tesseract — an independent model doing recognition, not the DBNet detector
+ * used in production) on both the original and the scrubbed output, and count confident multi-char
+ * words. CPU doesn't matter here, so OCR is upscaled for maximum sensitivity.
+ *
+ * Why OCR and not "re-run the detector": the verifier must be independent of production, and it must
+ * measure the thing that actually matters — can a human read the text. OCR generally reads degraded
+ * text better than people, so "OCR can't read it" is a conservative proxy for "a labeler can't".
+ *
+ * Saves out/verify_<name>.png with any residual readable-word boxes drawn in red.
+ *
+ * Usage: tsx src/verify.ts [img ...]
+ */
+import { readFile } from 'node:fs/promises'
+import { basename } from 'node:path'
+import sharp from 'sharp'
+import { type Worker, createWorker } from 'tesseract.js'
+
+import { advancedScrub, loadModels } from '../src/scrub.ts'
+
+const OCR_CONF = 60 // min tesseract word confidence to count as "readable"
+const OCR_UPSCALE = 2 // upscale before OCR for max sensitivity (CPU irrelevant for a test)
+
+interface Word {
+ text: string
+ confidence: number
+ bbox: { x0: number; y0: number; x1: number; y1: number }
+}
+
+/** Confident, multi-character alphanumeric words OCR can read from an image (upscaled for recall). */
+async function readableWords(tess: Worker, img: Buffer, W: number, H: number): Promise<Word[]> {
+ const big = await sharp(img)
+ .resize(Math.round(W * OCR_UPSCALE), Math.round(H * OCR_UPSCALE), { fit: 'fill' })
+ .png()
+ .toBuffer()
+ const { data } = await tess.recognize(big, {}, { blocks: true })
+ const words = ((data as { words?: Word[] }).words ??
+ (data.blocks ?? []).flatMap((b: any) =>
+ (b.paragraphs ?? []).flatMap((p: any) => (p.lines ?? []).flatMap((l: any) => l.words ?? []))
+ )) as Word[]
+ return words.filter((w) => w.confidence >= OCR_CONF && /[A-Za-z0-9]{2,}/.test(w.text ?? ''))
+}
+
+async function main(): Promise<void> {
+ const models = await loadModels()
+ const tess = await createWorker('eng')
+ const imgs = process.argv.slice(2)
+ const files = imgs.length
+ ? imgs
+ : ['out/original_wikipedia.png', 'corpus/shot_desktop_1280x720_0.png', 'corpus/shot_mobile_375x812_0.png']
+
+ let worst = 0
+ for (const f of files) {
+ const buf = await readFile(f)
+ const meta = await sharp(buf).metadata()
+ const W = meta.width!
+ const H = meta.height!
+ const origWords = await readableWords(tess, buf, W, H)
+ const { out } = await advancedScrub(buf, models, 'dbnet')
+ const residWords = await readableWords(tess, out, W, H)
+ const leak = (100 * residWords.length) / Math.max(1, origWords.length)
+ worst = Math.max(worst, leak)
+ const flag = residWords.length === 0 ? 'PASS' : leak < 2 ? 'ok' : 'LEAK'
+ console.log(
+ ` ${flag.padEnd(4)} ${basename(f).padEnd(34)} readable(orig)=${String(origWords.length).padStart(4)} readable(scrubbed)=${String(residWords.length).padStart(3)} (${leak.toFixed(1)}%)`
+ )
+ if (residWords.length) {
+ console.log(
+ ` leaked: ${residWords
+ .slice(0, 8)
+ .map((w) => JSON.stringify(w.text))
+ .join(', ')}`
+ )
+ }
+ const rects = residWords
+ .map(
+ (w) =>
+ `<rect x="${w.bbox.x0 / OCR_UPSCALE}" y="${w.bbox.y0 / OCR_UPSCALE}" width="${(w.bbox.x1 - w.bbox.x0) / OCR_UPSCALE}" height="${(w.bbox.y1 - w.bbox.y0) / OCR_UPSCALE}" fill="none" stroke="red" stroke-width="4"/>`
+ )
+ .join('')
+ await sharp(out)
+ .composite([{ input: Buffer.from(`<svg width="${W}" height="${H}">${rects}</svg>`), left: 0, top: 0 }])
+ .toFile('out/verify_' + basename(f))
+ }
+ await tess.terminate()
+ console.log(`\n worst readable-text leak: ${worst.toFixed(1)}% ${worst < 2 ? '-> PASS' : '-> needs tuning'}`)
+}
+
+main().catch((e) => {
+ console.error(e)
+ process.exit(1)
+})
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/dev/worker-proc.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/dev/worker-proc.ts
new file mode 100644
index 000000000000..c50d99537240
--- /dev/null
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/dev/worker-proc.ts
@@ -0,0 +1,45 @@
+/* eslint-disable no-console -- CLI output script: console output is the whole point */
+/**
+ * One worker process. Loads what MODE needs, processes WORK_N images, and writes the processing
+ * window (excludes model load + warmup) as @@R@@{json} on stdout. Both modes pin sharp to one
+ * libvips thread so a process ≈ one core, making the per-process numbers comparable and the
+ * sum-over-processes a fair machine-throughput figure.
+ *
+ * MODE=blur -> baseline blurOnly (no models, no network)
+ * MODE=advanced -> nsfw + face + dbnet scrub
+ */
+import { readFile, readdir } from 'node:fs/promises'
+import sharp from 'sharp'
+
+import { advancedScrub, blurOnly, loadModels } from '../src/scrub.ts'
+
+sharp.concurrency(1)
+
+const N = Number(process.env.WORK_N ?? 40)
+const MODE = process.env.MODE ?? 'advanced'
+
+async function main(): Promise<void> {
+ const files = (await readdir('corpus')).filter((f) => f.endsWith('.png'))
+ const bufs = await Promise.all(files.map((f) => readFile('corpus/' + f)))
+
+ let run: (b: Buffer) => Promise<unknown>
+ if (MODE === 'blur') {
+ run = (b) => blurOnly(b)
+ } else {
+ const models = await loadModels()
+ run = (b) => advancedScrub(b, models, 'dbnet')
+ }
+
+ await run(bufs[0]) // warmup
+ const t0 = performance.now()
+ for (let i = 0; i < N; i++) {
+ await run(bufs[i % bufs.length])
+ }
+ const ms = performance.now() - t0
+ process.stdout.write('@@R@@' + JSON.stringify({ imgs: N, ms }))
+}
+
+main().catch((e) => {
+ console.error(String(e))
+ process.exit(1)
+})
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/fixtures/wikipedia_pm_uk.png b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/fixtures/wikipedia_pm_uk.png
new file mode 100644
index 000000000000..b61e6ba0dbcd
Binary files /dev/null and b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/fixtures/wikipedia_pm_uk.png differ
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/jest.config.cjs b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/jest.config.cjs
index 24cd6ea1e880..4e033f283831 100644
--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/jest.config.cjs
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/jest.config.cjs
@@ -3,7 +3,10 @@ module.exports = {
testMatch: ['<rootDir>/src/**/*.test.ts'],
// The sources import each other with explicit `.ts` extensions (tsx style); strip the extension so
// jest resolves the .ts file (moduleFileExtensions includes 'ts' by default).
+ // jest-resolve can't resolve zxing-wasm's `.wasm` export subpaths (node proper can); map them.
moduleNameMapper: {
'^(\\.{1,2}/.*)\\.ts$': '$1',
+ '^zxing-wasm/reader/zxing_reader\\.wasm$': '<rootDir>/node_modules/zxing-wasm/dist/reader/zxing_reader.wasm',
+ '^zxing-wasm/writer/zxing_writer\\.wasm$': '<rootDir>/node_modules/zxing-wasm/dist/writer/zxing_writer.wasm',
},
}
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/package.json b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/package.json
index 529afcd9075d..b7221756753d 100644
--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/package.json
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/package.json
@@ -2,7 +2,7 @@
"name": "@posthog/ml-mirror-image-scrub-sidecar",
"version": "0.0.0",
"private": true,
- "description": "replay_vision image-scrub sidecar: an HTTP service that turns raw session-replay image bytes into scrubbed bytes (Stage 1 = sharp-only blur; Stage 2 swaps in the native ML scrub). The plugin-server consumer owns Kafka + S3 and calls this over loopback. Standalone package (not in pnpm-workspace.yaml) so its heavy Stage-2 ML deps never reach the root lockfile or the plugin-server image.",
+ "description": "replay_vision image-scrub sidecar: an HTTP service that turns raw session-replay image bytes into scrubbed bytes using the native ML scrub (NSFW gate + solid-fill of detected faces, text, and QR/barcodes). The plugin-server consumer owns Kafka + S3 and calls this over loopback. Standalone package (not in pnpm-workspace.yaml) so its ML deps (onnxruntime + models) never reach the root lockfile or the plugin-server image.",
"type": "module",
"scripts": {
"start": "tsx src/main.ts",
@@ -10,13 +10,22 @@
"typecheck": "tsc --noEmit",
"lint": "oxlint -c .oxlintrc.json",
"format": "oxfmt -c .oxfmtrc.json",
- "format:check": "oxfmt -c .oxfmtrc.json --check"
+ "format:check": "oxfmt -c .oxfmtrc.json --check",
+ "setup": "tsx dev/setup.ts",
+ "corpus": "tsx dev/make-corpus.ts",
+ "bench": "tsx dev/bench.ts",
+ "scale": "tsx dev/scale.ts",
+ "verify": "tsx dev/verify.ts",
+ "eval": "tsx dev/scrub-eval.ts",
+ "smoke": "tsx src/smoke.ts"
},
"dependencies": {
"express": "^4.21.1",
+ "onnxruntime-node": "^1.27.0",
"prom-client": "^15.1.3",
"sharp": "^0.34.5",
- "tsx": "^4.19.2"
+ "tsx": "^4.19.2",
+ "zxing-wasm": "^2.2.0"
},
"devDependencies": {
"@babel/core": "^7.26.0",
@@ -29,12 +38,14 @@
"jest": "^29.7.0",
"oxfmt": "^0.35.0",
"oxlint": "^1.72.0",
+ "tesseract.js": "^6.0.1",
"typescript": "^5.7.2"
},
"packageManager": "[email protected]",
"pnpm": {
"onlyBuiltDependencies": [
"esbuild",
+ "onnxruntime-node",
"sharp"
]
}
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/pnpm-lock.yaml b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/pnpm-lock.yaml
index dd14833fb68a..b1b72ae04e44 100644
--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/pnpm-lock.yaml
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/pnpm-lock.yaml
@@ -11,6 +11,9 @@ importers:
express:
specifier: ^4.21.1
version: 4.22.2
+ onnxruntime-node:
+ specifier: ^1.27.0
+ version: 1.27.0
prom-client:
specifier: ^15.1.3
version: 15.1.3
@@ -20,6 +23,9 @@ importers:
tsx:
specifier: ^4.19.2
version: 4.22.4
+ zxing-wasm:
+ specifier: ^2.2.0
+ version: 2.2.4(@types/[email protected])
devDependencies:
'@babel/core':
specifier: ^7.26.0
@@ -51,6 +57,9 @@ importers:
oxlint:
specifier: ^1.72.0
version: 1.72.0
+ tesseract.js:
+ specifier: ^6.0.1
+ version: 6.0.1
typescript:
specifier: ^5.7.2
version: 5.9.3
@@ -1331,6 +1340,9 @@ packages:
resolution: {integrity: sha512-K6uROf1LD88uDQqJCktA4yzL1YYAK6NgfsI0v/mTgyPKWsX1CnJ0XPSDhViejru1GcRkLWb8RlzFYJRqGUbaug==}
+ '@types/[email protected]':
+ resolution: {integrity: sha512-QSb9ojDincskc+uKMI0KXp8e1NALFINCrMlp8VGKGcTSxeEyRTTKyjWw75NYrCZHUsVEEEpr1tYHpbtaC++/sQ==}
+
resolution: {integrity: sha512-02S5fmqeoKzVZCHPZid4b8JH2eM5HzQLZWN2FohQEy/0eXTq8VXZfSN6Pcr3F6N9R/vNrj7cpgbhjie6m/1tCA==}
@@ -1389,6 +1401,10 @@ packages:
resolution: {integrity: sha512-PYAthTa2m2VKxuvSD3DPC/Gy+U+sOA1LAuT8mkmRuvw+NACSaeXEQ+NHcVF7rONl6qcaxV3Uuemwawk+7+SJLw==}
engines: {node: '>= 0.6'}
+ resolution: {integrity: sha512-ufJnssQGbxzLNS1Ho9bCtX4rQKCCvoVuDLHoJyc3F9dOGDB4BkWs2Ci0kv53lqocAEQ/Cbi+I2XCsNYGqVYqng==}
+ engines: {node: '>=12.0'}
+
resolution: {integrity: sha512-gKXj5ALrKWQLsYG9jlTRmR/xKluxHV+Z9QEwNIgCfM1/uwPMCuzVVnh5mwTd+OuBZcwSIMbqssNWRm1lE51QaQ==}
engines: {node: '>=8'}
@@ -1466,6 +1482,9 @@ packages:
resolution: {integrity: sha512-VOMgTMwjAaUG580SXn3LacVgjurrbMme7ZZNYGSSV7mmtY6QQRh0Eg3pwIcntQ77DErK1L0NxkbetjcoXzVwKw==}
+ resolution: {integrity: sha512-vHdS19CnY3hwiNdkaqk93DvjVLfbEcI8mys4UjuWrlX1haDmroo8o4xCzh4wD6DGV6HxRCyauwhHRqMTfERtjw==}
+
resolution: {integrity: sha512-3grm+/2tUOvu2cjJkvsIxrv/wVpfXQW4PsQHYm7yk4vfpu7Ekl6nEsYBoJUL6qDwZUx8wUhQ8tR2qz+ad9c9OA==}
engines: {node: '>= 0.8', npm: 1.2.8000 || >= 1.4.16}
@@ -1610,6 +1629,14 @@ packages:
resolution: {integrity: sha512-3sUqbMEc77XqpdNO7FRyRog+eW3ph+GYCbj+rK+uYyRMuwsVy0rMiVtPn+QJlKFvWP/1PYpapqYn0Me2knFn+A==}
engines: {node: '>=0.10.0'}
+ resolution: {integrity: sha512-rBMvIzlpA8v6E+SJZoo++HAYqsLrkg7MSfIinMPFhmkorw7X+dOXVJQs+QT69zGkzMyfDnIMN2Wid1+NbL3T+A==}
+ engines: {node: '>= 0.4'}
+
+ resolution: {integrity: sha512-8QmQKqEASLd5nx0U1B1okLElbUuuttJ/AnYmRXbbbGDWh6uS208EjD4Xqq/I9wK7u0v6O08XhTWnt5XtEbR6Dg==}
+ engines: {node: '>= 0.4'}
+
resolution: {integrity: sha512-g7nH6P6dyDioJogAAGprGpCtVImJhpPk/roCzdb3fIh61/s/nPsfR6onyMwkCAR/OlC3yBC0lESvUoQEAssIrw==}
engines: {node: '>= 0.8'}
@@ -1682,6 +1709,10 @@ packages:
resolution: {integrity: sha512-UpzcLCXolUWcNu5HtVMHYdXJjArjsF9C0aNnquZYY4uW/Vu0miy5YoWvbV345HauVvcAUnpRuhMMcqTcGOY2+w==}
engines: {node: '>=8'}
+ resolution: {integrity: sha512-TtpcNJ3XAzx3Gq8sWRzJaVajRs0uVxA2YAkdb1jm2YkPz4G6egUFAyA3n5vtEIZefPk5Wa4UXbKuS5fKkJWdgA==}
+ engines: {node: '>=10'}
+
resolution: {integrity: sha512-eGuFFw7Upda+g4p+QHvnW0RyTX/SVeJBDM/gCtMARO0cLuT2HcEKnTPvhjV6aGeqrCB/sbNop0Kszm0jsaWU4A==}
engines: {node: '>=4'}
@@ -1776,6 +1807,14 @@ packages:
resolution: {integrity: sha512-nFR0zLpU2YCaRxwoCJvL6UvCH2JFyFVIvwTLsIf21AuHlMskA1hhTdk+LlYJtOlYt9v6dvszD2BGRqBL+iQK9Q==}
deprecated: Old versions of glob are not supported, and contain widely publicized security vulnerabilities, which have been fixed in the current version. Please update. Support for old versions may be purchased (at exorbitant rates) by contacting [email protected]
+ resolution: {integrity: sha512-KUJEViiuFT3I97t+GYMikLPJS2Lfo/S2F+DQuBWzuzaMPnvt5yyZePzArx36fBzpGTxZjIpDbXLeySLgh+k76g==}
+ engines: {node: '>=10.0'}
+
+ resolution: {integrity: sha512-DpLKbNU4WylpxJykQujfCcwYWiV/Jhm50Goo0wrVILAv5jOr9d+H+UR3PhSCD2rCCEIg0uc+G+muBTwD54JhDQ==}
+ engines: {node: '>= 0.4'}
+
resolution: {integrity: sha512-ZUKRh6/kUFoAiTAtTYPZJ3hw9wNxx+BIBOijnlG9PnrJsCcSjs1wyyD6vJpaYtgnzDrKYRSqf3OO6Rfa93xsRg==}
engines: {node: '>= 0.4'}
@@ -1787,6 +1826,9 @@ packages:
resolution: {integrity: sha512-EykJT/Q1KjTWctppgIAgfSO0tKVuZUjhgMr17kqTumMl6Afv3EISleU7qZUzoXDFTAHTDC4NOoG/ZxU3EvlMPQ==}
engines: {node: '>=8'}
+ resolution: {integrity: sha512-55JNKuIW+vq4Ke1BjOTjM2YctQIvCT7GFzHwmfZPGo5wnrgkid0YQtnAleFSqumZm4az3n2BS+erby5ipJdgrg==}
+
resolution: {integrity: sha512-1cDNdwJ2Jaohmb3sg4OmKaMBwuC48sYni5HUw2DvsC8LjGTLK9h+eb1X6RyuOHe4hT0ULCW68iomhjUoKUqlPQ==}
engines: {node: '>= 0.4'}
@@ -1810,6 +1852,9 @@ packages:
resolution: {integrity: sha512-v3MXnZAcvnywkTUEZomIActle7RXXeedOR31wwl7VlyoXO4Qi9arvSenNQWne1TcRwhCL1HwLI21bEqdpj8/rA==}
engines: {node: '>=0.10.0'}
+ resolution: {integrity: sha512-um+2dgAWmYsu615EXpWVwSmapJhON0G43t3Ka/EVaohzPQXSMqKEqeDK/oIW3Ow+BXaF2PvSc+oBTFp793A5Ow==}
+
resolution: {integrity: sha512-2SPlun1JUPWoM6t3F0dw0FkCF/jWY8kttcY4f599GLTSjh2OCuuhdTkJQsEcZzBqbXZGKMK2OqW1oZsjtf/gQA==}
engines: {node: '>=8'}
@@ -1853,6 +1898,9 @@ packages:
resolution: {integrity: sha512-hFoiJiTl63nn+kstHGBtewWSKnQLpyb155KHheA1l39uvtO9nWIop1p3udqPcUd/xbF1VLMO4n7OI6p7RbngDg==}
engines: {node: '>=8'}
+ resolution: {integrity: sha512-ITvGim8FhRiYe4IQ5uHSkj7pVaPDrCTkNd3yq3cV7iZAcJdHTUMPMEHcqSOy9xZ9qFenQCvi+2wjH9a1nXqHww==}
+
resolution: {integrity: sha512-RHxMLp9lnKHGHRng9QFhRCMbYAcVpn69smSGcq3f36xjgVVWThj4qqLbTLlq7Ssj8B+fIQ1EuCEGI2lKsyQeIw==}
@@ -2057,6 +2105,10 @@ packages:
resolution: {integrity: sha512-JmqCvUhmt43madlpFzG4BQzG2Z3m6tvQDNKdClZnO3VbIudJYmxsT0FNJMeiB2+JTSlTQTSbU8QdesVmwJcmLg==}
+ resolution: {integrity: sha512-S6x5wmcDmsDRRU/c2dkccDwQPXoFczc5+HpQ2lON8pnvHlnvHAHj5WlLVvw6n6vNyHuVugYrFohYxbS+pvFpKQ==}
+ engines: {node: '>=10'}
+
resolution: {integrity: sha512-/IXtbwEk5HTPyEwyKX6hGkYXxM9nbj64B+ilVJnC/R6B0pH5G4V3b0pVbL7DBj4tkhBAppbQUlf6F6Xl9LHu1g==}
engines: {node: '>= 0.4'}
@@ -2112,6 +2164,15 @@ packages:
resolution: {integrity: sha512-+EUsqGPLsM+j/zdChZjsnX51g4XrHFOIXwfnCVPGlQk/k5giakcKsuxCObBRu6DSm9opw/O6slWbJdghQM4bBg==}
engines: {node: '>= 0.6'}
+ resolution: {integrity: sha512-c4FRfUm/dbcWZ7U+1Wq0AwCyFL+3nt2bEw05wfxSz+DWpWsitgmSgYmy2dQdWyKC1694ELPqMs/YzUSNozLt8A==}
+ engines: {node: 4.x || >=6.0.0}
+ peerDependencies:
+ encoding: ^0.1.0
+ peerDependenciesMeta:
+ encoding:
+ optional: true
+
resolution: {integrity: sha512-O5lz91xSOeoXP6DulyHfllpq+Eg00MWitZIbtPfoSEvqIHdl5gfcY6hYzDWnj0qD5tz52PI08u9qUvSVeUBeHw==}
@@ -2131,6 +2192,10 @@ packages:
resolution: {integrity: sha512-W67iLl4J2EXEGTbfeHCffrjDfitvLANg0UlX3wFUUSTx92KXRFegMHUVgSqE+wvhAbi4WqjGg9czysTV2Epbew==}
engines: {node: '>= 0.4'}
+ resolution: {integrity: sha512-NuAESUOUMrlIXOfHKzD6bpPu3tYt3xvjNdRIQ+FeT0lNb4K8WR70CaDxhuNguS2XG+GjkyMwOzsN5ZktImfhLA==}
+ engines: {node: '>= 0.4'}
+
resolution: {integrity: sha512-oVlzkg3ENAhCk2zdv7IJwd/QUD4z2RxRwpkcGY8psCVcCYZNq4wYnVWALHM+brtuJjePWiYF/ClmuDr8Ch5+kg==}
engines: {node: '>= 0.8'}
@@ -2142,6 +2207,17 @@ packages:
resolution: {integrity: sha512-kbpaSSGJTWdAY5KPVeMOKXSrPtr8C8C7wodJbcsd51jRnmD+GZu8Y0VoU6Dm5Z4vWr0Ig/1NKuWRKf7j5aaYSg==}
engines: {node: '>=6'}
+ resolution: {integrity: sha512-3KxL5wIVqa8Ex08jxSzncm9CMgw8CjOFyOQ7SxvG9o0cVLlhTNKXyIQuTbtX4tGPJEf73OER2xrjt4HJSBL4ow==}
+
+ resolution: {integrity: sha512-QEzGwrvNBgv4uPVdnbHsOGG4G6T96mdlcFI8aAKPjMU8wOPpVocPXb6k3QGkaZagVTv2G9Bnnbo6Z3JdXr1fQw==}
+ os: [win32, darwin, linux]
+
+ resolution: {integrity: sha512-8AV/sCtuzUeTo8gQK5qDZzARrulB3egtLzFgteqB2tcT4Mw7B8Kt7JcDHmltjz6FOAHsvTevk70gZEbhM4ZS9Q==}
+ hasBin: true
+
resolution: {integrity: sha512-QYeXWkP+aLt7utt5SLivNIk09glWx9QE235ODjgcEZ3sd1VMaUBSpLymh6ZRCA76gD2rMP4bXanUz/fx+nLM9Q==}
engines: {node: ^20.19.0 || >=22.12.0}
@@ -2258,6 +2334,9 @@ packages:
resolution: {integrity: sha512-zrceR/XhGYU/d/opr2EKO7aRHUeiBI8qjtfHqADTwZd6Szfy16la6kqD0MIUs5z5hx6AaKa+PixpPrR289+I0A==}
+ resolution: {integrity: sha512-kY1AZVr2Ra+t+piVaJ4gxaFaReZVH40AKNo7UCX6W+dEwBo/2oZJzqfuN1qLq1oL45o56cPaTXELwrTh8Fpggg==}
+
resolution: {integrity: sha512-0ghuzq67LI9bLXpOX/ISfve/Mq33a4aFRzoQYhnnok1JOFpmE/A2TBGkNVenOGEeSBCjIiWcc6MVOG5HEQv0sA==}
engines: {node: '>=4'}
@@ -2309,6 +2388,10 @@ packages:
resolution: {integrity: sha512-VMbMxbDeehAxpOtWJXlcUS5E8iXh6QmN+BkRX1GARS3wRaXEEgzCcB10gTQazO42tpNIya8xIyNx8fll1OFPrg==}
engines: {node: '>= 0.8.0'}
+ resolution: {integrity: sha512-3NnuWfM6vBYoy5gZFvHiYsVbafvI9vZv/+jlIigFn4oP4zjNPK3LhcY0xSCgeb1a5L8jO71Mit9LlNoi2UfDDQ==}
+ engines: {node: '>=10'}
+
resolution: {integrity: sha512-x0RTqQel6g5SY7Lg6ZreMmsOzncHFU7nhnRWkKgWuMTu5NN0DR5oruckMqRvacAN9d5w6ARnRBXl9xhDCgfMeA==}
engines: {node: '>= 0.8.0'}
@@ -2408,9 +2491,19 @@ packages:
resolution: {integrity: sha512-ot0WnXS9fgdkgIcePe6RHNk1WA8+muPa6cSjeR3V8K27q9BB1rTE3R1p7Hv0z1ZyAc8s6Vvv8DIyWf681MAt0w==}
engines: {node: '>= 0.4'}
+ resolution: {integrity: sha512-yEFYrVhod+hdNyx7g5Bnkkb0G6si8HJurOoOEgC8B/O0uXLHlaey/65KRv6cuWBNhBgHKAROVpc7QyYqE5gFng==}
+ engines: {node: '>=20'}
+
resolution: {integrity: sha512-+G0LLgjjo9BZX2MfdvPfH+MKLCrxlXSYec5DaPYP1fe6Iyhf0/fSmJ0bFiZ1F8BT6cGXl2LpltQptzjXKWEkKA==}
+ resolution: {integrity: sha512-pv4GjmramjdObhDyR1q85Td8X60Puu/lGQn7Kw2id05LLgHhAcWgnz6xSdMCSxBMWjQDmMyDXPTC2aqADdpiow==}
+
+ resolution: {integrity: sha512-/sPvMvrCtgxnNRCjbTYbr7BRu0yfWDsMZQ2a/T5aN/L1t8wUQN6tTWv6p6FwzpoEBA0jrN2UD2SX4QQFRdoDbA==}
+
resolution: {integrity: sha512-cAGWPIyOHU6zlmg88jwm7VRyXnMN7iV68OGAbYDk/Mh/xC/pzVPlQtY6ngoIH/5/tciuhGfvESU8GrHrcxD56w==}
engines: {node: '>=8'}
@@ -2430,6 +2523,9 @@ packages:
resolution: {integrity: sha512-o5sSPKEkg/DIQNmH43V0/uerLrpzVedkUh8tGNvaeXpfpuwjKenlSox/2O/BTlZUtEe+JG7s5YhEz608PlAHRA==}
engines: {node: '>=0.6'}
+ resolution: {integrity: sha512-N3WMsuqV66lT30CrXNbEjx4GEwlow3v6rr4mCcv6prnfwhS01rkgyFdjPNBYd9br7LpXV1+Emh01fHnq2Gdgrw==}
+
resolution: {integrity: sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w==}
@@ -2442,10 +2538,18 @@ packages:
resolution: {integrity: sha512-0fr/mIH1dlO+x7TlcMy+bIDqKPsw/70tVyeHW787goQjhmqaZe10uwLujubK9q9Lg6Fiho1KUKDYz0Z7k7g5/g==}
engines: {node: '>=4'}
+ resolution: {integrity: sha512-Ne+eE4r0/iWnpAxD852z3A+N0Bt5RN//NjJwRd2VFHEmrywxf5vsZlh4R6lixl6B+wz/8d+maTSAkN1FIkI3LQ==}
+ engines: {node: '>=10'}
+
resolution: {integrity: sha512-t0rzBq87m3fVcduHDUFhKmyyX+9eo6WQjZvf51Ea/M0Q7+T374Jp1aUiyUl0GKxp8M/OETVHSDvmkyPgvX+X2w==}
engines: {node: '>=10'}
+ resolution: {integrity: sha512-YGYEVz3Fm5iy/AybuA0oyNFq7H4CgQNfRp/qfe8nurE1kuCeNm3/vfm9X4Mtl+qLyaKJUh5xrFZwogr41SMjYA==}
+ engines: {node: '>=20'}
+
resolution: {integrity: sha512-TkRKr9sUTxEH8MdfuCSP7VizJyzRNMjj2J2do2Jr3Kym598JVdEksuzPQCnlFPW4ky9Q+iA+ma9BGm06XQBy8g==}
engines: {node: '>= 0.6'}
@@ -2499,6 +2603,15 @@ packages:
resolution: {integrity: sha512-ts/8E8l5b7kY0vlWLewOkDXMmPdLcVV4GmOQLyxuSswIJsweeFZtAsMF7k1Nszz+TYBQrlYRmzOnr398y1JemQ==}
+ resolution: {integrity: sha512-zksaLKM2fVlnB5jQQDqKXXwYHLQUVH9es+5TOOHwGOVJOCeRBCiPjwSg+3tN2AdTCzjgli4jijCH290kXb/zWQ==}
+
+ resolution: {integrity: sha512-2JAn3z8AR6rjK8Sm8orRC0h/bcl/DqL7tRPdGZ4I1CjdF+EaMLmYxBHyXuKL849eucPFhvBoxMsflfOb8kxaeQ==}
+
+ resolution: {integrity: sha512-saE57nupxk6v3HY35+jzBwYa0rKSy0XR8JSxZPwgLr7ys0IBzhGviA1/TUGJLmSVqs8pb9AnvICXEuOHLprYTw==}
+
resolution: {integrity: sha512-BLI3Tl1TW3Pvl70l3yq3Y64i+awpwXqsGBYWkkqMtnbXgrMD+yj7rhW0kuEDxzJaYXGjEW5ogapKNMEKNMjibA==}
engines: {node: '>= 8'}
@@ -2534,6 +2647,14 @@ packages:
resolution: {integrity: sha512-rVksvsnNCdJ/ohGc6xgPwyN8eheCxsiLM8mxuE/t/mOVqJewPuO1miLpTHQiRgTKCLexL4MeAFVagts7HmNZ2Q==}
engines: {node: '>=10'}
+ resolution: {integrity: sha512-+J9RrgTKOmlxFSDHo0pI1xM6BLVUv+o0ZT9ANtCxGkjIVCCUdx9alUF8Gm+dGLKbkkkidWIHFDZHDMpfITt4+w==}
+
+ resolution: {integrity: sha512-1gq5zs4wuNTs5umWLypzNNeuJoluFvwmvjiiT3L9z/TMlVveeJRWy7h90xyUqCe+Qq0zL0w7o5zkdDMWDr9aZA==}
+ peerDependencies:
+ '@types/emscripten': '>=1.39.6'
+
snapshots:
@@ -3827,6 +3948,8 @@ snapshots:
dependencies:
'@types/node': 24.13.2
+ '@types/[email protected]': {}
+
dependencies:
'@types/node': 24.13.2
@@ -3900,6 +4023,8 @@ snapshots:
mime-types: 2.1.35
negotiator: 0.6.3
+
dependencies:
type-fest: 0.21.3
@@ -4008,6 +4133,8 @@ snapshots:
+
dependencies:
bytes: 3.1.2
@@ -4146,6 +4273,18 @@ snapshots:
+ dependencies:
+ es-define-property: 1.0.1
+ es-errors: 1.3.0
+ gopd: 1.2.0
+
+ dependencies:
+ define-data-property: 1.1.4
+ has-property-descriptors: 1.0.2
+ object-keys: 1.1.1
+
@@ -4219,6 +4358,8 @@ snapshots:
+
@@ -4356,12 +4497,28 @@ snapshots:
once: 1.4.0
path-is-absolute: 1.0.1
+ dependencies:
+ globalthis: 1.0.4
+ matcher: 4.0.0
+ semver: 7.8.5
+ serialize-error: 8.1.0
+
+ dependencies:
+ define-properties: 1.2.1
+ gopd: 1.2.0
+
+ dependencies:
+ es-define-property: 1.0.1
+
@@ -4384,6 +4541,8 @@ snapshots:
dependencies:
safer-buffer: 2.1.2
+
dependencies:
pkg-dir: 4.2.0
@@ -4414,6 +4573,8 @@ snapshots:
+
@@ -4802,6 +4963,10 @@ snapshots:
dependencies:
tmpl: 1.0.5
+ dependencies:
+ escape-string-regexp: 4.0.0
+
@@ -4839,6 +5004,10 @@ snapshots:
+ dependencies:
+ whatwg-url: 5.0.0
+
@@ -4851,6 +5020,8 @@ snapshots:
+
dependencies:
ee-first: 1.1.1
@@ -4863,6 +5034,16 @@ snapshots:
dependencies:
mimic-fn: 2.1.0
+
+ dependencies:
+ adm-zip: 0.5.18
+ global-agent: 4.1.3
+ onnxruntime-common: 1.27.0
+
+
dependencies:
tinypool: 2.1.0
@@ -4997,6 +5178,8 @@ snapshots:
+
dependencies:
regenerate: 1.4.2
@@ -5055,6 +5238,10 @@ snapshots:
transitivePeerDependencies:
- supports-color
+ dependencies:
+ type-fest: 0.20.2
+
dependencies:
encodeurl: 2.0.0
@@ -5183,10 +5370,28 @@ snapshots:
+
dependencies:
bintrees: 1.0.2
+
+ dependencies:
+ bmp-js: 0.1.0
+ idb-keyval: 6.3.0
+ is-url: 1.2.4
+ node-fetch: 2.7.0
+ opencollective-postinstall: 2.0.3
+ regenerator-runtime: 0.13.11
+ tesseract.js-core: 6.1.2
+ wasm-feature-detect: 1.8.0
+ zlibjs: 0.3.1
+ transitivePeerDependencies:
+ - encoding
+
dependencies:
'@istanbuljs/schema': 0.1.6
@@ -5203,6 +5408,8 @@ snapshots:
+
optional: true
@@ -5214,8 +5421,14 @@ snapshots:
+
+ dependencies:
+ tagged-tag: 1.0.0
+
dependencies:
media-typer: 0.3.0
@@ -5258,6 +5471,15 @@ snapshots:
dependencies:
makeerror: 1.0.12
+
+
+ dependencies:
+ tr46: 0.0.3
+ webidl-conversions: 3.0.1
+
dependencies:
isexe: 2.0.0
@@ -5292,3 +5514,10 @@ snapshots:
yargs-parser: 21.1.1
+
+
+ dependencies:
+ '@types/emscripten': 0.0.34
+ type-fest: 5.8.0
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/src/blur.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/src/blur.ts
index a1d3a95268fc..4ea6de00d0d1 100644
--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/src/blur.ts
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/src/blur.ts
@@ -10,7 +10,14 @@ const DOWNSAMPLE_RATIO = 0.12
const BLUR_SIGMA = 2.34
const MAX_LONG_SIDE = 96
// Cap decoded pixels: compressed bytes expand many-fold in libvips, so this guards RSS, not input size.
-const LIMIT_INPUT_PIXELS = 50_000_000
+// Every sharp() decode of raw request bytes (here and in the ML path's src-image.ts) must pass this.
+export const LIMIT_INPUT_PIXELS = 50_000_000
+
+// 1x1 transparent PNG: the output substituted for an image the NSFW/gore gate rejects (see advancedScrub).
+export const BLANK_PNG = Buffer.from(
+ 'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNk+M9QDwADhgGAWjR9awAAAABJRU5ErkJggg==',
+ 'base64'
+)
export class UndecodableImageError extends Error {}
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/src/dbnet.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/src/dbnet.ts
new file mode 100644
index 000000000000..9db40278830a
--- /dev/null
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/src/dbnet.ts
@@ -0,0 +1,199 @@
+/**
+ * DBNet text-region detection via onnxruntime-node (native). Model: PP-OCRv3 detection (a DB head),
+ * ~2.4MB ONNX. Outputs a per-pixel text-probability map; we threshold it, horizontally dilate it
+ * (so words on a line bridge into one box that reaches the line end), find connected components,
+ * and return their expanded axis-aligned boxes. Axis-aligned is enough since we only blur.
+ *
+ * detectTextDbnet takes per-call opts so the same model can run a cheap production pass and an
+ * expensive high-recall verification pass (see verify.ts) in the same process.
+ */
+import * as ort from 'onnxruntime-node'
+
+import { numFromEnv } from './env.ts'
+import { type Box, roundTo32 } from './geometry.ts'
+import { type Src, srcSharp } from './src-image.ts'
+
+export interface DetectOpts {
+ detLimit?: number // detection budget SIDE: the model input is capped at detLimit^2 px (aspect preserved). Bigger = catches smaller text, slower.
+ probThreshold?: number // per-pixel text probability cutoff
+ boxScoreMin?: number // mean probability over a component's core pixels to keep it
+ minAreaPx?: number // min component size in model-resolution px
+ dilateX?: number // horizontal dilation radius (model-res px) to merge words on a line
+ padX?: number
+ padY?: number
+}
+
+const DEFAULTS: Required<DetectOpts> = {
+ detLimit: numFromEnv('DET_LIMIT', 640, 256, 4096),
+ probThreshold: numFromEnv('PROB_T', 0.3, 0.05, 0.9),
+ boxScoreMin: numFromEnv('BOX_SCORE', 0.5, 0.05, 0.95),
+ minAreaPx: numFromEnv('MIN_AREA', 16, 1, 1024),
+ dilateX: numFromEnv('DILATE_X', 6, 0, 64),
+ padX: numFromEnv('PAD_X', 0.25, 0, 2),
+ padY: numFromEnv('PAD_Y', 0.3, 0, 2),
+}
+
+const MEAN = [0.485, 0.456, 0.406]
+const STD = [0.229, 0.224, 0.225]
+
+export interface DbnetModel {
+ session: ort.InferenceSession
+ inputName: string
+ outputName: string
+}
+
+// 1 intra-op thread by default so we scale by running many images in parallel (one core each).
+const ORT_THREADS = numFromEnv('ORT_THREADS', 1, 1, 32)
+
+export async function loadDbnet(modelPath: string): Promise<DbnetModel> {
+ const session = await ort.InferenceSession.create(modelPath, {
+ graphOptimizationLevel: 'all',
+ intraOpNumThreads: ORT_THREADS,
+ interOpNumThreads: 1,
+ executionMode: 'sequential',
+ })
+ return { session, inputName: session.inputNames[0], outputName: session.outputNames[0] }
+}
+
+async function preprocess(
+ src: Src,
+ W: number,
+ H: number,
+ detLimit: number
+): Promise<{ data: Float32Array; rw: number; rh: number; sx: number; sy: number }> {
+ // Area budget (detLimit^2), aspect preserved: same tensor-size bound as a detLimit-square, but a
+ // tall page keeps its native text size instead of being squashed below detectability.
+ const ratio = Math.min(1, Math.sqrt((detLimit * detLimit) / (W * H)))
+ const rw = roundTo32(W * ratio)
+ const rh = roundTo32(H * ratio)
+ const { data } = await srcSharp(src).resize(rw, rh, { fit: 'fill' }).raw().toBuffer({ resolveWithObject: true })
+ const chw = new Float32Array(3 * rw * rh)
+ const plane = rw * rh
+ for (let i = 0, p = 0; i < data.length; i += 3, p++) {
+ chw[p] = (data[i] / 255 - MEAN[0]) / STD[0]
+ chw[plane + p] = (data[i + 1] / 255 - MEAN[1]) / STD[1]
+ chw[2 * plane + p] = (data[i + 2] / 255 - MEAN[2]) / STD[2]
+ }
+ return { data: chw, rw, rh, sx: W / rw, sy: H / rh }
+}
+
+/** Horizontal dilation by radius k via per-row prefix sums; bridges inter-word gaps on a line. */
+function dilateHoriz(bin: Uint8Array, rw: number, rh: number, k: number): Uint8Array {
+ if (k <= 0) {
+ return bin
+ }
+ const out = new Uint8Array(rw * rh)
+ const prefix = new Int32Array(rw + 1)
+ for (let y = 0; y < rh; y++) {
+ const row = y * rw
+ for (let x = 0; x < rw; x++) {
+ prefix[x + 1] = prefix[x] + bin[row + x]
+ }
+ for (let x = 0; x < rw; x++) {
+ const lo = Math.max(0, x - k)
+ const hi = Math.min(rw - 1, x + k)
+ out[row + x] = prefix[hi + 1] - prefix[lo] > 0 ? 1 : 0
+ }
+ }
+ return out
+}
+
+function postprocess(
+ prob: Float32Array,
+ rw: number,
+ rh: number,
+ sx: number,
+ sy: number,
+ W: number,
+ H: number,
+ o: Required<DetectOpts>
+): Box[] {
+ const bin = new Uint8Array(rw * rh)
+ for (let i = 0; i < prob.length; i++) {
+ bin[i] = prob[i] >= o.probThreshold ? 1 : 0
+ }
+ const dil = dilateHoriz(bin, rw, rh, o.dilateX)
+
+ const seen = new Uint8Array(rw * rh)
+ const stack: number[] = []
+ const boxes: Box[] = []
+ for (let start = 0; start < dil.length; start++) {
+ if (!dil[start] || seen[start]) {
+ continue
+ }
+ let minX = rw,
+ minY = rh,
+ maxX = 0,
+ maxY = 0
+ let coreSum = 0,
+ coreCnt = 0 // score only over real (pre-dilation) text pixels
+ stack.push(start)
+ seen[start] = 1
+ while (stack.length) {
+ const idx = stack.pop()!
+ const x = idx % rw
+ const y = (idx - x) / rw
+ if (bin[idx]) {
+ coreSum += prob[idx]
+ coreCnt++
+ }
+ if (x < minX) {
+ minX = x
+ }
+ if (x > maxX) {
+ maxX = x
+ }
+ if (y < minY) {
+ minY = y
+ }
+ if (y > maxY) {
+ maxY = y
+ }
+ if (x > 0 && dil[idx - 1] && !seen[idx - 1]) {
+ seen[idx - 1] = 1
+ stack.push(idx - 1)
+ }
+ if (x < rw - 1 && dil[idx + 1] && !seen[idx + 1]) {
+ seen[idx + 1] = 1
+ stack.push(idx + 1)
+ }
+ if (y > 0 && dil[idx - rw] && !seen[idx - rw]) {
+ seen[idx - rw] = 1
+ stack.push(idx - rw)
+ }
+ if (y < rh - 1 && dil[idx + rw] && !seen[idx + rw]) {
+ seen[idx + rw] = 1
+ stack.push(idx + rw)
+ }
+ }
+ if (coreCnt < o.minAreaPx || coreSum / coreCnt < o.boxScoreMin) {
+ continue
+ }
+ const ex = (maxX - minX + 1) * o.padX
+ const ey = (maxY - minY + 1) * o.padY
+ // min/max are inclusive pixel indices, so the box spans [min, max + 1) before padding.
+ const left = Math.max(0, Math.round((minX - ex) * sx))
+ const top = Math.max(0, Math.round((minY - ey) * sy))
+ const right = Math.min(W, Math.round((maxX + 1 + ex) * sx))
+ const bottom = Math.min(H, Math.round((maxY + 1 + ey) * sy))
+ if (right - left >= 2 && bottom - top >= 2) {
+ boxes.push({ left, top, width: right - left, height: bottom - top })
+ }
+ }
+ return boxes
+}
+
+export async function detectTextDbnet(
+ model: DbnetModel,
+ src: Src,
+ W: number,
+ H: number,
+ opts: DetectOpts = {}
+): Promise<Box[]> {
+ const o: Required<DetectOpts> = { ...DEFAULTS, ...opts }
+ const { data, rw, rh, sx, sy } = await preprocess(src, W, H, o.detLimit)
+ const tensor = new ort.Tensor('float32', data, [1, 3, rh, rw])
+ const out = await model.session.run({ [model.inputName]: tensor })
+ const prob = out[model.outputName].data as Float32Array
+ return postprocess(prob, rw, rh, sx, sy, W, H, o)
+}
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/src/env.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/src/env.ts
new file mode 100644
index 000000000000..b7f638700b12
--- /dev/null
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/src/env.ts
@@ -0,0 +1,14 @@
+/**
+ * Validated env-var tunables. The scrub knobs are correctness-critical: a typo'd value that parses
+ * to NaN fails OPEN (e.g. `prob >= NaN` is always false -> zero text boxes -> un-redacted output,
+ * silently counted as scrubbed). So every numeric knob must parse finite and in range, at module
+ * load, or the process refuses to start.
+ */
+export function numFromEnv(name: string, defaultValue: number, min: number, max: number): number {
+ const raw = process.env[name]
+ const value = raw === undefined ? defaultValue : Number(raw)
+ if (!Number.isFinite(value) || value < min || value > max) {
+ throw new Error(`${name} must be a number in [${min}, ${max}], got ${raw ?? defaultValue}`)
+ }
+ return value
+}
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/src/geometry.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/src/geometry.ts
new file mode 100644
index 000000000000..37639334d94c
--- /dev/null
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/src/geometry.ts
@@ -0,0 +1,11 @@
+export interface Box {
+ left: number
+ top: number
+ width: number
+ height: number
+}
+
+// ONNX detectors need input dims on a 32-px grid; floor at 32.
+export function roundTo32(n: number): number {
+ return Math.max(32, Math.round(n / 32) * 32)
+}
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/src/main.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/src/main.ts
index 0b79f802f7b8..41c8eba8bf46 100644
--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/src/main.ts
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/src/main.ts
@@ -1,8 +1,22 @@
import { loadConfig } from './config.ts'
+import { ScrubMetrics } from './metrics.ts'
+import { advancedScrub, loadModels } from './scrub.ts'
import { startServer } from './server.ts'
const cfg = loadConfig()
-const { scrub, metrics } = startServer(cfg.port, cfg.metricsPort, cfg.maxConcurrency, cfg.maxBodyBytes)
+// Models load before any listener exists, so the readiness probe can't pass until the scrub can run.
+const models = await loadModels()
+const { scrub, metrics } = startServer(
+ cfg.port,
+ cfg.metricsPort,
+ cfg.maxConcurrency,
+ cfg.maxBodyBytes,
+ async (input) => {
+ const { out, t } = await advancedScrub(input, models)
+ ScrubMetrics.observeScrubOutcome(t)
+ return out
+ }
+)
for (const sig of ['SIGINT', 'SIGTERM'] as const) {
process.on(sig, () => {
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/src/metrics.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/src/metrics.ts
index 5e8d75ded8c1..a21ef338bed2 100644
--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/src/metrics.ts
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/src/metrics.ts
@@ -1,5 +1,7 @@
import { Counter, Histogram, Registry } from 'prom-client'
+import { type StageTimings } from './scrub.ts'
+
export const register = new Registry()
const scrubbed = new Counter({
@@ -44,6 +46,29 @@ const outputBytes = new Histogram({
buckets: [64, 256, 1024, 4096, 16384, 65536],
registers: [register],
})
+// The scrub is a privacy control, so its OUTCOME signals matter as much as its error signals: a
+// runaway NSFW gate irreversibly blanking everything, or a detector flatlining at zero (persisting
+// un-redacted screenshots), must be distinguishable from healthy operation.
+const blanked = new Counter({
+ name: 'ml_mirror_image_scrub_blanked_total',
+ help: 'Images irreversibly replaced with a blank PNG by the NSFW/gore gate (alert on rate spikes)',
+ registers: [register],
+})
+const facesRedacted = new Counter({
+ name: 'ml_mirror_image_scrub_faces_redacted_total',
+ help: 'Face regions solid-filled (alert on a sustained zero rate under traffic: detector outage)',
+ registers: [register],
+})
+const textBoxesRedacted = new Counter({
+ name: 'ml_mirror_image_scrub_text_boxes_redacted_total',
+ help: 'Text regions solid-filled (alert on a sustained zero rate under traffic: detector outage)',
+ registers: [register],
+})
+const codesRedacted = new Counter({
+ name: 'ml_mirror_image_scrub_codes_redacted_total',
+ help: 'QR/barcode regions solid-filled',
+ registers: [register],
+})
export const ScrubMetrics = {
incScrubbed: () => scrubbed.inc(),
@@ -54,4 +79,12 @@ export const ScrubMetrics = {
incAborted: () => aborted.inc(),
startTimer: (): (() => void) => duration.startTimer(),
observeOutputBytes: (n: number) => outputBytes.observe(n),
+ observeScrubOutcome: (t: StageTimings): void => {
+ if (t.blanked) {
+ blanked.inc()
+ }
+ facesRedacted.inc(t.faces)
+ textBoxesRedacted.inc(t.textBoxes)
+ codesRedacted.inc(t.codes)
+ },
}
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/src/qr.test.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/src/qr.test.ts
new file mode 100644
index 000000000000..4befc5794a83
--- /dev/null
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/src/qr.test.ts
@@ -0,0 +1,52 @@
+/**
+ * detectCodes failing open (zero boxes, no error) would ship un-redacted codes, so this pins the
+ * whole chain — wasm loading from node_modules, RGB->RGBA expansion, corner->padded-box mapping —
+ * against a QR composited at a known location. Runs without the ONNX models, so it's the one
+ * detector CI can exercise.
+ */
+import { readFileSync } from 'node:fs'
+import sharp from 'sharp'
+import { prepareZXingModule, writeBarcode } from 'zxing-wasm/writer'
+
+import { detectCodes } from './qr.ts'
+
+const writerWasm = readFileSync(require.resolve('zxing-wasm/writer/zxing_writer.wasm'))
+prepareZXingModule({
+ overrides: {
+ wasmBinary: writerWasm.buffer.slice(writerWasm.byteOffset, writerWasm.byteOffset + writerWasm.byteLength),
+ },
+})
+
+describe('detectCodes', () => {
+ it('returns an in-bounds padded box covering a QR composited at a known location', async () => {
+ const qr = await writeBarcode('otpauth://totp/test?secret=JBSWY3DPEHPK3PXP', {
+ format: 'QRCode',
+ scale: 4,
+ })
+ const qrPng = Buffer.from(await qr.image!.arrayBuffer())
+ const { width: qrW, height: qrH } = await sharp(qrPng).metadata()
+ const [frameW, frameH, qrLeft, qrTop] = [800, 600, 500, 300]
+
+ const { data, info } = await sharp({
+ create: { width: frameW, height: frameH, channels: 3, background: '#fff' },
+ })
+ .composite([{ input: qrPng, left: qrLeft, top: qrTop }])
+ .removeAlpha()
+ .raw()
+ .toBuffer({ resolveWithObject: true })
+
+ const boxes = await detectCodes({ data, W: info.width, H: info.height })
+
+ expect(boxes).toHaveLength(1)
+ const b = boxes[0]
+ expect(b.left).toBeGreaterThanOrEqual(0)
+ expect(b.top).toBeGreaterThanOrEqual(0)
+ expect(b.left + b.width).toBeLessThanOrEqual(frameW)
+ expect(b.top + b.height).toBeLessThanOrEqual(frameH)
+ // the padded box must fully cover the QR itself
+ expect(b.left).toBeLessThanOrEqual(qrLeft)
+ expect(b.top).toBeLessThanOrEqual(qrTop)
+ expect(b.left + b.width).toBeGreaterThanOrEqual(qrLeft + qrW!)
+ expect(b.top + b.height).toBeGreaterThanOrEqual(qrTop + qrH!)
+ })
+})
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/src/qr.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/src/qr.ts
new file mode 100644
index 000000000000..c0af4c0a03de
--- /dev/null
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/src/qr.ts
@@ -0,0 +1,64 @@
+/**
+ * QR / barcode detection via zxing-wasm (pure wasm, no native deps). Machine-decodable codes are a
+ * PII-carrier class the face/text detectors can't see — a TOTP provisioning QR or a ticket barcode
+ * survives selective redaction at full fidelity — so detected codes get the same solid fill as text.
+ * zxing only reports codes it can decode, which is the right bar: a code too degraded to decode is
+ * also too degraded to leak.
+ */
+import { readFileSync } from 'node:fs'
+import { createRequire } from 'node:module'
+import { prepareZXingModule, readBarcodes } from 'zxing-wasm/reader'
+
+import { type Box } from './geometry.ts'
+import { type Src } from './src-image.ts'
+
+// zxing-wasm's default loader fetches its .wasm from a CDN on first use; hand it the binary that
+// shipped in node_modules instead, so the worker needs no runtime egress and always runs the build
+// the lockfile pinned. createRequire over import.meta so jest's CJS transform can load this module;
+// cwd-based resolution matches the package's existing cwd-relative model paths (WORKDIR /code/app).
+const wasmFile = createRequire(`${process.cwd()}/`).resolve('zxing-wasm/reader/zxing_reader.wasm')
+const wasmBytes = readFileSync(wasmFile)
+prepareZXingModule({
+ overrides: {
+ wasmBinary: wasmBytes.buffer.slice(wasmBytes.byteOffset, wasmBytes.byteOffset + wasmBytes.byteLength),
+ },
+})
+
+const PAD = 0.15 // expand each hit so quiet zones / clipped modules are covered
+
+export async function detectCodes(src: Src): Promise<Box[]> {
+ const { data, W, H } = src
+ // zxing takes RGBA ImageData; expand the shared raw RGB in one pass.
+ const rgba = new Uint8ClampedArray(W * H * 4)
+ for (let i = 0, o = 0; i < data.length; i += 3, o += 4) {
+ rgba[o] = data[i]
+ rgba[o + 1] = data[i + 1]
+ rgba[o + 2] = data[i + 2]
+ rgba[o + 3] = 255
+ }
+ // Structural ImageData (zxing dispatches on width/height/data); Node has no ImageData class, so
+ // colorSpace only exists to satisfy the DOM type.
+ const imageData = { data: rgba, width: W, height: H, colorSpace: 'srgb' } as ImageData
+ const results = await readBarcodes(imageData, { tryHarder: true, maxNumberOfSymbols: 32 })
+
+ const boxes: Box[] = []
+ for (const r of results) {
+ const p = r.position
+ const xs = [p.topLeft.x, p.topRight.x, p.bottomLeft.x, p.bottomRight.x]
+ const ys = [p.topLeft.y, p.topRight.y, p.bottomLeft.y, p.bottomRight.y]
+ const minX = Math.min(...xs)
+ const maxX = Math.max(...xs)
+ const minY = Math.min(...ys)
+ const maxY = Math.max(...ys)
+ const px = (maxX - minX) * PAD
+ const py = (maxY - minY) * PAD
+ const left = Math.max(0, Math.round(minX - px))
+ const top = Math.max(0, Math.round(minY - py))
+ const right = Math.min(W, Math.round(maxX + px))
+ const bottom = Math.min(H, Math.round(maxY + py))
+ if (right - left >= 2 && bottom - top >= 2) {
+ boxes.push({ left, top, width: right - left, height: bottom - top })
+ }
+ }
+ return boxes
+}
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/src/safety.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/src/safety.ts
new file mode 100644
index 000000000000..311cbc171366
--- /dev/null
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/src/safety.ts
@@ -0,0 +1,54 @@
+/**
+ * NSFW/gore gate via onnxruntime-node. Model: image-safety-classifier-xs (SwiftFormer, 3.5M params,
+ * MIT), 224x224 input, softmax over [NSFL, NSFW, SFW] baked into the graph — the output IS
+ * probabilities. The gate runs on ORT like the other detectors so the whole scrub shares one ML
+ * runtime, and the NSFL class is what makes the gate cover gore, not just nudity.
+ */
+import * as ort from 'onnxruntime-node'
+
+import { numFromEnv } from './env.ts'
+import { type Src, srcSharp } from './src-image.ts'
+
+const SAFETY_SIZE = 224 // fixed model input; pixel values 0-255 (normalization is baked into the graph)
+const ORT_THREADS = numFromEnv('ORT_THREADS', 1, 1, 32)
+
+export interface SafetyModel {
+ session: ort.InferenceSession
+ inputName: string
+ outputName: string
+}
+
+export async function loadSafety(modelPath: string): Promise<SafetyModel> {
+ const session = await ort.InferenceSession.create(modelPath, {
+ graphOptimizationLevel: 'all',
+ intraOpNumThreads: ORT_THREADS,
+ interOpNumThreads: 1,
+ executionMode: 'sequential',
+ })
+ return { session, inputName: session.inputNames[0], outputName: session.outputNames[0] }
+}
+
+export interface SafetyScores {
+ nsfl: number
+ nsfw: number
+ sfw: number
+}
+
+export async function classifySafety(model: SafetyModel, src: Src): Promise<SafetyScores> {
+ const { data } = await srcSharp(src)
+ .resize(SAFETY_SIZE, SAFETY_SIZE, { fit: 'fill' })
+ .raw()
+ .toBuffer({ resolveWithObject: true })
+ const plane = SAFETY_SIZE * SAFETY_SIZE
+ const chw = new Float32Array(3 * plane)
+ for (let i = 0, p = 0; i < data.length; i += 3, p++) {
+ chw[p] = data[i]
+ chw[plane + p] = data[i + 1]
+ chw[2 * plane + p] = data[i + 2]
+ }
+ const out = await model.session.run({
+ [model.inputName]: new ort.Tensor('float32', chw, [1, 3, SAFETY_SIZE, SAFETY_SIZE]),
+ })
+ const probs = out[model.outputName].data as Float32Array
+ return { nsfl: probs[0], nsfw: probs[1], sfw: probs[2] }
+}
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/src/scrub.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/src/scrub.ts
new file mode 100644
index 000000000000..36c33d17a37c
--- /dev/null
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/src/scrub.ts
@@ -0,0 +1,346 @@
+/**
+ * The image-scrub pipelines. Two entry points over the same input so throughput stays comparable:
+ * - blurOnly: the cheap baseline (downsample + gaussian blur), kept in sync with the inline
+ * anonymizer's rust/replay-anonymizer-node/src/blur.rs so comparisons are apples-to-apples.
+ * - advancedScrub: NSFW/gore gate -> faces, text regions, and QR/barcodes solid-filled.
+ *
+ * All three models (safety gate, YuNet faces, DBNet text) run on native onnxruntime-node —
+ * deliberately ONE ML runtime, so there is a single native-binary compatibility surface and no
+ * second runtime with its own failure modes or slow fallback backend. QR/barcode detection runs on
+ * zxing-wasm. The source is decoded once to raw RGB (area-capped at SCRUB_MAX_PIXELS) and shared
+ * across stages.
+ */
+import sharp from 'sharp'
+
+import { BLANK_PNG, LIMIT_INPUT_PIXELS, UndecodableImageError, blurOnly } from './blur.ts'
+import { type DbnetModel, detectTextDbnet, loadDbnet } from './dbnet.ts'
+import { numFromEnv } from './env.ts'
+import { type Box } from './geometry.ts'
+import { detectCodes } from './qr.ts'
+import { type SafetyModel, classifySafety, loadSafety } from './safety.ts'
+import { type Src, decodeSrc, srcSharp } from './src-image.ts'
+import { type YunetModel, detectFacesYunet, loadYunet } from './yunet.ts'
+
+export type TextMode = 'heuristic' | 'dbnet'
+
+// blurOnly/BLANK_PNG live in the ML-dep-free blur.ts; re-exported here so the eval harness and
+// benchmarks can compare the baseline against advancedScrub from one module.
+export { BLANK_PNG, blurOnly }
+
+// --- models -------------------------------------------------------------------------------------
+export interface Models {
+ safety: SafetyModel
+ dbnet: DbnetModel
+ yunet: YunetModel
+}
+
+export async function loadModels(
+ dbnetPath = 'models/dbnet_det.onnx',
+ yunetPath = 'models/yunet.onnx',
+ safetyPath = 'models/safety.onnx'
+): Promise<Models> {
+ const [safety, dbnet, yunet] = await Promise.all([
+ loadSafety(safetyPath),
+ loadDbnet(dbnetPath),
+ loadYunet(yunetPath),
+ ])
+ return { safety, dbnet, yunet }
+}
+
+export async function disposeModels(m: Models): Promise<void> {
+ await Promise.all([m.safety.session.release(), m.dbnet.session.release(), m.yunet.session.release()])
+}
+
+// --- advanced pipeline --------------------------------------------------------------------------
+export interface StageTimings {
+ decodeMs: number
+ nsfwMs: number
+ faceMs: number
+ textMs: number
+ codesMs: number
+ composeMs: number
+ encodeMs: number
+ totalMs: number
+ blanked: boolean
+ faces: number
+ textBoxes: number
+ codes: number
+}
+
+const NSFW_THRESHOLD = numFromEnv('NSFW_THRESHOLD', 0.6, 0.05, 0.95) // NSFL+NSFW combined; deliberately loose, this is a safety net
+const PNG_LEVEL = numFromEnv('PNG_LEVEL', 3, 0, 9) // sharp png compressionLevel; lower = faster, bigger
+// Every redaction (faces, text, codes) is a SOLID mean-colour fill (irreversible) rather than a
+// blur/mosaic (low-pass filters that leave coarse structure an LLM or a re-run detector can still
+// recover). Text margin scales with box height — our horizontal-only dilation makes each box one
+// line, so its height is a font-size proxy — so big titles get a big margin. Edges are feathered so
+// the fill isn't a jarring hard rectangle.
+const TEXT_MARGIN_FRAC = numFromEnv('TEXT_MARGIN_FRAC', 0.25, 0, 2) // top/side margin as a fraction of box height
+const TEXT_MARGIN_BOTTOM_FRAC = numFromEnv('TEXT_MARGIN_BOTTOM_FRAC', 0.45, 0, 2) // extra below for descenders
+const TEXT_MARGIN_MIN = numFromEnv('TEXT_MARGIN_MIN', 4, 0, 64) // floor in px for tiny text
+const EDGE_BLUR = numFromEnv('EDGE_BLUR', 4, 0, 32) // sigma to feather redaction-region edges (0 = hard edges; never reveals)
+
+function clampBox(b: Box, W: number, H: number): Box | null {
+ const left = Math.max(0, Math.min(W - 1, Math.round(b.left)))
+ const top = Math.max(0, Math.min(H - 1, Math.round(b.top)))
+ const width = Math.max(1, Math.min(W - left, Math.round(b.width)))
+ const height = Math.max(1, Math.min(H - top, Math.round(b.height)))
+ if (width < 2 || height < 2) {
+ return null
+ }
+ return { left, top, width, height }
+}
+
+// --- input preparation --------------------------------------------------------------------------
+/** Adaptive DBNet detection budget: big enough to resolve small text on retina shots, capped for cost.
+ * The returned value is the budget SIDE — dbnet caps its input at detLimit^2 px, aspect preserved. */
+// Detection budget as a fraction of the image's own scale (sqrt of its area). 0.75 clears all crisp
+// rendered UI (session replay's actual domain) cheaply; raise toward 1.0 for faint/small
+// scanned-document print (more CPU), lower for more throughput. Faint low-contrast text is
+// contrast- not size-limited, so resolution alone won't catch every faded fax line.
+const DET_FACTOR = numFromEnv('DET_FACTOR', 0.75, 0.1, 1)
+const DET_CAP = numFromEnv('DET_CAP', 1600, 256, 4096) // cap so retina screenshots don't explode
+function adaptiveDetLimit(W: number, H: number): number {
+ const target = Math.round((Math.sqrt(W * H) * DET_FACTOR) / 32) * 32
+ return Math.max(736, Math.min(DET_CAP, target))
+}
+
+/** Whole worker job for one image, advanced path. Detection is parallelized when PARALLEL_DETECT=1:
+ * the three ORT sessions run on onnxruntime's background threads. */
+export async function advancedScrub(
+ input: Buffer,
+ m: Models,
+ textMode: TextMode = 'dbnet'
+): Promise<{ out: Buffer; t: StageTimings }> {
+ const timings: StageTimings = {
+ decodeMs: 0,
+ nsfwMs: 0,
+ faceMs: 0,
+ textMs: 0,
+ codesMs: 0,
+ composeMs: 0,
+ encodeMs: 0,
+ totalMs: 0,
+ blanked: false,
+ faces: 0,
+ textBoxes: 0,
+ codes: 0,
+ }
+ const t0 = performance.now()
+ const tDec = performance.now()
+ // Decode the PNG ONCE; every stage re-wraps these raw pixels. The decode is the only stage that
+ // consumes untrusted bytes, so its failures are permanent-for-these-bytes (422/skip), never 500.
+ let src: Src
+ try {
+ src = await decodeSrc(input)
+ } catch (e) {
+ throw e instanceof UndecodableImageError ? e : new UndecodableImageError(String(e))
+ }
+ const { W, H } = src
+ timings.decodeMs = performance.now() - tDec
+
+ // 1. NSFW / gore gate FIRST: if it trips we skip all detection. Running it first (rather than
+ // overlapping detection) keeps each worker ~1 core, which packs better under multi-process
+ // scaling — the throughput-bound case. Set PARALLEL_DETECT=1 to overlap instead (lower latency
+ // per image, but each worker uses more cores).
+ const tN = performance.now()
+ const scores = await classifySafety(m.safety, src)
+ const bad = scores.nsfl + scores.nsfw
+ timings.nsfwMs = performance.now() - tN
+ if (bad >= NSFW_THRESHOLD) {
+ timings.blanked = true
+ timings.totalMs = performance.now() - t0
+ return { out: BLANK_PNG, t: timings }
+ }
+
+ // 2. Face (YuNet) + text (DBNet) on native ORT, codes (zxing) on wasm. Serial by default
+ // (1 core/worker); parallel opt-in.
+ const det = adaptiveDetLimit(W, H)
+ const runText = (): Promise<Box[]> =>
+ textMode === 'dbnet' ? detectTextDbnet(m.dbnet, src, W, H, { detLimit: det }) : detectTextRegions(input, W, H)
+ let faceBoxes: Box[]
+ let textBoxes: Box[]
+ let codeBoxes: Box[]
+ if (process.env.PARALLEL_DETECT === '1') {
+ const tD = performance.now()
+ ;[faceBoxes, textBoxes, codeBoxes] = await Promise.all([
+ detectFacesYunet(m.yunet, src, W, H),
+ runText(),
+ detectCodes(src),
+ ])
+ timings.faceMs = timings.textMs = timings.codesMs = performance.now() - tD
+ } else {
+ const tF = performance.now()
+ faceBoxes = await detectFacesYunet(m.yunet, src, W, H)
+ timings.faceMs = performance.now() - tF
+ const tT = performance.now()
+ textBoxes = await runText()
+ timings.textMs = performance.now() - tT
+ const tQ = performance.now()
+ codeBoxes = await detectCodes(src)
+ timings.codesMs = performance.now() - tQ
+ }
+ timings.faces = faceBoxes.length
+ timings.textBoxes = textBoxes.length
+ timings.codes = codeBoxes.length
+
+ // Text boxes get a font-size-scaled margin (DBNet boxes sit on the baseline, so descenders —
+ // g, y, p, q, j — hang below and need extra coverage underneath). Face boxes are already padded
+ // by the detector (yunet PAD) and code boxes by detectCodes; they fill as-is.
+ const expandText = (t: Box): Box | null => {
+ const mg = Math.round(Math.max(TEXT_MARGIN_MIN, t.height * TEXT_MARGIN_FRAC))
+ const mb = Math.round(Math.max(TEXT_MARGIN_MIN, t.height * TEXT_MARGIN_BOTTOM_FRAC))
+ return clampBox(
+ { left: t.left - mg, top: t.top - mg, width: t.width + 2 * mg, height: t.height + mg + mb },
+ W,
+ H
+ )
+ }
+ const fillBoxes = [...faceBoxes, ...textBoxes.map(expandText).filter((b): b is Box => b !== null), ...codeBoxes]
+
+ const out = await compose(src, W, H, fillBoxes, timings)
+ timings.totalMs = performance.now() - t0
+ return { out, t: timings }
+}
+
+/**
+ * Model-free text detector. Text has high local edge density, so: downscale to grayscale, compute
+ * a gradient map, tile it, and mark tiles whose mean gradient is high (but not saturated, which
+ * filters out hard image/photo edges). Returns the texty tiles as boxes in full-res coords. Rough,
+ * but we only need "blur where text is", not character-accurate boxes.
+ */
+const TEXT_DS_WIDTH = 480 // downscale width for the gradient pass
+const TEXT_TILE = 10 // tile size in downscaled px
+const TEXT_EDGE_T = 22 // mean gradient threshold for a tile to count as text
+
+async function detectTextRegions(input: Buffer, W: number, H: number): Promise<Box[]> {
+ const dsW = Math.min(W, TEXT_DS_WIDTH)
+ const sx = W / dsW
+ const dsH = Math.max(1, Math.round(H / sx))
+ const { data, info } = await sharp(input, { limitInputPixels: LIMIT_INPUT_PIXELS })
+ .grayscale()
+ .resize(dsW, dsH, { fit: 'fill' })
+ .raw()
+ .toBuffer({ resolveWithObject: true })
+ const w = info.width
+ const h = info.height
+ const cols = Math.ceil(w / TEXT_TILE)
+ const rows = Math.ceil(h / TEXT_TILE)
+ const sum = new Float64Array(cols * rows)
+ const cnt = new Int32Array(cols * rows)
+ const sat = new Int32Array(cols * rows) // count of very-strong edges (likely photo/icon, not text)
+
+ for (let y = 1; y < h - 1; y++) {
+ const row = y * w
+ for (let x = 1; x < w - 1; x++) {
+ const i = row + x
+ const g = Math.abs(data[i + 1] - data[i - 1]) + Math.abs(data[i + w] - data[i - w])
+ const ci = Math.floor(y / TEXT_TILE) * cols + Math.floor(x / TEXT_TILE)
+ sum[ci] += g
+ cnt[ci]++
+ if (g > 200) {
+ sat[ci]++
+ }
+ }
+ }
+
+ const boxes: Box[] = []
+ for (let r = 0; r < rows; r++) {
+ for (let c = 0; c < cols; c++) {
+ const ci = r * cols + c
+ const n = cnt[ci]
+ if (n === 0) {
+ continue
+ }
+ const mean = sum[ci] / n
+ const satFrac = sat[ci] / n
+ if (mean > TEXT_EDGE_T && satFrac < 0.12) {
+ const b = clampBox(
+ {
+ left: c * TEXT_TILE * sx,
+ top: r * TEXT_TILE * sx,
+ width: TEXT_TILE * sx,
+ height: TEXT_TILE * sx,
+ },
+ W,
+ H
+ )
+ if (b) {
+ boxes.push(b)
+ }
+ }
+ }
+ }
+ return boxes
+}
+
+/** Overwrite every redaction box (faces, text, codes alike) with its quantized mean colour on a
+ * copy of the frame, then composite that copy back over the original through a hard alpha mask.
+ * Box-count-independent: one full-frame blur + one composite regardless of box count. The blur
+ * feathers only the fill COLOUR into its surroundings — the alpha stays hard, so no original
+ * pixels inside a box ever survive. A solid fill carries no glyph, face, or code-module structure
+ * (blur and mosaic are low-pass filters whose coarse structure an LLM or a re-run detector can
+ * still recover), so the same irreversible treatment covers all three classes. */
+async function compose(src: Src, W: number, H: number, boxes: Box[], timings: StageTimings): Promise<Buffer> {
+ const tC = performance.now()
+ if (boxes.length === 0) {
+ timings.composeMs = performance.now() - tC
+ const tE0 = performance.now()
+ const out0 = await srcSharp(src).png({ compressionLevel: PNG_LEVEL }).toBuffer()
+ timings.encodeMs = performance.now() - tE0
+ return out0
+ }
+
+ // Redaction layer starts as a copy of the source; boxes are OVERWRITTEN rather than low-pass
+ // filtered, so their content is destroyed (irreversible), not merely softened. The base frame
+ // must stay pristine — outside the mask the composite shows it — which is why the fills go into
+ // a copy rather than in place.
+ const red = Buffer.from(src.data)
+ const alpha = new Uint8Array(W * H)
+
+ for (const b of boxes) {
+ let r = 0,
+ g = 0,
+ bl = 0
+ const n = b.width * b.height
+ for (let y = b.top; y < b.top + b.height; y++) {
+ let idx = (y * W + b.left) * 3
+ for (let x = 0; x < b.width; x++, idx += 3) {
+ r += src.data[idx]
+ g += src.data[idx + 1]
+ bl += src.data[idx + 2]
+ }
+ }
+ // Quantize the fill to the top 4 bits per channel (16 levels each, 12 bits total instead of
+ // 24) so it carries even less signal about the underlying content's colours.
+ r = Math.round(r / n) & 0xf0
+ g = Math.round(g / n) & 0xf0
+ bl = Math.round(bl / n) & 0xf0
+ for (let y = b.top; y < b.top + b.height; y++) {
+ let idx = (y * W + b.left) * 3
+ for (let x = 0; x < b.width; x++, idx += 3) {
+ red[idx] = r
+ red[idx + 1] = g
+ red[idx + 2] = bl
+ }
+ alpha.fill(255, y * W + b.left, y * W + b.left + b.width)
+ }
+ }
+
+ const raw3 = { raw: { width: W, height: H, channels: 3 } } as const
+ const raw1 = { raw: { width: W, height: H, channels: 1 } } as const
+ const alphaLayer = Buffer.from(alpha.buffer, alpha.byteOffset, alpha.byteLength)
+
+ // Soften edges by blurring the COLOUR layer only (alpha stays hard, so nothing under a box is
+ // ever revealed; the blur just fades the fill into its background margin).
+ const redBlurred = EDGE_BLUR > 0 ? await sharp(red, raw3).blur(EDGE_BLUR).raw().toBuffer() : red
+ const overlay = await sharp(redBlurred, raw3).joinChannel(alphaLayer, raw1).png().toBuffer()
+
+ timings.composeMs = performance.now() - tC
+ const tE = performance.now()
+ const out = await srcSharp(src)
+ .composite([{ input: overlay, left: 0, top: 0 }])
+ .png({ compressionLevel: PNG_LEVEL })
+ .toBuffer()
+ timings.encodeMs = performance.now() - tE
+ return out
+}
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/src/server.test.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/src/server.test.ts
index b271b1b9d8c5..8e02e287a71c 100644
--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/src/server.test.ts
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/src/server.test.ts
@@ -1,6 +1,7 @@
import { once } from 'node:events'
import type { AddressInfo } from 'node:net'
+import { blurOnly } from './blur.ts'
import { startServer } from './server.ts'
const PNG = Buffer.from(
@@ -14,7 +15,9 @@ describe('image-scrub sidecar server', () => {
let servers: ReturnType<typeof startServer>
beforeAll(async () => {
- servers = startServer(0, 0, 4, 1024)
+ // The model-free blur keeps this suite about the HTTP plumbing; the ML scrub path is
+ // exercised by the image build's smoke test and the dev eval harness.
+ servers = startServer(0, 0, 4, 1024, blurOnly)
await Promise.all([once(servers.scrub, 'listening'), once(servers.metrics, 'listening')])
base = `http://127.0.0.1:${(servers.scrub.address() as AddressInfo).port}`
metricsBase = `http://127.0.0.1:${(servers.metrics.address() as AddressInfo).port}`
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/src/server.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/src/server.ts
index f05807f1a583..c539d4b9d3e0 100644
--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/src/server.ts
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/src/server.ts
@@ -2,17 +2,14 @@
import express, { type NextFunction, type Request, type Response } from 'express'
import { type Server } from 'node:http'
-import { UndecodableImageError, blurOnly } from './blur.ts'
+import { UndecodableImageError } from './blur.ts'
import { ScrubMetrics, register } from './metrics.ts'
class ConsumerHungUpError extends Error {}
-async function scrub(input: Buffer, signal: AbortSignal): Promise<Buffer> {
- if (signal.aborted) {
- throw new ConsumerHungUpError()
- }
- return blurOnly(input)
-}
+/** The scrub implementation is injected (main.ts wires advancedScrub over its loaded models; tests
+ * inject the model-free blur) so the HTTP plumbing stays testable without the ML runtime. */
+export type ScrubFn = (input: Buffer) => Promise<Buffer>
export interface SidecarServers {
// /scrub, bound to loopback — the pod IP must never expose it.
@@ -25,8 +22,16 @@ export function startServer(
port: number,
metricsPort: number,
maxConcurrency: number,
- maxBodyBytes: number
+ maxBodyBytes: number,
+ scrubFn: ScrubFn
): SidecarServers {
+ async function scrub(input: Buffer, signal: AbortSignal): Promise<Buffer> {
+ if (signal.aborted) {
+ throw new ConsumerHungUpError()
+ }
+ return scrubFn(input)
+ }
+
let inFlight = 0
const app = express()
app.disable('x-powered-by')
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/src/smoke.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/src/smoke.ts
new file mode 100644
index 000000000000..aa4026cc1272
--- /dev/null
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/src/smoke.ts
@@ -0,0 +1,24 @@
+/**
+ * Startup smoke test: loads the models and runs one scrub end to end. Run at image-build time (see
+ * Dockerfile.ml-mirror-image-scrub) with networking disabled, so a missing/corrupt model, a
+ * prebuilt-binary mismatch, or an accidental runtime network dependency fails the build instead of
+ * crash-looping the deploy.
+ */
+import sharp from 'sharp'
+
+import { advancedScrub, disposeModels, loadModels } from './scrub.ts'
+
+async function main(): Promise<void> {
+ const models = await loadModels()
+ const png = await sharp({ create: { width: 64, height: 64, channels: 3, background: '#fff' } })
+ .png()
+ .toBuffer()
+ const { t } = await advancedScrub(png, models)
+ await disposeModels(models)
+ console.log(`smoke scrub OK (${Math.round(t.totalMs)}ms)`)
+}
+
+main().catch((e) => {
+ console.error(e)
+ process.exit(1)
+})
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/src/src-image.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/src/src-image.ts
new file mode 100644
index 000000000000..4c09da17ab33
--- /dev/null
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/src/src-image.ts
@@ -0,0 +1,45 @@
+/** Decode the source image ONCE to raw RGB; every stage re-wraps it instead of re-decoding the PNG.
+ * Decoding a multi-megapixel PNG is tens of ms; the pipeline touches the source 4-5 times. */
+import sharp from 'sharp'
+
+import { LIMIT_INPUT_PIXELS } from './blur.ts'
+import { numFromEnv } from './env.ts'
+
+// Every frame is downscaled (aspect preserved) to this pixel-AREA budget inside the decode,
+// unconditionally. Two reasons: (1) memory — compose holds a few full-frame buffers, and bytes are
+// proportional to area, so the budget bounds the per-image working set (~8 MB/frame at 1600^2 vs
+// ~150 MB at the 50 MP decode limit); (2) fidelity honesty — text detection runs under the same
+// area budget (DET_CAP^2), so storing pixels above it would preserve exactly the detail the
+// detectors never certified as clean. An area budget rather than a long-side cap so tall pages
+// (skyscraper screenshots, infographics) keep legible native resolution instead of being squashed.
+export const SCRUB_MAX_PIXELS = numFromEnv('SCRUB_MAX_PIXELS', 1600 * 1600, 96 * 96, LIMIT_INPUT_PIXELS)
+
+export interface Src {
+ data: Buffer
+ W: number
+ H: number
+}
+
+export async function decodeSrc(input: Buffer): Promise<Src> {
+ const meta = await sharp(input, { limitInputPixels: LIMIT_INPUT_PIXELS }).metadata()
+ if (!meta.width || !meta.height) {
+ throw new Error('image has invalid dimensions')
+ }
+ const scale = Math.min(1, Math.sqrt(SCRUB_MAX_PIXELS / (meta.width * meta.height)))
+ const targetW = Math.max(1, Math.round(meta.width * scale))
+ const targetH = Math.max(1, Math.round(meta.height * scale))
+ // flatten, NOT removeAlpha: removeAlpha discards the alpha channel but keeps the RGB underneath,
+ // so content hidden under fully transparent pixels (invisible in the replay) would surface in
+ // the scrubbed output. Flatten composites over a background, destroying hidden RGB.
+ const { data, info } = await sharp(input, { limitInputPixels: LIMIT_INPUT_PIXELS })
+ .resize(targetW, targetH, { fit: 'fill' })
+ .flatten({ background: '#fff' })
+ .raw()
+ .toBuffer({ resolveWithObject: true })
+ return { data, W: info.width, H: info.height }
+}
+
+/** A fresh sharp pipeline over the already-decoded raw pixels (no PNG decode). */
+export function srcSharp(s: Src): sharp.Sharp {
+ return sharp(s.data, { raw: { width: s.W, height: s.H, channels: 3 } })
+}
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/src/yunet.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/src/yunet.ts
new file mode 100644
index 000000000000..73a6c8e2e1cb
--- /dev/null
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/src/yunet.ts
@@ -0,0 +1,182 @@
+/**
+ * YuNet face detection via onnxruntime-node (native, async). One multi-scale pass (strides 8/16/32)
+ * detects small and large faces at once, so normal-aspect frames need a single inference; only
+ * extreme-aspect frames are tiled (see detectionWindows).
+ *
+ * Decode follows OpenCV's FaceDetectorYN: score = sqrt(cls*obj), grid-anchor bbox, then greedy NMS.
+ */
+import * as ort from 'onnxruntime-node'
+
+import { numFromEnv } from './env.ts'
+import { type Box } from './geometry.ts'
+import { type Src, srcSharp } from './src-image.ts'
+
+const YUNET_SIDE = 640 // this YuNet build has a FIXED 640x640 input (dynamic dims are rejected)
+const SCORE_MIN = numFromEnv('YUNET_SCORE', 0.7, 0.05, 0.95)
+const NMS_IOU = 0.3
+const STRIDES = [8, 16, 32]
+const PAD = 0.25 // expand each detected face box so hairline/chin/ears are covered
+const ORT_THREADS = numFromEnv('ORT_THREADS', 1, 1, 32)
+
+export interface YunetModel {
+ session: ort.InferenceSession
+ inputName: string
+}
+
+export async function loadYunet(modelPath: string): Promise<YunetModel> {
+ const session = await ort.InferenceSession.create(modelPath, {
+ graphOptimizationLevel: 'all',
+ intraOpNumThreads: ORT_THREADS,
+ interOpNumThreads: 1,
+ executionMode: 'sequential',
+ })
+ return { session, inputName: session.inputNames[0] }
+}
+
+function iou(a: Box, b: Box): number {
+ const x1 = Math.max(a.left, b.left)
+ const y1 = Math.max(a.top, b.top)
+ const x2 = Math.min(a.left + a.width, b.left + b.width)
+ const y2 = Math.min(a.top + a.height, b.top + b.height)
+ const inter = Math.max(0, x2 - x1) * Math.max(0, y2 - y1)
+ return inter === 0 ? 0 : inter / (a.width * a.height + b.width * b.height - inter)
+}
+
+export interface FaceOpts {
+ scoreMin?: number // lower = more sensitive (the verification pass uses this to catch lingering faces)
+}
+
+// Tiling bounds for extreme-aspect frames. A single letterboxed pass scales by 640/longSide, so on a
+// very tall/wide image a face (at most ~shortSide across) can land below the detector's smallest
+// stride. Above MAX_ASPECT the frame is cut along its long axis into windows of aspect TILE_ASPECT
+// (overlapping by one shortSide, so a face — at most one shortSide across — is always fully inside
+// some window): each window then scales by 640/(TILE_ASPECT*shortSide), keeping any face at least
+// ~640/TILE_ASPECT/(shortSide/faceSize) px. TILE_ASPECT=6 keeps a face spanning the full short side
+// at >=107px and a quarter-width face at >=27px, both comfortably detectable.
+const MAX_ASPECT = 3
+const TILE_ASPECT = 6
+
+interface Window {
+ left: number
+ top: number
+ width: number
+ height: number
+}
+
+function detectionWindows(W: number, H: number): Window[] {
+ const long = Math.max(W, H)
+ const short = Math.min(W, H)
+ if (long / short <= MAX_ASPECT) {
+ return [{ left: 0, top: 0, width: W, height: H }]
+ }
+ const windowLong = TILE_ASPECT * short
+ const stride = windowLong - short // overlap of one shortSide: no face can straddle two windows undetected
+ const windows: Window[] = []
+ for (let pos = 0; ; pos += stride) {
+ const start = Math.min(pos, long - windowLong)
+ windows.push(
+ W >= H
+ ? { left: start, top: 0, width: Math.min(windowLong, long), height: H }
+ : { left: 0, top: start, width: W, height: Math.min(windowLong, long) }
+ )
+ if (start + windowLong >= long) {
+ break
+ }
+ }
+ return windows
+}
+
+async function detectInWindow(
+ model: YunetModel,
+ src: Src,
+ W: number,
+ H: number,
+ win: Window,
+ scoreMin: number
+): Promise<{ b: Box; s: number }[]> {
+ // The model input is a fixed square, so LETTERBOX: uniform downscale (aspect preserved) into the
+ // top-left of a black 640x640 canvas. A fit-to-square squash would smear faces on tall/wide
+ // frames past detectability (a 13:1 page compresses faces 13x on one axis); letterboxing keeps
+ // them undistorted, merely smaller.
+ const scale = YUNET_SIDE / Math.max(win.width, win.height)
+ const dw = Math.max(1, Math.round(win.width * scale))
+ const dh = Math.max(1, Math.round(win.height * scale))
+ const isWholeFrame = win.width === W && win.height === H
+ const pipeline = isWholeFrame ? srcSharp(src) : srcSharp(src).extract(win)
+ const { data } = await pipeline
+ .resize(dw, dh, { fit: 'fill' })
+ .extend({ top: 0, left: 0, right: YUNET_SIDE - dw, bottom: YUNET_SIDE - dh, background: '#000' })
+ .raw()
+ .toBuffer({ resolveWithObject: true })
+
+ // RGB(HWC, 0-255) -> BGR(CHW, float32, no normalization), as OpenCV's YuNet expects.
+ const side = YUNET_SIDE
+ const chw = new Float32Array(3 * side * side)
+ const plane = side * side
+ for (let i = 0, p = 0; i < data.length; i += 3, p++) {
+ chw[p] = data[i + 2] // B
+ chw[plane + p] = data[i + 1] // G
+ chw[2 * plane + p] = data[i] // R
+ }
+ const out = await model.session.run({ [model.inputName]: new ort.Tensor('float32', chw, [1, 3, side, side]) })
+
+ // Uniform inverse scale back to window coords, then offset to frame coords; boxes decoded in the
+ // letterbox padding scale past the window edge and get clamped away.
+ const sx = win.width / dw
+ const sy = win.height / dh
+ const cand: { b: Box; s: number }[] = []
+ for (const s of STRIDES) {
+ const cls = out[`cls_${s}`].data as Float32Array
+ const obj = out[`obj_${s}`].data as Float32Array
+ const bbox = out[`bbox_${s}`].data as Float32Array
+ const fw = Math.floor(side / s)
+ const fh = Math.floor(side / s)
+ for (let r = 0; r < fh; r++) {
+ for (let c = 0; c < fw; c++) {
+ const i = r * fw + c
+ const score = Math.sqrt(Math.max(0, cls[i]) * Math.max(0, obj[i]))
+ if (score < scoreMin) {
+ continue
+ }
+ const cx = (c + bbox[i * 4]) * s
+ const cy = (r + bbox[i * 4 + 1]) * s
+ const bw = Math.exp(bbox[i * 4 + 2]) * s
+ const bh = Math.exp(bbox[i * 4 + 3]) * s
+ const px = bw * PAD
+ const py = bh * PAD
+ const left = Math.max(0, Math.round((cx - bw / 2 - px) * sx) + win.left)
+ const top = Math.max(0, Math.round((cy - bh / 2 - py) * sy) + win.top)
+ const right = Math.min(W, Math.round((cx + bw / 2 + px) * sx) + win.left)
+ const bottom = Math.min(H, Math.round((cy + bh / 2 + py) * sy) + win.top)
+ if (right - left >= 2 && bottom - top >= 2) {
+ cand.push({ b: { left, top, width: right - left, height: bottom - top }, s: score })
+ }
+ }
+ }
+ }
+ return cand
+}
+
+export async function detectFacesYunet(
+ model: YunetModel,
+ src: Src,
+ W: number,
+ H: number,
+ opts: FaceOpts = {}
+): Promise<Box[]> {
+ const scoreMin = opts.scoreMin ?? SCORE_MIN
+ const cand: { b: Box; s: number }[] = []
+ for (const win of detectionWindows(W, H)) {
+ cand.push(...(await detectInWindow(model, src, W, H, win, scoreMin)))
+ }
+
+ // greedy NMS over all windows (overlap regions produce duplicates for the same face)
+ cand.sort((a, b) => b.s - a.s)
+ const keep: Box[] = []
+ for (const { b } of cand) {
+ if (!keep.some((k) => iou(k, b) > NMS_IOU)) {
+ keep.push(b)
+ }
+ }
+ return keep
+}
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/tsconfig.json b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/tsconfig.json
index fc7c1fdfb9e8..d7b09241a0b7 100644
--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/tsconfig.json
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/tsconfig.json
@@ -10,5 +10,5 @@
"allowImportingTsExtensions": true,
"types": ["node", "jest"]
},
- "include": ["src/**/*.ts"]
+ "include": ["src/**/*.ts", "dev/**/*.ts"]
}