🪢 Open source agent evals & observability: Trace, evaluate, and improve LLM applications with one open platform.
TypeScript analyticsautogenevaluationlangchainlarge-language-modelsllama-indexllmllm-evaluationllm-observabilityllmopsmonitoringobservabilityopen-sourceopenaiplaygroundprompt-engineeringprompt-managementself-hostedycombinator
fix(trace): decode unicode escapes in remaining JSON viewers (#14668)
Yuto Toyad6a6a466dddc
diff --git a/web/src/components/trace/components/IOPreview/IOPreviewJSON.tsx b/web/src/components/trace/components/IOPreview/IOPreviewJSON.tsxindex 43d9105f63..f08fe141c4 100644--- a/web/src/components/trace/components/IOPreview/IOPreviewJSON.tsx+++ b/web/src/components/trace/components/IOPreview/IOPreviewJSON.tsx@@ -25,6 +25,7 @@ import { InlineCommentBubble } from "@/src/features/comments/components/InlineCoimport { type CommentedPathsByField } from "@/src/components/ui/AdvancedJsonViewer/utils/commentRanges";import { type ExpansionState } from "@/src/components/ui/AdvancedJsonViewer/types";import { type Prisma, type ScoreDomain, deepParseJson } from "@langfuse/shared";+import { decodeUnicodeInJson } from "@/src/utils/decodeUnicodeInJson";import { CorrectedOutputField } from "./components/CorrectedOutputField";const VIRTUALIZATION_THRESHOLD = 3333;@@ -122,19 +123,24 @@ function IOPreviewJSONInner({// Fall back to raw values when caller does not provide pre-parsed fields// (e.g. session events rows in v4 mode).+ // Decode \uXXXX escapes (e.g. Japanese ingested with Python+ // ensure_ascii=True) at the data source so that search-match offsets, comment+ // ranges, rendering and copy-to-clipboard all operate on the same decoded+ // strings. Decoding at the leaf renderer instead would desync highlight+ // offsets. Already-decoded strings are a no-op.const effectiveInput = useMemo(() => {if (isParsing) return undefined;- return parsedInput ?? deepParseJson(input);+ return decodeUnicodeInJson(parsedInput ?? deepParseJson(input));}, [parsedInput, input, isParsing]);const effectiveOutput = useMemo(() => {if (isParsing) return undefined;- return parsedOutput ?? deepParseJson(output);+ return decodeUnicodeInJson(parsedOutput ?? deepParseJson(output));}, [parsedOutput, output, isParsing]);const effectiveMetadata = useMemo(() => {if (isParsing) return undefined;- return parsedMetadata ?? deepParseJson(metadata);+ return decodeUnicodeInJson(parsedMetadata ?? deepParseJson(metadata));}, [parsedMetadata, metadata, isParsing]);const showInput = !hideInput && !(hideIfNull && effectiveInput === undefined);diff --git a/web/src/components/ui/CodeJsonViewer.tsx b/web/src/components/ui/CodeJsonViewer.tsxindex 00ec0cc02c..a1a62f9859 100644--- a/web/src/components/ui/CodeJsonViewer.tsx+++ b/web/src/components/ui/CodeJsonViewer.tsx@@ -12,6 +12,7 @@ import { cn } from "@/src/utils/tailwind";import { default as React18JsonView } from "react18-json-view";import "react18-json-view/src/dark.css";import { deepParseJson } from "@langfuse/shared";+import { decodeUnicodeInJson } from "@/src/utils/decodeUnicodeInJson";import { Skeleton } from "@/src/components/ui/skeleton";import { useTheme } from "next-themes";import { usePostHogClientCapture } from "@/src/features/posthog-analytics/usePostHogClientCapture";@@ -46,8 +47,14 @@ export function JSONView(props: {externalJsonCollapsed?: boolean;onToggleCollapse?: () => void;}) {- // some users ingest stringified json nested in json, parse it- const parsedJson = useMemo(() => deepParseJson(props.json), [props.json]);+ // some users ingest stringified json nested in json, parse it. Also decode+ // \uXXXX escapes (e.g. Japanese ingested with Python ensure_ascii=True) so+ // non-ASCII content renders as real characters. Already-decoded strings are+ // a no-op (decodeUnicodeEscapesOnly returns early when there is no backslash).+ const parsedJson = useMemo(+ () => decodeUnicodeInJson(deepParseJson(props.json)),+ [props.json],+ );const { resolvedTheme } = useTheme();const { setIsMarkdownEnabled } = useMarkdownContext();const capture = usePostHogClientCapture();diff --git a/web/src/components/ui/PrettyJsonView.clienttest.ts b/web/src/components/ui/PrettyJsonView.clienttest.tsindex 7dcf4e0399..0cfd72be61 100644--- a/web/src/components/ui/PrettyJsonView.clienttest.ts+++ b/web/src/components/ui/PrettyJsonView.clienttest.ts@@ -116,6 +116,27 @@ describe("decodeUnicodeInJson", () => {});});+ it("drops keys that decode to a prototype-pollution vector", () => {+ // An escaped "__proto__" survives deepParseJson's literal-string filter and+ // only becomes dangerous after we decode it — so it must be dropped here.+ const result = decodeUnicodeInJson({+ "\\u005f\\u005fproto\\u005f\\u005f": { admin: true },+ safe: "\\u5024",+ }) as Record<string, unknown>;+ expect(result).toEqual({ safe: "値" });+ // The decoded object's prototype must be untouched (no pollution).+ expect(Object.getPrototypeOf(result)).toBe(Object.prototype);+ expect((result as { admin?: unknown }).admin).toBeUndefined();+ // constructor / prototype are dropped too.+ expect(+ decodeUnicodeInJson({+ "\\u0063onstructor": 1,+ "\\u0070rototype": 2,+ ok: 3,+ }),+ ).toEqual({ ok: 3 });+ });+it("does not blow the call stack on very deeply nested structures", () => {// Build a chain ~10x deeper than MAX_DEPTH. A recursive implementation would// throw "Maximum call stack size exceeded" here.diff --git a/web/src/components/ui/PrettyJsonView.tsx b/web/src/components/ui/PrettyJsonView.tsxindex 0a04a42894..773b3b5231 100644--- a/web/src/components/ui/PrettyJsonView.tsx+++ b/web/src/components/ui/PrettyJsonView.tsx@@ -1,7 +1,7 @@import { useMemo, useState, useEffect, useRef, useCallback, memo } from "react";import { cn } from "@/src/utils/tailwind";import { deepParseJson } from "@langfuse/shared";-import { decodeUnicodeEscapesOnly } from "@/src/utils/unicode";+import { decodeUnicodeInJson } from "@/src/utils/decodeUnicodeInJson";import { Skeleton } from "@/src/components/ui/skeleton";import { type MediaReturnType } from "@/src/features/media/validation";import { LangfuseMediaView } from "@/src/components/ui/LangfuseMediaView";@@ -84,112 +84,14 @@ const SYSTEM_TITLES = ["system", "Input"];const MONO_TEXT_CLASSES = "font-mono text-xs wrap-break-word";const PREVIEW_TEXT_CLASSES = "italic text-gray-500 dark:text-gray-400";-// Guards to keep decoding bounded on very large payloads. Exceeding either-// limit returns the remainder undecoded (preserving browser responsiveness-// over decoding completeness).-export const DECODE_UNICODE_MAX_NODES = 50_000;-export const DECODE_UNICODE_MAX_DEPTH = 200;--/**- * Iteratively decode \uXXXX escape sequences in all string values of a parsed JSON- * structure. Used so that traces ingested via Python SDK's json.dumps(ensure_ascii=True)- * display non-ASCII characters (e.g. Japanese, Chinese) correctly in the trace detail- * view. Mirrors the approach used in IOTableCell and batch export (see PR #12882).- *- * Uses greedy mode to handle both \uXXXX (single-escaped) and \\uXXXX (double-escaped)- * forms that can appear depending on the ingest path.- *- * Implemented iteratively (explicit stack) with node-count and depth caps so that- * very large or deeply nested payloads cannot blow the call stack or freeze the tab.- */-export function decodeUnicodeInJson(value: unknown): unknown {- if (typeof value === "string") {- return decodeUnicodeEscapesOnly(value, true);- }- if (value === null || typeof value !== "object") {- return value;- }-- const root: unknown[] | Record<string, unknown> = Array.isArray(value)- ? []- : {};-- type Frame = {- source: unknown[] | Record<string, unknown>;- target: unknown[] | Record<string, unknown>;- depth: number;- };- const stack: Frame[] = [- {- source: value as unknown[] | Record<string, unknown>,- target: root,- depth: 0,- },- ];-- let nodeCount = 0;- let budgetExceeded = false;-- while (stack.length > 0) {- const { source, target, depth } = stack.pop()!;-- if (Array.isArray(source)) {- const arr = target as unknown[];- for (let i = 0; i < source.length; i++) {- const v = source[i];- if (budgetExceeded || ++nodeCount > DECODE_UNICODE_MAX_NODES) {- budgetExceeded = true;- arr[i] = v;- continue;- }- arr[i] = assignDecodedOrDescend(v, depth, stack);- }- } else {- const obj = target as Record<string, unknown>;- for (const k of Object.keys(source as Record<string, unknown>)) {- const v = (source as Record<string, unknown>)[k];- // Keys can also contain \uXXXX escapes when the ingest path double-- // encodes the payload, so decode them alongside the values.- const decodedKey = decodeUnicodeEscapesOnly(k, true);- if (budgetExceeded || ++nodeCount > DECODE_UNICODE_MAX_NODES) {- budgetExceeded = true;- obj[decodedKey] = v;- continue;- }- obj[decodedKey] = assignDecodedOrDescend(v, depth, stack);- }- }- }-- return root;-}--function assignDecodedOrDescend(- v: unknown,- depth: number,- stack: Array<{- source: unknown[] | Record<string, unknown>;- target: unknown[] | Record<string, unknown>;- depth: number;- }>,-): unknown {- if (typeof v === "string") {- return decodeUnicodeEscapesOnly(v, true);- }- if (v === null || typeof v !== "object") {- return v;- }- if (depth + 1 > DECODE_UNICODE_MAX_DEPTH) {- return v; // bail on deeper subtrees to avoid runaway work- }- const child: unknown[] | Record<string, unknown> = Array.isArray(v) ? [] : {};- stack.push({- source: v as unknown[] | Record<string, unknown>,- target: child,- depth: depth + 1,- });- return child;-}+// decodeUnicodeInJson was extracted to a standalone module so that other JSON+// viewers (e.g. CodeJsonViewer) can reuse it without creating an import cycle.+// Re-exported here for backward compatibility with existing imports and tests.+export {+ decodeUnicodeInJson,+ DECODE_UNICODE_MAX_NODES,+ DECODE_UNICODE_MAX_DEPTH,+} from "@/src/utils/decodeUnicodeInJson";function shouldShowValue(value: unknown, showNullValues: boolean): boolean {if (showNullValues) return true;diff --git a/web/src/utils/decodeUnicodeInJson.ts b/web/src/utils/decodeUnicodeInJson.tsnew file mode 100644index 0000000000..be43ca7c69--- /dev/null+++ b/web/src/utils/decodeUnicodeInJson.ts@@ -0,0 +1,121 @@+import { decodeUnicodeEscapesOnly } from "@/src/utils/unicode";++// Guards to keep decoding bounded on very large payloads. Exceeding either+// limit returns the remainder undecoded (preserving browser responsiveness+// over decoding completeness).+export const DECODE_UNICODE_MAX_NODES = 50_000;+export const DECODE_UNICODE_MAX_DEPTH = 200;++// Mirrors the anti-prototype-pollution guard in deepParseJson (see+// packages/shared/src/utils/json.ts). deepParseJson strips these keys before+// we run, but an escaped wire key like "\\u005f\\u005fproto\\u005f\\u005f"+// survives its literal-string filter and only becomes "__proto__" after we+// decode it here — so we must re-apply the same guard on the decoded key to+// avoid assigning to Object.prototype accessors (e.g. the __proto__ setter).+const DANGEROUS_KEYS = new Set(["__proto__", "constructor", "prototype"]);++/**+ * Iteratively decode \uXXXX escape sequences in all string values of a parsed JSON+ * structure. Used so that traces ingested via Python SDK's json.dumps(ensure_ascii=True)+ * display non-ASCII characters (e.g. Japanese, Chinese) correctly in the trace detail+ * view. Mirrors the approach used in IOTableCell and batch export (see PR #12882).+ *+ * Uses greedy mode to handle both \uXXXX (single-escaped) and \\uXXXX (double-escaped)+ * forms that can appear depending on the ingest path.+ *+ * Implemented iteratively (explicit stack) with node-count and depth caps so that+ * very large or deeply nested payloads cannot blow the call stack or freeze the tab.+ */+export function decodeUnicodeInJson(value: unknown): unknown {+ if (typeof value === "string") {+ return decodeUnicodeEscapesOnly(value, true);+ }+ if (value === null || typeof value !== "object") {+ return value;+ }++ const root: unknown[] | Record<string, unknown> = Array.isArray(value)+ ? []+ : {};++ type Frame = {+ source: unknown[] | Record<string, unknown>;+ target: unknown[] | Record<string, unknown>;+ depth: number;+ };+ const stack: Frame[] = [+ {+ source: value as unknown[] | Record<string, unknown>,+ target: root,+ depth: 0,+ },+ ];++ let nodeCount = 0;+ let budgetExceeded = false;++ while (stack.length > 0) {+ const { source, target, depth } = stack.pop()!;++ if (Array.isArray(source)) {+ const arr = target as unknown[];+ for (let i = 0; i < source.length; i++) {+ const v = source[i];+ if (budgetExceeded || ++nodeCount > DECODE_UNICODE_MAX_NODES) {+ budgetExceeded = true;+ arr[i] = v;+ continue;+ }+ arr[i] = assignDecodedOrDescend(v, depth, stack);+ }+ } else {+ const obj = target as Record<string, unknown>;+ for (const k of Object.keys(source as Record<string, unknown>)) {+ const v = (source as Record<string, unknown>)[k];+ // Keys can also contain \uXXXX escapes when the ingest path double-+ // encodes the payload, so decode them alongside the values.+ const decodedKey = decodeUnicodeEscapesOnly(k, true);+ // Drop keys that decode to a prototype-pollution vector (e.g. an+ // escaped "__proto__"), matching deepParseJson's DANGEROUS_KEYS filter.+ if (DANGEROUS_KEYS.has(decodedKey)) {+ continue;+ }+ if (budgetExceeded || ++nodeCount > DECODE_UNICODE_MAX_NODES) {+ budgetExceeded = true;+ obj[decodedKey] = v;+ continue;+ }+ obj[decodedKey] = assignDecodedOrDescend(v, depth, stack);+ }+ }+ }++ return root;+}++function assignDecodedOrDescend(+ v: unknown,+ depth: number,+ stack: Array<{+ source: unknown[] | Record<string, unknown>;+ target: unknown[] | Record<string, unknown>;+ depth: number;+ }>,+): unknown {+ if (typeof v === "string") {+ return decodeUnicodeEscapesOnly(v, true);+ }+ if (v === null || typeof v !== "object") {+ return v;+ }+ if (depth + 1 > DECODE_UNICODE_MAX_DEPTH) {+ return v; // bail on deeper subtrees to avoid runaway work+ }+ const child: unknown[] | Record<string, unknown> = Array.isArray(v) ? [] : {};+ stack.push({+ source: v as unknown[] | Record<string, unknown>,+ target: child,+ depth: depth + 1,+ });+ return child;+}