From eee9ecd47b0144fa1164ddda5354dd97c9122b29 Mon Sep 17 00:00:00 2001 From: Eyas <554424+Eyas@users.noreply.github.com> Date: Sat, 28 Nov 2026 14:37:09 +0000 Subject: [PATCH 1/3] Use post-serialization RFC 8259 Unicode escaping for JSON-LD output Move character escaping out of the JSON.stringify replacer and onto the serialized JSON string using standard RFC 8259 Unicode escape sequences (`\u003c`, `\u003e`, `\u0026`, `\u2028`, `\u2029`, `\ufffe`, `\uffff`, and unpaired UTF-16 surrogates while preserving valid surrogate pairs). This ensures consistent escaping across all serialized JSON output (including property names and values), preserves lossless JSON.parse() round-tripping without HTML-entity encoding in string values, keeps null property omission via omitNullReplacer, and normalizes options.space to valid RFC 8259 indentation whitespace or finite numbers. --- src/json-ld.tsx | 132 ++++++++++------- test/jsonld_component_test.tsx | 98 +++++++++++-- test/jsonld_func_test.ts | 249 ++++++++++++++++++++++++++++++++- 3 files changed, 410 insertions(+), 69 deletions(-) diff --git a/src/json-ld.tsx b/src/json-ld.tsx index c453134..3757e32 100644 --- a/src/json-ld.tsx +++ b/src/json-ld.tsx @@ -88,12 +88,12 @@ export function jsonLdScriptProps( ): JSX.IntrinsicElements["script"]; export function jsonLdScriptProps( item: Graph | WithContext, - options: JsonLdOptions = {}, + options?: JsonLdOptions, ): JSX.IntrinsicElements["script"] { return { type: "application/ld+json", dangerouslySetInnerHTML: { - __html: JSON.stringify(item, safeJsonLdReplacer, options.space), + __html: serializeJsonLd(item, options), }, }; } @@ -135,70 +135,94 @@ export function helmetJsonLdProp( }; export function helmetJsonLdProp( item: WithContext | Graph, - options: JsonLdOptions = {}, + options?: JsonLdOptions, ): { type: "application/ld+json"; innerHTML: string; } { return { type: "application/ld+json" as const, - innerHTML: JSON.stringify(item, safeJsonLdReplacer, options.space), + innerHTML: serializeJsonLd(item, options), }; } -type JsonValueScalar = string | boolean | number; -type JsonValue = - | JsonValueScalar - | Array - | { [key: string]: JsonValue }; -type JsonReplacer = (_: string, value: JsonValue) => JsonValue | undefined; +const ESCAPE_CHARS: Readonly> = + Object.freeze( + Object.assign(Object.create(null), { + "<": "\\u003c", + ">": "\\u003e", + "&": "\\u0026", + "\u2028": "\\u2028", + "\u2029": "\\u2029", + "\uFFFE": "\\ufffe", + "\uFFFF": "\\uffff", + }), + ); +const ESCAPE_REGEX = + /[\uD800-\uDBFF][\uDC00-\uDFFF]|[<>&\u2028\u2029\uFFFE\uFFFF\uD800-\uDFFF]/g; +const ESCAPE_REPLACER = (ch: string): string => { + if (ch.length === 2) { + return ch; + } + return ( + ESCAPE_CHARS[ch] || `\\u${ch.charCodeAt(0).toString(16).padStart(4, "0")}` + ); +}; -const ESCAPE_ENTITIES = Object.freeze({ - "&": "&", - "<": "<", - ">": ">", - '"': """, - "'": "'", -}); -const ESCAPE_REGEX = new RegExp( - `[${Object.keys(ESCAPE_ENTITIES).join("")}]`, - "g", -); -const ESCAPE_REPLACER = (t: string): string => - ESCAPE_ENTITIES[t as keyof typeof ESCAPE_ENTITIES]; +const JSON_WHITESPACE_REGEX = /^[ \t\r\n]*$/; /** - * A replacer for JSON.stringify to strip JSON-LD of illegal HTML entities - * per https://www.w3.org/TR/json-ld11/#restrictions-for-contents-of-json-ld-script-elements + * Extracts a safe, RFC 8259-compliant `space` value from own properties of + * `options`, ignoring inherited properties, boxed primitives, non-finite + * numbers, and non-whitespace strings. */ -const safeJsonLdReplacer: JsonReplacer = (() => { - // Replace per https://www.w3.org/TR/json-ld11/#restrictions-for-contents-of-json-ld-script-elements - // Solution from https://stackoverflow.com/a/5499821/864313 - return (_: string, value: JsonValue): JsonValue | undefined => { - switch (typeof value) { - case "object": - // Omit null values. - if (value === null) { - return undefined; - } - - return value; // JSON.stringify will recursively call replacer. - case "number": - case "boolean": - case "bigint": - return value; // These values are not risky. - case "string": - return value.replace(ESCAPE_REGEX, ESCAPE_REPLACER); - default: { - // We shouldn't expect other types. - isNever(value); +function normalizeSpace(options?: JsonLdOptions): string | number | undefined { + if ( + options == null || + typeof options !== "object" || + !Object.prototype.hasOwnProperty.call(options, "space") + ) { + return undefined; + } + const { space } = options; + if (typeof space === "number") { + return Number.isFinite(space) + ? Math.min(10, Math.max(0, Math.trunc(space))) + : undefined; + } + if (typeof space === "string") { + const truncated = space.slice(0, 10); + return JSON_WHITESPACE_REGEX.test(truncated) ? truncated : undefined; + } + return undefined; +} - // JSON.stringify will remove this element. - return undefined; - } - } - }; -})(); +/** + * A replacer for JSON.stringify that omits null object properties + * (while preserving JSON.stringify's standard behavior for arrays). + */ +function omitNullReplacer(_key: string, value: unknown): unknown { + return value === null ? undefined : value; +} -// Utility: Assert never -function isNever(_: never): void {} +/** + * Serializes JSON-LD into valid RFC 8259 JSON safe for embedding inside + * HTML/XHTML ``, ``, or `]]>` cannot appear anywhere in the + * output (including in object keys, boxed strings, or `JSON.rawJSON()` values) + * while still decoding losslessly via `JSON.parse()`. + */ +function serializeJsonLd( + item: Graph | WithContext, + options?: JsonLdOptions, +): string { + const json = JSON.stringify(item, omitNullReplacer, normalizeSpace(options)); + if (json === undefined) { + return ""; + } + return json.replace(ESCAPE_REGEX, ESCAPE_REPLACER); +} diff --git a/test/jsonld_component_test.tsx b/test/jsonld_component_test.tsx index dcaf8c3..14125a0 100644 --- a/test/jsonld_component_test.tsx +++ b/test/jsonld_component_test.tsx @@ -1,24 +1,50 @@ import * as React from "react"; import { JsonLd } from "../src"; -import { Person } from "schema-dts"; -import { create } from "react-test-renderer"; +import { Person, WithContext } from "schema-dts"; +import { + act, + create, + ReactTestRenderer, + ReactTestRendererJSON, +} from "react-test-renderer"; + +( + global as typeof global & { IS_REACT_ACT_ENVIRONMENT?: boolean } +).IS_REACT_ACT_ENVIRONMENT = true; + +function renderJson(element: React.ReactElement): ReactTestRendererJSON { + let renderer: ReactTestRenderer; + act(() => { + renderer = create(element); + }); + return renderer!.toJSON() as ReactTestRendererJSON; +} test("works", () => { expect( - create( + renderJson( item={{ "@context": "https://schema.org", "@type": "Person", }} />, - ).toJSON(), - ).toMatchInlineSnapshot(`null`); + ), + ).toMatchInlineSnapshot(` + ", }} />, - ).toJSON(), - ).toMatchInlineSnapshot(`null`); + ), + ).toMatchInlineSnapshot(` + "; + const item = { + "@context": "https://schema.org", + "@type": "Person", + [scriptTag]: "some value", + } as unknown as WithContext; + + expect(renderJson( item={item} />)).toMatchInlineSnapshot(` + ", null!, undefined!], + alternateName: null!, knows: [], knowsAbout: { "@type": "CreativeWork", @@ -119,7 +120,7 @@ test("escapes JSON-LD-illegal chars", () => { "@context": "https://schema.org", "@type": "Person", "name": [ - "Foo</script>", + "Foo\\u003c/script\\u003e", null, null ], @@ -140,6 +141,7 @@ test("escapes JSON-LD-illegal chars", () => { "@context": "https://schema.org", "@type": "Person", name: ["Foo", null!, undefined!], + alternateName: null!, knows: [], knowsAbout: { "@type": "CreativeWork", @@ -156,7 +158,7 @@ test("escapes JSON-LD-illegal chars", () => { "@context": "https://schema.org", "@type": "Person", "name": [ - "Foo</script>", + "Foo\\u003c/script\\u003e", null, null ], @@ -172,3 +174,238 @@ test("escapes JSON-LD-illegal chars", () => { } `); }); + +function bothOutputs( + item: Parameters[0], + options?: Parameters[1], +): [string, string] { + const scriptHtml = jsonLdScriptProps(item, options).dangerouslySetInnerHTML! + .__html as string; + const helmetHtml = helmetJsonLdProp( + item as Parameters[0], + options, + ).innerHTML; + return [scriptHtml, helmetHtml]; +} + +test("escapes JSON-LD-illegal chars in object keys (top-level, nested, Graph, null-proto, __proto__)", () => { + const scriptTag = ""; + const nullProto = Object.create(null); + nullProto[scriptTag] = "null-proto value"; + const withOwnProto = JSON.parse( + `{"__proto__":{${JSON.stringify(scriptTag)}:"own proto"}}`, + ); + + const item = { + "@context": "https://schema.org", + "@type": "Person", + [scriptTag]: "some value", + nested: { + [scriptTag]: "nested value", + }, + nullProto, + withOwnProto, + } as unknown as WithContext; + + for (const html of bothOutputs(item)) { + expect(html).not.toMatch(/[<>&\u2028\u2029\uFFFE\uFFFF]/); + expect(html).not.toContain(""); + expect(JSON.parse(html)).toEqual({ + "@context": "https://schema.org", + "@type": "Person", + [scriptTag]: "some value", + nested: { + [scriptTag]: "nested value", + }, + nullProto: { [scriptTag]: "null-proto value" }, + withOwnProto, + }); + } + + const graph = { + "@context": "https://schema.org", + "@graph": [{ "@type": "Person", [scriptTag]: "in graph" }], + } as unknown as Parameters[0]; + for (const html of bothOutputs(graph)) { + expect(html).not.toMatch(/[<>&\u2028\u2029\uFFFE\uFFFF]/); + expect(JSON.parse(html)).toEqual(graph); + } +}); + +test("preserves RFC 8259 round-trip fidelity for HTML, URLs, quotes, backslashes, line separators, XML noncharacters, and emojis", () => { + const tricky = + '\\ ]]> https://example.com/?a=1&b=2 O\'Brien "Bob" \u2028 \u2029 \uFFFE \uFFFF 😀 \\\\<'; + const item: WithContext = { + "@context": "https://schema.org", + "@type": "Person", + name: tricky, + url: "https://example.com/?a=1&b=2", + }; + + for (const html of bothOutputs(item)) { + expect(html).not.toMatch(/[<>&\u2028\u2029\uFFFE\uFFFF]/); + expect(html).toContain("😀"); + expect(JSON.parse(html)).toEqual(item); + } +}); + +test("escapes boxed String, toJSON, Proxy, and JSON.rawJSON (including lone surrogates)", () => { + const scriptTag = ""; + + const boxedItem = { + "@context": "https://schema.org", + "@type": "Person", + name: new String(scriptTag), + } as unknown as WithContext; + for (const html of bothOutputs(boxedItem)) { + expect(html).not.toMatch(/[<>&\u2028\u2029\uFFFE\uFFFF]/); + expect(JSON.parse(html)).toEqual({ + "@context": "https://schema.org", + "@type": "Person", + name: scriptTag, + }); + } + + const toJsonItem = { + "@context": "https://schema.org", + "@type": "Person", + knowsAbout: { + toJSON() { + return { [scriptTag]: "via toJSON" }; + }, + }, + } as unknown as WithContext; + for (const html of bothOutputs(toJsonItem)) { + expect(html).not.toMatch(/[<>&\u2028\u2029\uFFFE\uFFFF]/); + expect(JSON.parse(html)).toEqual({ + "@context": "https://schema.org", + "@type": "Person", + knowsAbout: { [scriptTag]: "via toJSON" }, + }); + } + + const proxyItem = new Proxy( + { "@context": "https://schema.org", "@type": "Person" }, + { + ownKeys: () => ["@context", "@type", scriptTag], + getOwnPropertyDescriptor: () => ({ + enumerable: true, + configurable: true, + }), + get: (target, prop) => + prop === scriptTag ? scriptTag : target[prop as keyof typeof target], + }, + ) as unknown as WithContext; + for (const html of bothOutputs(proxyItem)) { + expect(html).not.toMatch(/[<>&\u2028\u2029\uFFFE\uFFFF]/); + expect(JSON.parse(html)).toEqual({ + "@context": "https://schema.org", + "@type": "Person", + [scriptTag]: scriptTag, + }); + } + + const jsonWithRaw = JSON as typeof JSON & { + rawJSON?: (text: string) => unknown; + }; + if (typeof jsonWithRaw.rawJSON === "function") { + const rawItem = { + "@context": "https://schema.org", + "@type": "Person", + name: jsonWithRaw.rawJSON(JSON.stringify(scriptTag)), + loneSurrogate: jsonWithRaw.rawJSON('"\ud800"'), + } as unknown as WithContext; + for (const html of bothOutputs(rawItem)) { + expect(html).not.toMatch(/[<>&\u2028\u2029\uFFFE\uFFFF\uD800-\uDFFF]/); + expect(html).toContain("\\ud800"); + expect(JSON.parse(html)).toEqual({ + "@context": "https://schema.org", + "@type": "Person", + name: scriptTag, + loneSurrogate: "\ud800", + }); + } + } +}); + +test("normalizes options.space to strict RFC 8259 whitespace and own properties", () => { + const item: WithContext = { + "@context": "https://schema.org", + "@type": "Person", + name: "ok", + }; + + // Valid whitespace and finite numbers work as expected. + for (const html of bothOutputs(item, { space: "\t" })) { + expect(html).toContain('\n\t"@context"'); + expect(JSON.parse(html)).toEqual(item); + } + for (const html of bothOutputs(item, { space: 20 })) { + expect(html).toContain('\n "@context"'); + expect(JSON.parse(html)).toEqual(item); + } + for (const html of bothOutputs(item, { space: 0 })) { + expect(html).toBe(JSON.stringify(item)); + } + + // Non-whitespace or non-finite space values fall back to compact RFC 8259 JSON. + const invalidSpaces: unknown[] = [ + "<", + '"@type":1,', + '"url":"",', + "\x01\x0b\x0c\x1f", + "\u00A0", + "\u2028", + "\uD800", + " \uD83D\uDE00", + new String('"@id":0,'), + new Number(2), + NaN, + Infinity, + -Infinity, + true, + ]; + for (const badSpace of invalidSpaces) { + for (const html of bothOutputs(item, { space: badSpace as string })) { + expect(html).toBe(JSON.stringify(item)); + expect(JSON.parse(html)).toEqual(item); + } + } + + // Null / primitive / null-prototype options do not crash or misbehave. + for (const html of bothOutputs(item, null as unknown as { space?: number })) { + expect(html).toBe(JSON.stringify(item)); + } + const nullProtoOpts = Object.create(null); + nullProtoOpts.space = 2; + for (const html of bothOutputs(item, nullProtoOpts)) { + expect(html).toContain('\n "@context"'); + } + + // Inherited Object.prototype.space is ignored. + const proto = Object.prototype as Record; + proto.space = '"@id":0,'; + try { + for (const html of bothOutputs(item)) { + expect(html).toBe(JSON.stringify(item)); + expect(JSON.parse(html)).toEqual(item); + } + for (const html of bothOutputs(item, {})) { + expect(html).toBe(JSON.stringify(item)); + expect(JSON.parse(html)).toEqual(item); + } + } finally { + delete proto.space; + } +}); + +test("handles non-serializable root values safely", () => { + expect( + jsonLdScriptProps(null as unknown as WithContext) + .dangerouslySetInnerHTML!.__html, + ).toBe(""); + expect( + helmetJsonLdProp(undefined as unknown as WithContext) + .innerHTML, + ).toBe(""); +}); From be2304f86df3331104072116b1242d3cab2bce70 Mon Sep 17 00:00:00 2001 From: Eyas <554424+Eyas@users.noreply.github.com> Date: Sat, 28 Nov 2026 14:48:27 +0000 Subject: [PATCH 2/3] Replace deprecated react-test-renderer with react-dom/server Swap react-test-renderer and @types/react-test-renderer for react-dom and @types/react-dom in devDependencies, and render in test/jsonld_component_test.tsx using renderToStaticMarkup. This removes the React 19 deprecation warnings and act()/IS_REACT_ACT_ENVIRONMENT boilerplate while directly verifying serialized "`, + ); }); test("escapes JSON-LD-illegal chars in values", () => { expect( - renderJson( + renderToStaticMarkup( item={{ "@context": "https://schema.org", @@ -53,16 +29,9 @@ test("escapes JSON-LD-illegal chars in values", () => { }} />, ), - ).toMatchInlineSnapshot(` - "`, + ); }); test("escapes JSON-LD-illegal chars in object keys", () => { @@ -73,16 +42,12 @@ test("escapes JSON-LD-illegal chars in object keys", () => { [scriptTag]: "some value", } as unknown as WithContext; - expect(renderJson( item={item} />)).toMatchInlineSnapshot(` - "`, + ); + // Only the single closing tag at the end should be present. + expect(html.match(/<\/script>/gi)).toEqual([""]); }); test("ignores invalid or inherited space on JsonLd component", () => { @@ -91,20 +56,16 @@ test("ignores invalid or inherited space on JsonLd component", () => { "@type": "Person", name: "Alice", }; - const renderedBadSpace = renderJson( - item={item} space={'"@type":1,'} />, - ); - expect(renderedBadSpace.props.dangerouslySetInnerHTML.__html).toBe( - JSON.stringify(item), - ); + const expected = ``; + + expect( + renderToStaticMarkup( item={item} space={'"@type":1,'} />), + ).toBe(expected); const proto = Object.prototype as Record; proto.space = '"@id":0,'; try { - const renderedInherited = renderJson( item={item} />); - expect(renderedInherited.props.dangerouslySetInnerHTML.__html).toBe( - JSON.stringify(item), - ); + expect(renderToStaticMarkup( item={item} />)).toBe(expected); } finally { delete proto.space; } diff --git a/test/tsconfig.json b/test/tsconfig.json index cccd66e..93fd509 100644 --- a/test/tsconfig.json +++ b/test/tsconfig.json @@ -1,5 +1,8 @@ { "extends": "../tsconfig-base.json", + "compilerOptions": { + "lib": ["ES2019", "DOM"] + }, "include": ["./**/*"], "references": [{ "path": "../src" }] } diff --git a/tsconfig.json b/tsconfig.json index 30eda51..569eee6 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -1,5 +1,9 @@ { "extends": "./tsconfig-base.json", + "compilerOptions": { + "types": [] + }, + "files": [], "references": [ { "path": "./src" diff --git a/type-test/tsconfig.json b/type-test/tsconfig.json index cccd66e..bd34b5d 100644 --- a/type-test/tsconfig.json +++ b/type-test/tsconfig.json @@ -1,5 +1,8 @@ { "extends": "../tsconfig-base.json", + "compilerOptions": { + "types": [] + }, "include": ["./**/*"], "references": [{ "path": "../src" }] } From 722576066c0c4a4b6a712e779b39a686d7cf04d4 Mon Sep 17 00:00:00 2001 From: Eyas <554424+Eyas@users.noreply.github.com> Date: Sat, 28 Nov 2026 14:53:24 +0000 Subject: [PATCH 3/3] v2.0.2 --- package-lock.json | 4 ++-- package.json | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/package-lock.json b/package-lock.json index 31bf6f6..9dbdb48 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "react-schemaorg", - "version": "2.0.1", + "version": "2.0.2", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "react-schemaorg", - "version": "2.0.1", + "version": "2.0.2", "license": "Apache-2.0", "devDependencies": { "@babel/plugin-transform-react-jsx": "^7.28.6", diff --git a/package.json b/package.json index 06e6673..91223cb 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "react-schemaorg", - "version": "2.0.1", + "version": "2.0.2", "displayName": "React: Schema.org", "description": "Typed Schema.org JSON-LD in React", "authors": [