From 0848d35195fada87b1fedab0f6a566308a892a6a Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Bastien=20Roucari=C3=A8s?= <rouca@debian.org>
Date: Sat, 28 Jun 2025 22:21:06 +0200
Subject: [PATCH] Avoid a ReDos in string.js

[ ab]+$ is a ReDoS and crash a regression test on debian

forwarded: https://github.com/jsdom/jsdom/pull/3896
---
 lib/jsdom/living/helpers/strings.js | 34 +++++++++++++++++++++++++++--
 1 file changed, 32 insertions(+), 2 deletions(-)

Index: node-jsdom/lib/jsdom/living/helpers/strings.js
===================================================================
--- node-jsdom.orig/lib/jsdom/living/helpers/strings.js	2025-06-28 23:33:35.777608315 +0200
+++ node-jsdom/lib/jsdom/living/helpers/strings.js	2025-06-28 23:33:35.777608315 +0200
@@ -21,12 +21,42 @@
 
 // https://infra.spec.whatwg.org/#strip-leading-and-trailing-ascii-whitespace
 exports.stripLeadingAndTrailingASCIIWhitespace = s => {
-  return s.replace(/^[ \t\n\f\r]+/, "").replace(/[ \t\n\f\r]+$/, "");
+  const beg = s.replace(/^[ \t\n\f\r]+/, "");
+  // replace(/[ \t\n\f\r]+$/, "") without ReDoS
+  let i = beg.length - 1;
+  while (i >= 0) {
+    switch (beg[i]) {
+      case " ":
+      case "\t":
+      case "\n":
+      case "\f":
+      case "\r":
+        i--;
+        continue;
+    }
+    break;
+  }
+  return beg.slice(0, i + 1);
 };
 
 // https://infra.spec.whatwg.org/#strip-and-collapse-ascii-whitespace
 exports.stripAndCollapseASCIIWhitespace = s => {
-  return s.replace(/[ \t\n\f\r]+/g, " ").replace(/^[ \t\n\f\r]+/, "").replace(/[ \t\n\f\r]+$/, "");
+  const beg = s.replace(/[ \t\n\f\r]+/g, " ").replace(/^[ \t\n\f\r]+/, "");
+  // replace(/[ \t\n\f\r]+$/, "") without ReDoS
+  let i = beg.length - 1;
+  while (i >= 0) {
+    switch (beg[i]) {
+      case " ":
+      case "\t":
+      case "\n":
+      case "\f":
+      case "\r":
+        i--;
+        continue;
+    }
+    break;
+  }
+  return beg.slice(0, i + 1);
 };
 
 // https://html.spec.whatwg.org/multipage/infrastructure.html#valid-simple-colour
