:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(ai-research): preserve JSON-LD in ML mirror (#90243)
Robbie7db915f25f2c
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/metrics.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/metrics.tsindex b20ccadfec29..0d9d4c80d74c 100644--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/metrics.ts+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/metrics.ts@@ -33,6 +33,11 @@ export class MlMirrorMetrics {labelNames: ['impl'],})+ private static readonly mlJsonLdEvents = new Counter({+ name: 'recording_blob_ingestion_v2_ml_json_ld_events',+ help: 'JSON-LD custom replay events observed during ML mirror anonymization',+ })+private static readonly mlImagesCollected = new Counter({name: 'recording_blob_ingestion_v2_ml_images_collected',help: 'Images through the out-of-band scrub lane, by stage: collected (returned by the addon), deduped (suppressed by the cross-message cache), queued (handed to the producer), produced (delivery acked), produce_failed (delivery failed; refs un-marked for natural retry)',@@ -121,6 +126,12 @@ export class MlMirrorMetrics {this.mlAnonymizeFailed.labels(impl).inc()}+ public static incrementMlJsonLdEvents(count: number): void {+ if (count > 0) {+ this.mlJsonLdEvents.inc(count)+ }+ }+public static incrementMlImagesCollected(outcome: MlImageLaneStage, count: number): void {this.mlImagesCollected.labels(outcome).inc(count)}diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/ml-mirror-pipeline.test.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/ml-mirror-pipeline.test.tsindex d5d5d40214a2..9bf9c8d8c6b6 100644--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/ml-mirror-pipeline.test.ts+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/ml-mirror-pipeline.test.ts@@ -161,6 +161,27 @@ describe('ml-mirror-pipeline', () => {timestamp: now.toMillis(),data: { source: 5, id: 1, text: 'Hello SecretName', isChecked: false },},+ {+ type: 5,+ timestamp: now.plus({ milliseconds: 1 }).toMillis(),+ data: {+ tag: '$json_ld',+ payload: {+ '@context': 'https://schema.org',+ '@type': 'Product',+ name: 'Camera',+ email: '[email protected]',+ offers: {+ '@type': 'Offer',+ price: 100,+ seller: {+ '@type': 'Person',+ name: 'Example Viewer',+ },+ },+ },+ },+ },],},}),@@ -251,6 +272,21 @@ describe('ml-mirror-pipeline', () => {expect(windowId).toBe('window-1')// The Input event's text was scrubbed before it reached the recorder.expect(event.data.text).toBe('Hello **********')+ expect(recordedEvents()[1][1].data).toEqual({+ tag: '$json_ld',+ payload: {+ '@context': 'https://schema.org',+ '@type': 'Product',+ name: 'Camera',+ offers: {+ '@type': 'Offer',+ price: 100,+ seller: {+ '@type': 'Person',+ },+ },+ },+ })})it('drops sessions for a team that did not opt into AI training', async () => {diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/parse-and-anonymize-step.test.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/parse-and-anonymize-step.test.tsindex bec57e9b2d19..32d298d7236f 100644--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/parse-and-anonymize-step.test.ts+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/parse-and-anonymize-step.test.ts@@ -18,6 +18,16 @@ import {const compressWithGzip = promisify(gzip)const IMAGE_SOURCE_METRIC = 'recording_blob_ingestion_v2_ml_image_references_by_property'+const JSON_LD_EVENT_METRIC = 'recording_blob_ingestion_v2_ml_json_ld_events'++async function metricValue(name: string): Promise<number> {+ const metric = register.getSingleMetric(name)+ if (!metric) {+ return 0+ }+ const { values } = await metric.get()+ return values[0]?.value ?? 0+}async function imageSourceMetricValue(source: string, property: string, kind: string): Promise<number> {const metric = register.getSingleMetric(IMAGE_SOURCE_METRIC)@@ -92,6 +102,7 @@ describe('createParseAndAnonymizeMessageStep', () => {consoleLogCount: 1,consoleWarnCount: 2,consoleErrorCount: 3,+ jsonLdEventCount: 0,events: [{ ts: now, flags: 5 }],...metaOverrides,}),@@ -103,7 +114,8 @@ describe('createParseAndAnonymizeMessageStep', () => {})it('assembles a pre-serialized ParsedMessageData from the addon output', async () => {- addonSuccess()+ const jsonLdEventsBefore = await metricValue(JSON_LD_EVENT_METRIC)+ addonSuccess({ jsonLdEventCount: 2 })const result = await step({ message: kafkaMessage(), headers, team })expect(result.type).toBe(PipelineResultType.OK)@@ -120,6 +132,7 @@ describe('createParseAndAnonymizeMessageStep', () => {expect(parsed.snapshot_source).toBe('web')expect(parsed.snapshot_library).toBe('posthog-js')expect(parsed.metadata).toEqual({ partition: 3, topic: 'snapshots', rawSize: 2, offset: 42, timestamp: now })+ await expect(metricValue(JSON_LD_EVENT_METRIC)).resolves.toBe(jsonLdEventsBefore + 2)})it('normalizes a UUID session id before comparing against the header', async () => {@@ -253,6 +266,7 @@ describe('createParseAndAnonymizeMessageStep with image collection', () => {consoleLogCount: 0,consoleWarnCount: 0,consoleErrorCount: 0,+ jsonLdEventCount: 0,events: [{ ts: now, flags: 0 }],images: imageEntries,imageSources,@@ -362,6 +376,7 @@ describe('createParseAndAnonymizeMessageStep with url collection', () => {consoleLogCount: 0,consoleWarnCount: 0,consoleErrorCount: 0,+ jsonLdEventCount: 0,events: [],...(urls ? { urls } : {}),})diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/parse-and-anonymize-step.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/parse-and-anonymize-step.tsindex 76c038709fa4..4a0c95d27436 100644--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/parse-and-anonymize-step.ts+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/parse-and-anonymize-step.ts@@ -256,6 +256,8 @@ export function createParseAndAnonymizeMessageStep<T extends ParseMessageStepInpreturn dlq('distinct_id_header_body_mismatch')}+ MlMirrorMetrics.incrementMlJsonLdEvents(meta.jsonLdEventCount)+const parsedMessage: ParsedMessageData = {metadata: {partition: message.partition,diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/shared-fixtures.test.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/shared-fixtures.test.tsindex 41afd57d1039..efbec11243c0 100644--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/shared-fixtures.test.ts+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/shared-fixtures.test.ts@@ -37,11 +37,28 @@ interface MessageCase {message: Record<string, unknown[]>expected: Record<string, unknown>}+interface JsonLdContract {+ schemaVersion: 1+ typeSets: Array<{+ name: string+ types: string[]+ }>+ rejectedTypes: string[]+ cases: Array<{+ name: string+ input: unknown+ expected: unknown+ }>+}-function load<T>(name: string): T[] {+function loadDocument<T>(name: string): T {return parseJSON(fs.readFileSync(path.join(FIXTURE_DIR, name), 'utf8'))}+function load<T>(name: string): T[] {+ return loadDocument<T[]>(name)+}+let rustAddon: typeof import('@posthog/replay-anonymizer') | null = nulltry {rustAddon = require('@posthog/replay-anonymizer')@@ -56,6 +73,7 @@ const describeAddon = rustAddon ? describe : describe.skipdescribeAddon('native rust addon matches the shared fixtures', () => {const eventCases = load<EventCase>('events.json')const messageCases = load<MessageCase>('messages.json')+ const jsonLdContract = loadDocument<JsonLdContract>('json-ld-sanitization-v1.json')const TS0 = 1_700_000_000_000@@ -96,6 +114,10 @@ describeAddon('native rust addon matches the shared fixtures', () => {.map((l) => parseJSON(l))}+ test('uses the supported JSON-LD contract version', () => {+ expect(jsonLdContract.schemaVersion).toBe(1)+ })+describe('events', () => {test.each(eventCases.map((c) => [c.name, c] as const))('event: %s', async (_name, c) => {// --runInBand is required to ensure cases are sequential@@ -106,6 +128,44 @@ describeAddon('native rust addon matches the shared fixtures', () => {})})+ describe('JSON-LD contract', () => {+ test.each(jsonLdContract.cases.map((c) => [c.name, c] as const))('JSON-LD: %s', async (_name, c) => {+ rustAddon!.initAnonymizer({ text: [], url: [] })+ const event = { type: 5, data: { tag: '$json_ld', payload: c.input } }+ const expectedData = c.expected ? { tag: '$json_ld', payload: c.expected } : { tag: '$json_ld' }+ const result = await rustAddon!.anonymizeKafkaPayload(payloadOf('w', [event]))+ expect(result.failed).toBe(false)+ expect(parseLines(result.lines!)).toEqual(expectedLines('w', [{ type: 5, data: expectedData }]))+ })++ test.each(jsonLdContract.typeSets.map((typeSet) => [typeSet.name, typeSet] as const))(+ 'JSON-LD types: %s',+ async (_name, typeSet) => {+ rustAddon!.initAnonymizer({ text: [], url: [] })+ for (const type of typeSet.types) {+ const payload = { '@context': 'https://schema.org', '@type': type }+ const event = { type: 5, data: { tag: '$json_ld', payload } }+ const result = await rustAddon!.anonymizeKafkaPayload(payloadOf('w', [event]))+ expect(result.failed).toBe(false)+ expect(parseLines(result.lines!)).toEqual(+ expectedLines('w', [{ type: 5, data: { tag: '$json_ld', payload } }])+ )+ }+ }+ )++ test('JSON-LD rejected types', async () => {+ rustAddon!.initAnonymizer({ text: [], url: [] })+ for (const type of jsonLdContract.rejectedTypes) {+ const payload = { '@context': 'https://schema.org', '@type': type }+ const event = { type: 5, data: { tag: '$json_ld', payload } }+ const result = await rustAddon!.anonymizeKafkaPayload(payloadOf('w', [event]))+ expect(result.failed).toBe(false)+ expect(parseLines(result.lines!)).toEqual(expectedLines('w', [{ type: 5, data: { tag: '$json_ld' } }]))+ }+ })+ })+test.each(messageCases.map((c) => [c.name, c] as const))('message: %s', async (_name, c) => {rustAddon!.initAnonymizer(c.allow)for (const [windowId, events] of Object.entries(c.message)) {diff --git a/rust/Cargo.lock b/rust/Cargo.lockindex 53943a4b38fe..361141cf3b8a 100644--- a/rust/Cargo.lock+++ b/rust/Cargo.lock@@ -9301,7 +9301,7 @@ dependencies = [[[package]]name = "posthog-replay-anonymizer"-version = "0.4.7"+version = "0.4.8"dependencies = ["ahash 0.8.12","anyhow",diff --git a/rust/replay-anonymizer-node/src/index.ts b/rust/replay-anonymizer-node/src/index.tsindex 85c80174e3cd..8a550342f30b 100644--- a/rust/replay-anonymizer-node/src/index.ts+++ b/rust/replay-anonymizer-node/src/index.ts@@ -65,6 +65,7 @@ export interface AnonymizeMeta {consoleLogCount: numberconsoleWarnCount: numberconsoleErrorCount: number+ jsonLdEventCount: numberevents: AnonymizeEventMeta[]/** Collected original images (hash-sorted); present only when the collection lane was enabled and images were collected. */images?: AnonymizeImageEntry[]diff --git a/rust/replay-anonymizer/Cargo.toml b/rust/replay-anonymizer/Cargo.tomlindex fee40e209e01..eb6b9f4f3ba8 100644--- a/rust/replay-anonymizer/Cargo.toml+++ b/rust/replay-anonymizer/Cargo.toml@@ -1,6 +1,6 @@[package]name = "posthog-replay-anonymizer"-version = "0.4.7"+version = "0.4.8"edition = "2021"description = "PII scrubber for rrweb session-replay events: text/URL redaction, native image blur, and canvas/cv neutralization"license = "MIT"diff --git a/rust/replay-anonymizer/src/event.rs b/rust/replay-anonymizer/src/event.rsindex 7e927e1d1694..413205581d69 100644--- a/rust/replay-anonymizer/src/event.rs+++ b/rust/replay-anonymizer/src/event.rs@@ -16,6 +16,7 @@ use crate::json::{as_array_mut, as_object, as_object_mut, as_small_uint, as_str, key, parse_untrusted,reject_if_too_deep, string_value,};+use crate::json_ld::scrub_json_ld_payload;use crate::text::scrub_text;use crate::url::scrub_url;use crate::value::{scrub_console_plugin, scrub_generic_field, scrub_network_plugin};@@ -37,6 +38,7 @@ pub const SOURCE_ADOPTED_STYLESHEET: u8 = 15;pub const NETWORK_PLUGIN: &str = "rrweb/network@1";pub const CONSOLE_PLUGIN: &str = "rrweb/console@1";+pub(crate) const JSON_LD_EVENT_TAG: &str = "$json_ld";/// Panic backstop for the anyhow-based entry points (see [`crate::unwind`]).fn contain_panics<T>(f: impl FnOnce() -> Result<T>) -> Result<T> {@@ -240,6 +242,9 @@ pub fn route_data(}}Some(TYPE_CUSTOM) => match as_object_mut(data) {+ Some(data) if data.get("tag").and_then(as_str) == Some(JSON_LD_EVENT_TAG) => {+ Ok(scrub_json_ld_payload(data))+ }Some(data) => Ok(scrub_generic_field(ctx, data, "payload")),None => Ok(false),},diff --git a/rust/replay-anonymizer/src/json_ld.rs b/rust/replay-anonymizer/src/json_ld.rsnew file mode 100644index 000000000000..5cfc047b8f04--- /dev/null+++ b/rust/replay-anonymizer/src/json_ld.rs@@ -0,0 +1,606 @@+use std::borrow::Cow;+use std::collections::HashSet;++use simd_json::borrowed::{Object, Value};+use simd_json::prelude::Writable;+use simd_json::StaticNode;++use crate::json::{as_array, as_object, as_str, key};++// Keep this policy aligned with posthog-js/packages/browser/src/extensions/replay/external/json-ld.ts.+const MAX_JSON_LD_LENGTH: usize = 100_000;+const MAX_JSON_LD_OUTPUT_LENGTH: usize = 20_000;+const MAX_JSON_LD_TYPE_LENGTH: usize = 100;+const MAX_JSON_LD_TYPES: usize = 20;+const MAX_JSON_LD_NODES: usize = 2_048;+const SCHEMA_CONTEXT: &str = "https://schema.org";+const TYPE_INDEPENDENT_LEAF_PROPERTIES: &str =+ "actionStatus availability bestRating contentRating encodingFormat eventAttendanceMode eventStatus highPrice inLanguage isAccessibleForFree isFamilyFriendly itemCondition itemListOrder lowPrice maximumAttendeeCapacity nonprofitStatus numberOfItems offerCount position price priceCurrency priceValidUntil publicAccess ratingCount ratingValue reviewCount smokingAllowed worstRating";+const ACTION_TYPES: &str =+ "Action BorrowAction ReadAction SearchAction SeekToAction SolveMathAction WatchAction";+const ORGANIZATION_TYPES: &str =+ "AutoDealer Bakery BarOrPub CafeOrCoffeeShop CollegeOrUniversity Corporation DaySpa Dentist EducationalOrganization Electrician FoodEstablishment GovernmentOrganization HealthClub Hotel LegalService Library LibrarySystem LocalBusiness Locksmith LodgingBusiness MedicalBusiness NGO OnlineStore Organization PerformingGroup Pharmacy Physician Plumber RealEstateAgent Restaurant School SportsOrganization Store";+const PLACE_TYPES: &str = "Accommodation AdministrativeArea Country Place State";+const CREATIVE_WORK_TYPES: &str =+ "3DModel AboutPage Answer Article AudioObject Blog BlogPosting Book Clip CollectionPage Comment ContactPage Course CreativeWorkSeason CreativeWorkSeries DataCatalog DataDownload DataFeed Dataset DiscussionForumPosting Episode FAQPage Game HowTo HowToDirection HowToSection HowToStep HowToTip ImageObject LearningResource MediaObject Message MobileApplication Movie MusicPlaylist MusicRecording NewsArticle Photograph PodcastEpisode PodcastSeries ProfilePage QAPage Question Quiz Recipe Review ScholarlyArticle SearchResultsPage SiteNavigationElement SocialMediaPosting SoftwareApplication TVEpisode TVSeries TechArticle VacationRental VideoGame VideoObject WebApplication WebPage WebPageElement WebSite";+const EVENT_TYPES: &str =+ "BroadcastEvent BusinessEvent EducationEvent Festival MusicEvent SportsEvent TheaterEvent";+const PRODUCT_TYPES: &str = "Car IndividualProduct ProductGroup ProductModel";++#[derive(Clone, Copy)]+enum PropertyRule {+ Scalar(&'static str),+ Entity(&'static str, &'static str),+}++struct SanitizationBudget {+ remaining_nodes: usize,+ exceeded: bool,+}++impl SanitizationBudget {+ fn take_node(&mut self) -> bool {+ if self.remaining_nodes == 0 {+ self.exceeded = true;+ return false;+ }+ self.remaining_nodes -= 1;+ true+ }+}++const AGGREGATE_OFFER_RULES: &[PropertyRule] = &[PropertyRule::Entity("offers", "Offer")];+const BRAND_RULES: &[PropertyRule] = &[PropertyRule::Scalar("name")];+const BREADCRUMB_LIST_RULES: &[PropertyRule] =+ &[PropertyRule::Entity("itemListElement", "ListItem")];+const CREATIVE_WORK_RULES: &[PropertyRule] = &[+ PropertyRule::Scalar("genre"),+ PropertyRule::Scalar("dateCreated"),+ PropertyRule::Scalar("dateModified"),+ PropertyRule::Scalar("datePublished"),+ PropertyRule::Scalar("expires"),+ PropertyRule::Scalar("learningResourceType"),+ PropertyRule::Scalar("educationalLevel"),+ PropertyRule::Scalar("educationalUse"),+ PropertyRule::Scalar("interactivityType"),+ PropertyRule::Entity("aggregateRating", "AggregateRating"),+ PropertyRule::Entity("potentialAction", ACTION_TYPES),+ PropertyRule::Entity("publisher", ORGANIZATION_TYPES),+];+const EVENT_RULES: &[PropertyRule] = &[+ PropertyRule::Scalar("startDate"),+ PropertyRule::Scalar("endDate"),+ PropertyRule::Scalar("previousStartDate"),+ PropertyRule::Entity("aggregateRating", "AggregateRating"),+ PropertyRule::Entity("offers", "AggregateOffer Offer"),+];+const ITEM_LIST_RULES: &[PropertyRule] = &[PropertyRule::Entity("itemListElement", "ListItem")];+const LIST_ITEM_RULES: &[PropertyRule] = &[PropertyRule::Entity("item", "")];+const OFFER_RULES: &[PropertyRule] = &[PropertyRule::Entity("seller", ORGANIZATION_TYPES)];+const ORGANIZATION_RULES: &[PropertyRule] = &[+ PropertyRule::Scalar("name"),+ PropertyRule::Scalar("legalName"),+ PropertyRule::Scalar("foundingDate"),+ PropertyRule::Scalar("dissolutionDate"),+ PropertyRule::Entity("aggregateRating", "AggregateRating"),+ PropertyRule::Entity("brand", "Brand"),+];+const PLACE_RULES: &[PropertyRule] = &[PropertyRule::Entity("aggregateRating", "AggregateRating")];+const PRODUCT_RULES: &[PropertyRule] = &[+ PropertyRule::Scalar("name"),+ PropertyRule::Scalar("sku"),+ PropertyRule::Scalar("mpn"),+ PropertyRule::Scalar("gtin"),+ PropertyRule::Scalar("gtin8"),+ PropertyRule::Scalar("gtin12"),+ PropertyRule::Scalar("gtin13"),+ PropertyRule::Scalar("gtin14"),+ PropertyRule::Scalar("productID"),+ PropertyRule::Scalar("productGroupID"),+ PropertyRule::Scalar("asin"),+ PropertyRule::Scalar("model"),+ PropertyRule::Scalar("category"),+ PropertyRule::Scalar("color"),+ PropertyRule::Scalar("material"),+ PropertyRule::Scalar("pattern"),+ PropertyRule::Scalar("size"),+ PropertyRule::Scalar("productionDate"),+ PropertyRule::Scalar("releaseDate"),+ PropertyRule::Entity("brand", "Brand Organization"),+ PropertyRule::Entity("manufacturer", ORGANIZATION_TYPES),+ PropertyRule::Entity("offers", "Offer AggregateOffer"),+ PropertyRule::Entity("aggregateRating", "AggregateRating"),+];+const SERVICE_RULES: &[PropertyRule] = &[+ PropertyRule::Scalar("name"),+ PropertyRule::Scalar("serviceType"),+ PropertyRule::Scalar("category"),+ PropertyRule::Entity("provider", ORGANIZATION_TYPES),+ PropertyRule::Entity("areaServed", PLACE_TYPES),+ PropertyRule::Entity("offers", "AggregateOffer Offer"),+ PropertyRule::Entity("aggregateRating", "AggregateRating"),+];+const OFFER_CATALOG_RULES: &[PropertyRule] = &[+ PropertyRule::Scalar("name"),+ PropertyRule::Entity("itemListElement", ""),+];++fn listed(types: &str, entity_type: &str) -> bool {+ types+ .split_ascii_whitespace()+ .any(|candidate| candidate == entity_type)+}++fn entity_rules(entity_type: &str) -> Option<&'static [PropertyRule]> {+ match entity_type {+ "AggregateOffer" => Some(AGGREGATE_OFFER_RULES),+ "Brand" => Some(BRAND_RULES),+ "BreadcrumbList" => Some(BREADCRUMB_LIST_RULES),+ "CreativeWork" => Some(CREATIVE_WORK_RULES),+ "Event" => Some(EVENT_RULES),+ "ItemList" => Some(ITEM_LIST_RULES),+ "ListItem" => Some(LIST_ITEM_RULES),+ "Offer" => Some(OFFER_RULES),+ "Organization" => Some(ORGANIZATION_RULES),+ "Place" => Some(PLACE_RULES),+ "Product" => Some(PRODUCT_RULES),+ "Service" => Some(SERVICE_RULES),+ "OfferCatalog" => Some(OFFER_CATALOG_RULES),+ _ if listed(CREATIVE_WORK_TYPES, entity_type) => Some(CREATIVE_WORK_RULES),+ _ if listed(EVENT_TYPES, entity_type) => Some(EVENT_RULES),+ _ if listed(ORGANIZATION_TYPES, entity_type) => Some(ORGANIZATION_RULES),+ _ if listed(PLACE_TYPES, entity_type) => Some(PLACE_RULES),+ _ if listed(PRODUCT_TYPES, entity_type) => Some(PRODUCT_RULES),+ _ => None,+ }+}++fn is_scalar(value: &Value<'_>) -> bool {+ matches!(+ value,+ Value::String(_)+ | Value::Static(+ StaticNode::Null+ | StaticNode::Bool(_)+ | StaticNode::I64(_)+ | StaticNode::U64(_)+ | StaticNode::F64(_)+ )+ )+}++fn sanitize_scalar<'v>(value: &Value<'v>) -> Option<Value<'v>> {+ if is_scalar(value) || as_array(value).is_some_and(|items| items.iter().all(is_scalar)) {+ Some(value.clone())+ } else {+ None+ }+}++fn has_uri_scheme(value: &str) -> bool {+ let Some(separator_index) = value.find(':') else {+ return false;+ };+ let mut scheme = value[..separator_index].chars();+ scheme+ .next()+ .is_some_and(|first| first.is_ascii_alphabetic())+ && scheme.all(|character| {+ character.is_ascii_alphanumeric() || matches!(character, '+' | '.' | '-')+ })+}++fn sanitize_id<'v>(value: &Value<'_>) -> Option<Value<'v>> {+ let id = as_str(value)?.trim();+ let hash_index = id.find('#');+ let fragment = hash_index.map_or(id, |index| &id[index + 1..]);+ if fragment.is_empty()+ || (hash_index.is_none() && (has_uri_scheme(id) || id.contains('/') || id.contains('?')))+ {+ return None;+ }+ Some(owned_string(fragment.to_string()))+}++fn normalize_entity_type(entity_type: &str) -> &str {+ entity_type+ .strip_prefix("https://schema.org/")+ .or_else(|| entity_type.strip_prefix("http://schema.org/"))+ .unwrap_or(entity_type)+}++// Unknown types keep their name in the output, so the shape rule keeps free text such as an email out of the `@type` slot.+fn is_schema_term(entity_type: &str) -> bool {+ entity_type.bytes().all(|byte| byte.is_ascii_alphanumeric())+ && entity_type.bytes().any(|byte| byte.is_ascii_alphabetic())+}++fn entity_types(value: Option<&Value<'_>>) -> Vec<String> {+ let values: Vec<&str> = match value {+ Some(Value::String(value)) => vec![value.as_ref()],+ Some(Value::Array(values)) => values.iter().filter_map(as_str).collect(),+ _ => Vec::new(),+ };+ let mut seen = HashSet::new();+ values+ .into_iter()+ .map(normalize_entity_type)+ .filter(|entity_type| {+ is_schema_term(entity_type)+ && entity_type.encode_utf16().count() <= MAX_JSON_LD_TYPE_LENGTH+ })+ .filter(|entity_type| seen.insert(*entity_type))+ .take(MAX_JSON_LD_TYPES)+ .map(str::to_string)+ .collect()+}++fn owned_string<'v>(value: String) -> Value<'v> {+ Value::String(Cow::Owned(value))+}++fn sanitize_entity_value<'v>(+ value: &Value<'v>,+ allowed_types: &str,+ budget: &mut SanitizationBudget,+) -> Option<Value<'v>> {+ if let Some(items) = as_array(value) {+ let sanitized: Vec<Value<'v>> = items+ .iter()+ .filter_map(|item| sanitize_entity_value(item, allowed_types, budget))+ .collect();+ return (!sanitized.is_empty()).then_some(Value::Array(Box::new(sanitized)));+ }+ sanitize_entity(value, Some(allowed_types), budget)+}++fn sanitize_entity<'v>(+ value: &Value<'v>,+ allowed_types: Option<&str>,+ budget: &mut SanitizationBudget,+) -> Option<Value<'v>> {+ let object = as_object(value)?;+ if !budget.take_node() {+ return None;+ }+ let type_value = object.get("@type");+ let types = entity_types(type_value);++ let mut result = Object::default();+ if !types.is_empty() {+ let sanitized_type = if matches!(type_value, Some(Value::String(_))) {+ owned_string(types[0].clone())+ } else {+ Value::Array(Box::new(types.iter().cloned().map(owned_string).collect()))+ };+ result.insert(key("@type"), sanitized_type);+ }++ if let Some(id) = object.get("@id").and_then(sanitize_id) {+ result.insert(key("@id"), id);+ }+ for property in TYPE_INDEPENDENT_LEAF_PROPERTIES.split_ascii_whitespace() {+ if let Some(value) = object.get(property).and_then(sanitize_scalar) {+ result.insert(Cow::Borrowed(property), value);+ }+ }++ for entity_type in &types {+ if allowed_types.is_some_and(|allowed| !allowed.is_empty() && !listed(allowed, entity_type))+ {+ continue;+ }+ let Some(rules) = entity_rules(entity_type) else {+ continue;+ };+ for rule in rules {+ match *rule {+ PropertyRule::Scalar(property) => {+ if let Some(value) = object.get(property).and_then(sanitize_scalar) {+ result.insert(Cow::Borrowed(property), value);+ }+ }+ PropertyRule::Entity(property, allowed_types) => {+ if let Some(value) = object+ .get(property)+ .and_then(|value| sanitize_entity_value(value, allowed_types, budget))+ {+ result.insert(Cow::Borrowed(property), value);+ }+ }+ }+ }+ }++ if let Some(graph) = object+ .get("@graph")+ .and_then(|value| sanitize_entity_value(value, "", budget))+ {+ result.insert(key("@graph"), graph);+ }++ (!result.is_empty()).then_some(Value::Object(Box::new(result)))+}++fn is_schema_context(value: &Value<'_>) -> bool {+ matches!(+ as_str(value),+ Some(+ "https://schema.org"+ | "https://schema.org/"+ | "http://schema.org"+ | "http://schema.org/"+ )+ )+}++fn sanitize_root<'v>(value: &Value<'v>, budget: &mut SanitizationBudget) -> Option<Value<'v>> {+ let object = as_object(value)?;+ if !object.get("@context").is_some_and(is_schema_context) {+ return None;+ }++ let Value::Object(mut entity) = sanitize_entity(value, None, budget)? else {+ return None;+ };+ entity.insert(key("@context"), owned_string(SCHEMA_CONTEXT.to_string()));+ Some(Value::Object(entity))+}++fn sanitize_json_ld<'v>(value: &Value<'v>) -> Option<Value<'v>> {+ if value.encode().encode_utf16().count() > MAX_JSON_LD_LENGTH {+ return None;+ }++ let mut budget = SanitizationBudget {+ remaining_nodes: MAX_JSON_LD_NODES,+ exceeded: false,+ };+ let sanitized = if let Some(roots) = as_array(value) {+ if roots.is_empty() {+ return None;+ }+ let roots: Option<Vec<Value<'v>>> = roots+ .iter()+ .map(|root| sanitize_root(root, &mut budget))+ .collect();+ Value::Array(Box::new(roots?))+ } else {+ sanitize_root(value, &mut budget)?+ };++ if budget.exceeded {+ return None;+ }++ (sanitized.encode().encode_utf16().count() <= MAX_JSON_LD_OUTPUT_LENGTH).then_some(sanitized)+}++pub(crate) fn scrub_json_ld_payload<'v>(data: &mut Object<'v>) -> bool {+ let sanitized = data.get("payload").and_then(sanitize_json_ld);+ match sanitized {+ Some(sanitized) if data.get("payload") == Some(&sanitized) => false,+ Some(sanitized) => {+ data.insert(key("payload"), sanitized);+ true+ }+ None => data.remove("payload").is_some(),+ }+}++#[cfg(test)]+mod tests {+ use serde_json::json;++ use super::*;+ use crate::json::{as_object_mut, parse_untrusted};++ fn scrub(payload: serde_json::Value) -> serde_json::Value {+ let mut bytes =+ serde_json::to_vec(&json!({ "tag": "$json_ld", "payload": payload })).unwrap();+ let mut data = parse_untrusted(&mut bytes).unwrap();+ scrub_json_ld_payload(as_object_mut(&mut data).unwrap());+ serde_json::from_str(&data.encode()).unwrap()+ }++ #[test]+ fn matches_posthog_js_json_ld_sanitization() {+ let contract: serde_json::Value = serde_json::from_str(include_str!(+ "../tests/fixtures/json-ld-sanitization-v1.json"+ ))+ .unwrap();+ assert_eq!(contract["schemaVersion"], 1);+ assert_eq!(+ contract["limits"]["typePattern"], "^[A-Za-z0-9]*[A-Za-z][A-Za-z0-9]*$",+ "is_schema_term mirrors the published type pattern"+ );++ // The server has no DOM, so every case runs as if each `@id` fragment is captured.+ for case in contract["cases"].as_array().unwrap() {+ let expected = match &case["expected"] {+ serde_json::Value::Null => json!({ "tag": "$json_ld" }),+ expected => json!({ "tag": "$json_ld", "payload": expected }),+ };+ assert_eq!(scrub(case["input"].clone()), expected, "{}", case["name"]);+ }++ for type_set in contract["typeSets"].as_array().unwrap() {+ for entity_type in type_set["types"].as_array().unwrap() {+ let input = json!({+ "@context": "https://schema.org",+ "@type": entity_type,+ });+ assert_eq!(+ scrub(input.clone()),+ json!({ "tag": "$json_ld", "payload": input }),+ "{}: {}",+ type_set["name"],+ entity_type+ );+ }+ }++ for entity_type in contract["rejectedTypes"].as_array().unwrap() {+ let input = json!({+ "@context": "https://schema.org",+ "@type": entity_type,+ });+ assert_eq!(scrub(input), json!({ "tag": "$json_ld" }), "{entity_type}");+ }+ }++ #[test]+ fn keeps_nested_entity_arrays() {+ let input = json!({+ "@context": "https://schema.org",+ "@type": "Product",+ "offers": [+ [{ "@type": "Offer", "price": 100, "email": "[email protected]" }],+ "private"+ ]+ });+ assert_eq!(+ scrub(input),+ json!({+ "tag": "$json_ld",+ "payload": {+ "@context": "https://schema.org",+ "@type": "Product",+ "offers": [[{ "@type": "Offer", "price": 100 }]]+ }+ })+ );+ }++ #[test]+ fn enforces_posthog_js_json_ld_limits() {+ let contract: serde_json::Value = serde_json::from_str(include_str!(+ "../tests/fixtures/json-ld-sanitization-v1.json"+ ))+ .unwrap();+ let max_type_length = contract["limits"]["maxTypeLength"].as_u64().unwrap() as usize;+ let max_types = contract["limits"]["maxTypes"].as_u64().unwrap() as usize;+ let max_nodes = contract["limits"]["maxNodes"].as_u64().unwrap() as usize;+ let max_source_length = contract["limits"]["maxSourceLength"].as_u64().unwrap() as usize;+ let max_payload_length = contract["limits"]["maxPayloadLength"].as_u64().unwrap() as usize;++ let root = |entity_type: String, name: Option<String>| {+ json!({+ "@context": "https://schema.org",+ "@type": entity_type,+ "name": name+ })+ };+ let without_name = |value: serde_json::Value| {+ let mut value = value;+ value.as_object_mut().unwrap().remove("name");+ value+ };++ let type_at_limit = without_name(root("T".repeat(max_type_length), None));+ assert_eq!(+ scrub(type_at_limit.clone()),+ json!({ "tag": "$json_ld", "payload": type_at_limit })+ );+ assert_eq!(+ scrub(without_name(root("T".repeat(max_type_length + 1), None))),+ json!({ "tag": "$json_ld" })+ );++ let types: Vec<String> = (0..max_types).map(|index| format!("Type{index}")).collect();+ let type_input = json!({+ "@context": "https://schema.org",+ "@type": types,+ });+ assert_eq!(+ scrub(type_input.clone()),+ json!({ "tag": "$json_ld", "payload": type_input })+ );+ let mut types_over_limit = types.clone();+ types_over_limit.push("TypeOverLimit".to_string());+ assert_eq!(+ scrub(json!({+ "@context": "https://schema.org",+ "@type": types_over_limit,+ })),+ json!({+ "tag": "$json_ld",+ "payload": {+ "@context": "https://schema.org",+ "@type": types,+ }+ })+ );++ let root_with_graph = |graph_size: usize| {+ json!({+ "@context": "https://schema.org",+ "@type": "Thing",+ "@graph": vec![json!({}); graph_size],+ })+ };+ assert_eq!(+ scrub(root_with_graph(max_nodes - 1)),+ json!({+ "tag": "$json_ld",+ "payload": {+ "@context": "https://schema.org",+ "@type": "Thing",+ }+ })+ );+ assert_eq!(+ scrub(root_with_graph(max_nodes)),+ json!({ "tag": "$json_ld" })+ );++ let empty_source = json!({+ "@context": "https://schema.org",+ "@type": "Product",+ "private": ""+ });+ let empty_source_length = serde_json::to_string(&empty_source)+ .unwrap()+ .encode_utf16()+ .count();+ let source_at_limit = json!({+ "@context": "https://schema.org",+ "@type": "Product",+ "private": "x".repeat(max_source_length - empty_source_length)+ });+ assert_eq!(+ scrub(source_at_limit),+ json!({+ "tag": "$json_ld",+ "payload": { "@context": "https://schema.org", "@type": "Product" }+ })+ );+ let source_over_limit = json!({+ "@context": "https://schema.org",+ "@type": "Product",+ "private": "x".repeat(max_source_length - empty_source_length + 1)+ });+ assert_eq!(scrub(source_over_limit), json!({ "tag": "$json_ld" }));++ let empty_payload = root("Product".to_string(), Some(String::new()));+ let empty_payload_length = serde_json::to_string(&empty_payload)+ .unwrap()+ .encode_utf16()+ .count();+ let payload_at_limit = root(+ "Product".to_string(),+ Some("x".repeat(max_payload_length - empty_payload_length)),+ );+ assert_eq!(+ scrub(payload_at_limit.clone()),+ json!({ "tag": "$json_ld", "payload": payload_at_limit })+ );+ assert_eq!(+ scrub(root(+ "Product".to_string(),+ Some("x".repeat(max_payload_length - empty_payload_length + 1))+ )),+ json!({ "tag": "$json_ld" })+ );+ }+}diff --git a/rust/replay-anonymizer/src/lib.rs b/rust/replay-anonymizer/src/lib.rsindex 2183c3368ede..c2f7aa2f5a3b 100644--- a/rust/replay-anonymizer/src/lib.rs+++ b/rust/replay-anonymizer/src/lib.rs@@ -48,6 +48,7 @@ pub mod event;pub mod images;#[doc(hidden)]pub mod json;+mod json_ld;#[doc(hidden)]pub mod scan;pub mod snapshot;diff --git a/rust/replay-anonymizer/src/snapshot.rs b/rust/replay-anonymizer/src/snapshot.rsindex 6946dfca8237..79a0468286d3 100644--- a/rust/replay-anonymizer/src/snapshot.rs+++ b/rust/replay-anonymizer/src/snapshot.rs@@ -30,8 +30,8 @@ use crate::allow_lists::AllowLists;use crate::collect::{CollectedImage, ImageCollection};use crate::context::{Ctx, ImageSourceCount};use crate::event::{- route_data, route_event, SOURCE_ADOPTED_STYLESHEET, SOURCE_CANVAS_MUTATION, SOURCE_INPUT,- SOURCE_MUTATION, SOURCE_STYLESHEET_RULE, SOURCE_STYLE_DECLARATION, TYPE_CUSTOM,+ route_data, route_event, JSON_LD_EVENT_TAG, SOURCE_ADOPTED_STYLESHEET, SOURCE_CANVAS_MUTATION,+ SOURCE_INPUT, SOURCE_MUTATION, SOURCE_STYLESHEET_RULE, SOURCE_STYLE_DECLARATION, TYPE_CUSTOM,TYPE_FULL_SNAPSHOT, TYPE_INCREMENTAL, TYPE_META, TYPE_PLUGIN,};use crate::images::ImagePolicy;@@ -165,6 +165,7 @@ pub struct SnapshotMeta {pub console_log_count: u32,pub console_warn_count: u32,pub console_error_count: u32,+ pub json_ld_event_count: u32,pub events: Vec<EventMeta>,/// Collected original images (hash-sorted); non-empty only on the image-collection lane.#[serde(skip_serializing_if = "Vec::is_empty")]@@ -886,6 +887,7 @@ struct Sink {line_starts: Vec<usize>,events: Vec<EventMeta>,console: [u32; 3], // info, warn, error+ json_ld_events: u32,/// simd-json scratch reused across the per-event parses.buffers: simd_json::Buffers,/// Whether an in-place parse has consumed a span yet — the tree fallback is only sound while@@ -905,6 +907,7 @@ impl Sink {line_starts: Vec::new(),events: Vec::new(),console: [0; 3],+ json_ld_events: 0,buffers: simd_json::Buffers::default(),mutated: false,scratch_budget: SCRATCH_BUDGET,@@ -984,6 +987,7 @@ fn finish(console_log_count: sink.console[0],console_warn_count: sink.console[1],console_error_count: sink.console[2],+ json_ld_event_count: sink.json_ld_events,events: sink.events,// The collector lives on the Ctx, not the Sink; the entry point packs it in.images: Vec::new(),@@ -1420,6 +1424,12 @@ fn push_meta_from_data(ty: Option<u8>, ts: f64, data: Option<&Value<'_>>, sink:href,});+ if ty == Some(TYPE_CUSTOM)+ && dobj.and_then(|data| data.get("tag")).and_then(as_str) == Some(JSON_LD_EVENT_TAG)+ {+ sink.json_ld_events += 1;+ }+// rrweb/console@1 counts by level (mirrors `session-console-log-recorder.ts` safeLevel).if ty == Some(TYPE_PLUGIN) {if let Some(d) = dobj {diff --git a/rust/replay-anonymizer/tests/fixtures/json-ld-sanitization-v1.json b/rust/replay-anonymizer/tests/fixtures/json-ld-sanitization-v1.jsonnew file mode 100644index 000000000000..2a7fb83f0095--- /dev/null+++ b/rust/replay-anonymizer/tests/fixtures/json-ld-sanitization-v1.json@@ -0,0 +1,810 @@+{+ "schemaVersion": 1,+ "limits": {+ "maxTypeLength": 100,+ "typePattern": "^[A-Za-z0-9]*[A-Za-z][A-Za-z0-9]*$",+ "maxTypes": 20,+ "maxNodes": 2048,+ "maxSourceLength": 100000,+ "maxPayloadLength": 20000+ },+ "typeSets": [+ {+ "name": "Google-listed type",+ "types": [+ "3DModel",+ "Accommodation",+ "Action",+ "AdministrativeArea",+ "AggregateOffer",+ "AggregateRating",+ "AlignmentObject",+ "Answer",+ "Article",+ "BedDetails",+ "Blog",+ "BlogPosting",+ "Book",+ "BorrowAction",+ "Brand",+ "BreadcrumbList",+ "BroadcastEvent",+ "Car",+ "Certification",+ "Clip",+ "Comment",+ "ContactPoint",+ "Country",+ "Course",+ "CreativeWork",+ "CreativeWorkSeason",+ "CreativeWorkSeries",+ "CreditCard",+ "DataCatalog",+ "DataDownload",+ "DataFeed",+ "Dataset",+ "DaySpa",+ "DefinedRegion",+ "DiscussionForumPosting",+ "EducationalOccupationalCredential",+ "Electrician",+ "EmployerAggregateRating",+ "EntryPoint",+ "Episode",+ "Event",+ "Game",+ "GeoCoordinates",+ "GeoShape",+ "HealthClub",+ "Hotel",+ "HowTo",+ "HowToDirection",+ "HowToSection",+ "HowToStep",+ "HowToTip",+ "ImageObject",+ "InteractionCounter",+ "ItemList",+ "JobPosting",+ "LearningResource",+ "Library",+ "LibrarySystem",+ "ListItem",+ "LocalBusiness",+ "LocationFeatureSpecification",+ "Locksmith",+ "LodgingBusiness",+ "MathSolver",+ "MediaObject",+ "MemberProgram",+ "MemberProgramTier",+ "MerchantReturnPolicy",+ "MerchantReturnPolicySeasonalOverride",+ "Message",+ "MobileApplication",+ "MonetaryAmount",+ "Movie",+ "MusicPlaylist",+ "MusicRecording",+ "NewsArticle",+ "NutritionInformation",+ "OccupationalExperienceRequirements",+ "Offer",+ "OfferShippingDetails",+ "OnlineStore",+ "OpeningHoursSpecification",+ "Organization",+ "PeopleAudience",+ "PerformingGroup",+ "Person",+ "Pharmacy",+ "Place",+ "Plumber",+ "PostalAddress",+ "PriceSpecification",+ "Product",+ "ProductGroup",+ "ProfilePage",+ "PropertyValue",+ "QAPage",+ "QuantitativeValue",+ "Question",+ "Quiz",+ "Rating",+ "ReadAction",+ "Recipe",+ "Restaurant",+ "Review",+ "SeekToAction",+ "ServicePeriod",+ "ShippingConditions",+ "ShippingDeliveryTime",+ "ShippingRateSettings",+ "ShippingService",+ "SocialMediaPosting",+ "SoftwareApplication",+ "SolveMathAction",+ "SpeakableSpecification",+ "State",+ "Store",+ "Thing",+ "UnitPriceSpecification",+ "VacationRental",+ "VideoGame",+ "VideoObject",+ "WatchAction",+ "WebApplication",+ "WebPage",+ "WebPageElement"+ ]+ },+ {+ "name": "common Schema.org type",+ "types": [+ "AboutPage",+ "AudioObject",+ "AutoDealer",+ "Bakery",+ "BarOrPub",+ "BusinessEvent",+ "CafeOrCoffeeShop",+ "CollegeOrUniversity",+ "CollectionPage",+ "ContactPage",+ "Corporation",+ "Dentist",+ "EducationEvent",+ "EducationalOrganization",+ "FAQPage",+ "Festival",+ "FoodEstablishment",+ "GovernmentOrganization",+ "IndividualProduct",+ "LegalService",+ "MedicalBusiness",+ "MusicEvent",+ "NGO",+ "OfferCatalog",+ "Photograph",+ "Physician",+ "PodcastEpisode",+ "PodcastSeries",+ "ProductModel",+ "RealEstateAgent",+ "ScholarlyArticle",+ "School",+ "SearchAction",+ "SearchResultsPage",+ "Service",+ "SiteNavigationElement",+ "SportsEvent",+ "SportsOrganization",+ "TVEpisode",+ "TVSeries",+ "TechArticle",+ "TheaterEvent",+ "WebSite"+ ]+ },+ {+ "name": "unsupported type",+ "types": ["PrivateType", "constructor", "toString"]+ }+ ],+ "rejectedTypes": [+ "__proto__",+ "[email protected]",+ "+44 0000 000000",+ "Private Name",+ "https://example.com/vocab#Customer",+ "ex:Customer",+ "schema.org/Product",+ "",+ "07700900123"+ ],+ "cases": [+ {+ "name": "product with nested offer and identifiers",+ "capturedDomIds": ["product-id", "person-id"],+ "input": {+ "@context": "http://schema.org/",+ "@type": "Product",+ "@id": "https://example.com/products/123#product-id",+ "name": "Camera",+ "email": "[email protected]",+ "[email protected]": {+ "@type": "CustomMetadata",+ "ratingValue": 4.5+ },+ "offers": {+ "@type": "Offer",+ "@id": "https://example.com/offers/1",+ "price": 100,+ "priceCurrency": "GBP",+ "seller": {+ "@type": "Person",+ "@id": "#person-id",+ "name": "Private name"+ }+ }+ },+ "expected": {+ "@context": "https://schema.org",+ "@type": "Product",+ "@id": "product-id",+ "name": "Camera",+ "offers": {+ "@type": "Offer",+ "price": 100,+ "priceCurrency": "GBP",+ "seller": {+ "@type": "Person",+ "@id": "person-id"+ }+ }+ }+ },+ {+ "name": "root graph with unknown entity type",+ "capturedDomIds": ["person-id"],+ "input": {+ "@context": "https://schema.org",+ "@graph": [+ {+ "@type": "WebSite",+ "datePublished": "2026-08-25",+ "email": "[email protected]",+ "potentialAction": {+ "@type": "SearchAction",+ "actionStatus": "https://schema.org/PotentialActionStatus",+ "target": "https://example.com/search?q=private"+ }+ },+ {+ "@type": "FAQPage",+ "inLanguage": "en",+ "text": "Private question and answer"+ },+ {+ "@type": "Person",+ "@id": "person-id",+ "name": "Private name"+ },+ {+ "@type": "PrivateType",+ "ratingValue": 4.5,+ "email": "[email protected]",+ "customMetadata": {+ "priceCurrency": "GBP"+ }+ },+ ]+ },+ "expected": {+ "@context": "https://schema.org",+ "@graph": [+ {+ "@type": "WebSite",+ "datePublished": "2026-08-25",+ "potentialAction": {+ "@type": "SearchAction",+ "actionStatus": "https://schema.org/PotentialActionStatus"+ }+ },+ {+ "@type": "FAQPage",+ "inLanguage": "en"+ },+ {+ "@type": "Person",+ "@id": "person-id"+ },+ {+ "@type": "PrivateType",+ "ratingValue": 4.5+ }+ ]+ }+ },+ {+ "name": "type arrays and scalar arrays",+ "capturedDomIds": [],+ "input": {+ "@context": "https://schema.org",+ "@type": ["https://schema.org/Product", "Product", "Car", "Car", "PrivateType", 42],+ "name": ["Camera", 2, true, null],+ "color": [+ "black",+ {+ "value": "private"+ }+ ]+ },+ "expected": {+ "@context": "https://schema.org",+ "@type": ["Product", "Car", "PrivateType"],+ "name": ["Camera", 2, true, null]+ }+ },+ {+ "name": "duplicate types at nested entities",+ "capturedDomIds": [],+ "input": {+ "@context": "https://schema.org",+ "@type": ["Product", "Product", "https://schema.org/Product"],+ "offers": {+ "@type": ["Offer", "Offer"],+ "seller": {+ "@type": ["Organization", "Organization"],+ "brand": {+ "@type": ["Brand", "Brand"],+ "name": "Camera brand"+ }+ }+ }+ },+ "expected": {+ "@context": "https://schema.org",+ "@type": ["Product"],+ "offers": {+ "@type": ["Offer"],+ "seller": {+ "@type": ["Organization"],+ "brand": {+ "@type": ["Brand"],+ "name": "Camera brand"+ }+ }+ }+ }+ },+ {+ "name": "type count is capped after deduplication",+ "capturedDomIds": [],+ "input": {+ "@context": "https://schema.org",+ "@type": [+ "Type01",+ "Type01",+ "Type02",+ "Type03",+ "Type04",+ "Type05",+ "Type06",+ "Type07",+ "Type08",+ "Type09",+ "Type10",+ "Type11",+ "Type12",+ "Type13",+ "Type14",+ "Type15",+ "Type16",+ "Type17",+ "Type18",+ "Type19",+ "Type20",+ "Type21"+ ]+ },+ "expected": {+ "@context": "https://schema.org",+ "@type": [+ "Type01",+ "Type02",+ "Type03",+ "Type04",+ "Type05",+ "Type06",+ "Type07",+ "Type08",+ "Type09",+ "Type10",+ "Type11",+ "Type12",+ "Type13",+ "Type14",+ "Type15",+ "Type16",+ "Type17",+ "Type18",+ "Type19",+ "Type20"+ ]+ }+ },+ {+ "name": "root and nested entity arrays",+ "capturedDomIds": ["person-id"],+ "input": [+ {+ "@context": "https://schema.org",+ "@type": "Product",+ "name": "Camera",+ "offers": [+ {+ "@type": "Offer",+ "price": 100,+ "email": "[email protected]"+ },+ {+ "@type": "Person",+ "@id": "person-id",+ "name": "Private name"+ }+ ]+ },+ {+ "@context": "https://schema.org",+ "@type": "Organization",+ "name": "Acme"+ }+ ],+ "expected": [+ {+ "@context": "https://schema.org",+ "@type": "Product",+ "name": "Camera",+ "offers": [+ {+ "@type": "Offer",+ "price": 100+ },+ {+ "@type": "Person",+ "@id": "person-id"+ }+ ]+ },+ {+ "@context": "https://schema.org",+ "@type": "Organization",+ "name": "Acme"+ }+ ]+ },+ {+ "name": "invalid schema context",+ "capturedDomIds": [],+ "input": {+ "@context": "https://example.com",+ "@type": "Product",+ "name": "Camera"+ },+ "expected": null+ },+ {+ "name": "BreadcrumbList with nested items",+ "capturedDomIds": ["person-id"],+ "input": {+ "@context": "https://schema.org",+ "@type": "BreadcrumbList",+ "itemListElement": [+ {+ "@type": "ListItem",+ "position": 1,+ "name": "Private label",+ "item": {+ "@type": "Product",+ "name": "Camera",+ "email": "[email protected]"+ }+ },+ {+ "@type": "Person",+ "@id": "person-id",+ "name": "Private name"+ }+ ]+ },+ "expected": {+ "@context": "https://schema.org",+ "@type": "BreadcrumbList",+ "itemListElement": [+ {+ "@type": "ListItem",+ "position": 1,+ "item": {+ "@type": "Product",+ "name": "Camera"+ }+ },+ {+ "@type": "Person",+ "@id": "person-id"+ }+ ]+ }+ },+ {+ "name": "ItemList with nested items",+ "capturedDomIds": ["person-id"],+ "input": {+ "@context": "https://schema.org",+ "@type": "ItemList",+ "itemListElement": [+ {+ "@type": "ListItem",+ "position": 1,+ "name": "Private label",+ "item": {+ "@type": "Product",+ "name": "Camera",+ "email": "[email protected]"+ }+ },+ {+ "@type": "Person",+ "@id": "person-id",+ "name": "Private name"+ }+ ]+ },+ "expected": {+ "@context": "https://schema.org",+ "@type": "ItemList",+ "itemListElement": [+ {+ "@type": "ListItem",+ "position": 1,+ "item": {+ "@type": "Product",+ "name": "Camera"+ }+ },+ {+ "@type": "Person",+ "@id": "person-id"+ }+ ]+ }+ },+ {+ "name": "offer catalog and service roots",+ "capturedDomIds": [],+ "input": [+ {+ "@context": "https://schema.org",+ "@type": "OfferCatalog",+ "name": "Services",+ "itemListElement": {+ "@type": "Offer",+ "price": 100,+ "email": "[email protected]"+ }+ },+ {+ "@context": "https://schema.org",+ "@type": "Service",+ "name": "Installation",+ "serviceType": "Installation",+ "email": "[email protected]",+ "provider": {+ "@type": "EducationalOrganization",+ "name": "Acme",+ "telephone": "+44 0000 000000"+ }+ }+ ],+ "expected": [+ {+ "@context": "https://schema.org",+ "@type": "OfferCatalog",+ "name": "Services",+ "itemListElement": {+ "@type": "Offer",+ "price": 100+ }+ },+ {+ "@context": "https://schema.org",+ "@type": "Service",+ "name": "Installation",+ "serviceType": "Installation",+ "provider": {+ "@type": "EducationalOrganization",+ "name": "Acme"+ }+ }+ ]+ },+ {+ "name": "unallowlisted entity branch",+ "capturedDomIds": ["root-id", "child-id", "product-id", "reference-id"],+ "input": {+ "@context": "https://schema.org",+ "@type": "Product",+ "@id": "root-id",+ "name": "Camera",+ "privateRootValue": "private",+ "customChild": {+ "@type": "CustomChild",+ "@id": "child-id",+ "privateChildValue": "private",+ "nestedEntity": {+ "@type": "Product",+ "@id": "product-id",+ "name": "Private product name",+ "ratingValue": 4.5+ },+ "idOnlyNode": {+ "@id": "reference-id",+ "privateReferenceValue": "private"+ }+ }+ },+ "expected": {+ "@context": "https://schema.org",+ "@type": "Product",+ "@id": "root-id",+ "name": "Camera"+ }+ },+ {+ "name": "PII-bearing entity types",+ "capturedDomIds": ["contact-id", "person-id", "address-id"],+ "input": [+ {+ "@context": "https://schema.org",+ "@type": "ContactPoint",+ "@id": "contact-id",+ "name": "Private name",+ "email": "[email protected]",+ "telephone": "+44 0000 000000"+ },+ {+ "@context": "https://schema.org",+ "@type": "Person",+ "@id": "person-id",+ "name": "Private name",+ "email": "[email protected]"+ },+ {+ "@context": "https://schema.org",+ "@type": "PostalAddress",+ "@id": "address-id",+ "streetAddress": "Private address"+ }+ ],+ "expected": [+ {+ "@context": "https://schema.org",+ "@type": "ContactPoint",+ "@id": "contact-id"+ },+ {+ "@context": "https://schema.org",+ "@type": "Person",+ "@id": "person-id"+ },+ {+ "@context": "https://schema.org",+ "@type": "PostalAddress",+ "@id": "address-id"+ }+ ]+ },+ {+ "name": "PII-shaped entity types",+ "capturedDomIds": [],+ "input": {+ "@context": "https://schema.org",+ "@type": ["Product", "[email protected]"],+ "name": "Camera",+ "offers": [+ {+ "@type": "Offer",+ "price": 100+ },+ {+ "@type": "+44 0000 000000",+ "price": 90,+ "name": "Private name"+ },+ {+ "@type": "Private Name"+ }+ ],+ "@graph": [+ {+ "@type": "https://example.com/vocab#Customer",+ "name": "Private name"+ },+ {+ "@type": "ex:Customer",+ "ratingValue": 4.5+ }+ ]+ },+ "expected": {+ "@context": "https://schema.org",+ "@type": ["Product"],+ "name": "Camera",+ "offers": [+ {+ "@type": "Offer",+ "price": 100+ },+ {+ "price": 90+ }+ ],+ "@graph": [+ {+ "ratingValue": 4.5+ }+ ]+ }+ },+ {+ "name": "schema context without an entity",+ "capturedDomIds": [],+ "input": {+ "@context": "https://schema.org",+ "privateValue": "private"+ },+ "expected": null+ }+ ],+ "rawSourceCases": [+ {+ "name": "invalid JSON syntax",+ "source": "not json",+ "expected": null+ }+ ],+ "prototypeCases": [+ {+ "name": "inherited context",+ "inheritedProperties": {+ "@context": "https://schema.org",+ "@type": "Product",+ "@id": "inherited-id",+ "name": "Private name",+ "ratingValue": 5+ },+ "capturedDomIds": ["inherited-id"],+ "input": {+ "@type": "Product"+ },+ "expected": null+ },+ {+ "name": "inherited type",+ "inheritedProperties": {+ "@context": "https://schema.org",+ "@type": "Product",+ "@id": "inherited-id",+ "name": "Private name",+ "ratingValue": 5+ },+ "capturedDomIds": ["inherited-id"],+ "input": {+ "@context": "https://schema.org"+ },+ "expected": null+ },+ {+ "name": "inherited safe-looking leaves",+ "inheritedProperties": {+ "@context": "https://schema.org",+ "@type": "Product",+ "@id": "inherited-id",+ "name": "Private name",+ "ratingValue": 5+ },+ "capturedDomIds": ["inherited-id"],+ "input": {+ "@context": "https://schema.org",+ "@type": "Product"+ },+ "expected": {+ "@context": "https://schema.org",+ "@type": "Product"+ }+ }+ ]+}diff --git a/rust/replay-anonymizer/tests/snapshot.rs b/rust/replay-anonymizer/tests/snapshot.rsindex 025d3370bd13..85fb8eae4217 100644--- a/rust/replay-anonymizer/tests/snapshot.rs+++ b/rust/replay-anonymizer/tests/snapshot.rs@@ -66,6 +66,7 @@ fn end_to_end_contract() {{ "type": 3, "timestamp": TS0 + 2000.5, "data": { "source": 2, "type": 2, "id": 5, "x": 1, "y": 2 } },// Console warn plugin: counted, payload scrubbed.{ "type": 6, "timestamp": TS0 + 3000.0, "data": { "plugin": "rrweb/console@1", "payload": { "level": "warn", "payload": ["secret"], "trace": [] } } },+ { "type": 5, "timestamp": TS0 + 4000.0, "data": { "tag": "$json_ld", "payload": { "@context": "https://schema.org", "@type": "Product", "name": "Camera", "email": "[email protected]", "offers": { "@type": "Offer", "price": 100, "priceCurrency": "USD", "seller": { "@type": "Person", "name": "Example Viewer" } } } } },// Filtered out: no timestamp, non-object, non-positive timestamp.{ "type": 3, "data": { "source": 1 } },"junk",@@ -74,7 +75,7 @@ fn end_to_end_contract() {let out = run(&allow, &payload_of(&inner)).expect("message anonymizes");let lines = parse_lines(&out.lines);- assert_eq!(lines.len(), 4, "invalid events are filtered out");+ assert_eq!(lines.len(), 5, "invalid events are filtered out");for line in &lines {assert_eq!(line[0], "w-1");}@@ -88,6 +89,10 @@ fn end_to_end_contract() {json!({ "source": 2, "type": 2, "id": 5, "x": 1, "y": 2 }));assert_eq!(lines[3][1]["data"]["payload"]["payload"][0], "******");+ assert_eq!(+ lines[4][1]["data"],+ json!({ "tag": "$json_ld", "payload": { "@context": "https://schema.org", "@type": "Product", "name": "Camera", "offers": { "@type": "Offer", "price": 100, "priceCurrency": "USD", "seller": { "@type": "Person" } } } })+ );let meta = &out.meta;assert_eq!(meta.distinct_id, "d-1");@@ -96,7 +101,7 @@ fn end_to_end_contract() {assert_eq!(meta.snapshot_source.as_deref(), Some("web"));assert_eq!(meta.snapshot_library.as_deref(), Some("posthog-js"));assert_eq!(meta.start_ts, TS0);- assert_eq!(meta.end_ts, TS0 + 3000.0);+ assert_eq!(meta.end_ts, TS0 + 4000.0);assert_eq!((meta.console_log_count,@@ -105,6 +110,7 @@ fn end_to_end_contract() {),(0, 1, 0));+ assert_eq!(meta.json_ld_event_count, 1);let flags: Vec<u8> = meta.events.iter().map(|e| e.flags).collect();assert_eq!(@@ -114,6 +120,7 @@ fn end_to_end_contract() {FLAG_ACTIVE | FLAG_KEYPRESS,FLAG_ACTIVE | FLAG_CLICK | FLAG_MOUSE_ACTIVITY,0,+ 0,]);assert_eq!(