Skip to content

🪢 Open source agent evals & observability: Trace, evaluate, and improve LLM applications with one open platform.

fix(shared): prevent regex backtracking denial of service (#15891)

Max Deichmann0a83c25b7a9b
diff --git a/packages/shared/src/utils/stringChecks.ts b/packages/shared/src/utils/stringChecks.ts
index 6484c70ec6..5e3a9db448 100644
--- a/packages/shared/src/utils/stringChecks.ts
+++ b/packages/shared/src/utils/stringChecks.ts
@@ -12,7 +12,7 @@ export const VARIABLE_REGEX = /^\p{L}[\p{L}\p{N}_]*$/u;
export const MUSTACHE_REGEX = /{{([^{}]*)}}/g;
// Regex to find multiline variables
-export const MULTILINE_VARIABLE_REGEX = /{{[^{}]*\n[^{}]*}}/g;
+export const MULTILINE_VARIABLE_REGEX = /{{[^{}\n]*\n[^{}]*}}/g;
// Regex to find unclosed variables
export const UNCLOSED_VARIABLE_REGEX = /{{(?!{)(?![^{]*}})/g;
diff --git a/packages/shared/src/utils/zod.ts b/packages/shared/src/utils/zod.ts
index 65f631308b..52d3e5e3c6 100644
--- a/packages/shared/src/utils/zod.ts
+++ b/packages/shared/src/utils/zod.ts
@@ -176,16 +176,43 @@ export const noUrlCheck = (value: string) => !urlRegex.test(value);
export const NonEmptyString = z.string().min(1);
-export const htmlRegex = /<[^>]*>/g;
+export const htmlRegex = /<[^<>]*>/g;
+const containsHtmlRegex = /<[^<>]*>/;
+
+function removeHtmlTags(input: string): string {
+ const parts: string[] = [];
+ let cursor = 0;
+
+ while (cursor < input.length) {
+ const tagStart = input.indexOf("<", cursor);
+ if (tagStart === -1) {
+ parts.push(input.slice(cursor));
+ break;
+ }
-export const StringNoHTML = z.string().refine((val) => !htmlRegex.test(val), {
- message: "Text cannot contain HTML tags",
-});
+ const tagEnd = input.indexOf(">", tagStart + 1);
+ if (tagEnd === -1) {
+ parts.push(input.slice(cursor));
+ break;
+ }
+
+ parts.push(input.slice(cursor, tagStart));
+ cursor = tagEnd + 1;
+ }
+
+ return parts.join("");
+}
+
+export const StringNoHTML = z
+ .string()
+ .refine((val) => !containsHtmlRegex.test(val), {
+ message: "Text cannot contain HTML tags",
+ });
export const StringNoHTMLNonEmpty = z
.string()
.min(1, "Text cannot be empty")
- .refine((val) => !htmlRegex.test(val), {
+ .refine((val) => !containsHtmlRegex.test(val), {
message: "Text cannot contain HTML tags",
});
@@ -246,18 +273,14 @@ export type JSONArray = z.infer<typeof JSONArraySchema>;
* sanitizeEmailSubject("Test<script>alert(1)</script>") // Returns "Testscriptalert(1)/script"
*/
export function sanitizeEmailSubject(input: string): string {
- return (
- input
- // Remove carriage return and line feed (CRLF injection prevention)
- .replace(/[\r\n]/g, "")
- // Remove all control characters (ASCII 0-31 and 127)
- // eslint-disable-next-line no-control-regex
- .replace(/[\x00-\x1F\x7F]/g, "")
- // Remove HTML tags (defensive layer)
- .replace(htmlRegex, "")
- // Trim whitespace
- .trim()
- );
+ const withoutControlCharacters = input
+ // Remove carriage return and line feed (CRLF injection prevention)
+ .replace(/[\r\n]/g, "")
+ // Remove all control characters (ASCII 0-31 and 127)
+ // eslint-disable-next-line no-control-regex
+ .replace(/[\x00-\x1F\x7F]/g, "");
+
+ return removeHtmlTags(withoutControlCharacters).trim();
}
/**
diff --git a/web/src/__tests__/server/zod.servertest.ts b/web/src/__tests__/server/zod.servertest.ts
index 04dd913a42..9c51eb49f8 100644
--- a/web/src/__tests__/server/zod.servertest.ts
+++ b/web/src/__tests__/server/zod.servertest.ts
@@ -5,6 +5,8 @@ import {
paginationZod,
parseJsonPrioritised,
publicApiPaginationLimitZod,
+ sanitizeEmailSubject,
+ StringNoHTML,
} from "@langfuse/shared";
import { ZodError } from "zod";
@@ -129,3 +131,25 @@ describe("isJsonNumberLiteral", () => {
expect(isJsonNumberLiteral("01")).toBe(false);
});
});
+
+describe("StringNoHTML", () => {
+ it("rejects HTML consistently across validation calls", () => {
+ expect(StringNoHTML.safeParse("<b>").success).toBe(false);
+ expect(StringNoHTML.safeParse("<i>").success).toBe(false);
+ });
+
+ it("handles long unterminated tags without excessive backtracking", () => {
+ const input = "<".repeat(50_000);
+ const startedAt = performance.now();
+
+ expect(StringNoHTML.safeParse(input).success).toBe(true);
+ expect(performance.now() - startedAt).toBeLessThan(100);
+ });
+
+ it("removes every HTML tag from email subjects", () => {
+ expect(sanitizeEmailSubject("Project <b>one</b> <i>two</i>")).toBe(
+ "Project one two",
+ );
+ expect(sanitizeEmailSubject("Project <script<script>>")).toBe("Project >");
+ });
+});
diff --git a/web/src/components/editor/CodeMirrorEditor.clienttest.tsx b/web/src/components/editor/CodeMirrorEditor.clienttest.tsx
index fd2b2276c5..ef2449db52 100644
--- a/web/src/components/editor/CodeMirrorEditor.clienttest.tsx
+++ b/web/src/components/editor/CodeMirrorEditor.clienttest.tsx
@@ -15,4 +15,28 @@ describe("getPromptVariableDiagnostics", () => {
}),
]);
});
+
+ it("reports variables spanning multiple lines", () => {
+ expect(
+ getPromptVariableDiagnostics("Use {{first\nsecond\nthird}} here"),
+ ).toContainEqual(
+ expect.objectContaining({
+ from: 4,
+ message: "Variables cannot span multiple lines",
+ }),
+ );
+ });
+
+ it("handles long unterminated multiline variables without excessive backtracking", () => {
+ const content = `{{${"\n".repeat(20_000)}`;
+ const startedAt = performance.now();
+
+ expect(getPromptVariableDiagnostics(content)).toEqual([
+ expect.objectContaining({
+ from: 0,
+ message: "Unclosed variable brackets",
+ }),
+ ]);
+ expect(performance.now() - startedAt).toBeLessThan(100);
+ });
});