Skip to content

DeepTutor: Lifelong Personalized Tutoring. https://deeptutor.info/.

fix(chat): strip decoded invisible unicode controls

Bingxi Zhao (Frank)20f95999c317
diff --git a/web/lib/markdown-display.ts b/web/lib/markdown-display.ts
index edcab6d0b..cd6cf6687 100644
--- a/web/lib/markdown-display.ts
+++ b/web/lib/markdown-display.ts
@@ -1,6 +1,7 @@
"use client";
-const ZERO_WIDTH_REGEX = /[\u200B-\u200D\uFEFF]/g;
+const INVISIBLE_CONTROL_REGEX =
+ /[\u200B-\u200F\u202A-\u202E\u2060\u2066-\u2069\uFEFF]/g;
const EMPTY_DETAILS_REGEX =
/<details(?:\s[^>]*)?>\s*(<summary(?:\s[^>]*)?>\s*(?:&nbsp;|\s|<br\s*\/?>)*\s*<\/summary>\s*)?<\/details>/gi;
const EMPTY_SUMMARY_REGEX =
@@ -16,7 +17,7 @@ const EMPTY_HTML_BLOCK_REGEX =
const HTML_TABLE_REGEX = /<table(?:\s[^>]*)?>[\s\S]*?<\/table>/gi;
function stripInvisibleCharacters(value: string): string {
- return value.replace(ZERO_WIDTH_REGEX, "");
+ return value.replace(INVISIBLE_CONTROL_REGEX, "");
}
// Tags that the renderer (rehype-raw + react-markdown) is allowed to render
@@ -668,8 +669,8 @@ function decodeEscapedUnicodeRun(escaped: string): string {
export function normalizeMarkdownForDisplay(content: string): string {
if (!content) return "";
- const normalized = decodeEscapedUnicodeRuns(
- stripInvisibleCharacters(String(content)).replace(/\r\n/g, "\n"),
+ const normalized = stripInvisibleCharacters(
+ decodeEscapedUnicodeRuns(String(content).replace(/\r\n/g, "\n")),
)
.replace(EMPTY_DETAILS_REGEX, "")
.replace(EMPTY_SUMMARY_REGEX, "")
diff --git a/web/tests/markdown-display.test.ts b/web/tests/markdown-display.test.ts
index c714eaff8..a30557490 100644
--- a/web/tests/markdown-display.test.ts
+++ b/web/tests/markdown-display.test.ts
@@ -90,6 +90,17 @@ test("normalizeMarkdownForDisplay decodes dense non-ASCII JSON escapes", () => {
assert.equal(normalizeMarkdownForDisplay(input), "「数制转换」");
});
+test("decoded unicode cannot reintroduce invisible or bidi controls", () => {
+ assert.equal(
+ normalizeMarkdownForDisplay("\\u200b\\u4e2d\\u6587"),
+ "中文",
+ );
+ assert.equal(
+ normalizeMarkdownForDisplay("\\u202e\\u0061\\u0062"),
+ "ab",
+ );
+});
+
test("normalizeMarkdownForDisplay keeps isolated and ASCII unicode escape examples", () => {
const inputs = [
"A JSON string can encode A as \\u0041.",