Regex Denial of Service (ReDoS) Prevention in Modern JavaScript
A critical security vulnerability affecting Node.js microservices and web applications is Regular Expression Denial of Service (ReDoS). An inefficient regex containing nested quantifiers can trigger Catastrophic Backtracking when fed crafted user input—locking up the single-threaded Event Loop and consuming 100% CPU indefinitely.
1. What is Catastrophic Backtracking?
Regular expression engines use backtracking to try alternative match paths when evaluation fails. If a regex contains ambiguous, overlapping nested quantifiers, the number of potential matching paths grows exponentially ($O(2^n)$):
JavaScript
1// THE VULNERABLE REGEX:
2const evilRegex =/(a+)+$/;
Output
1Input: "aaaaaaaaaaaaaaaaaaaaaaaaaaaa!" (28 'a's followed by exclamation)
2 • Path 1: (a)(a)(a)... fails at '!'
3 • Path 2: (aa)(a)... fails at '!'
4 • Path 3: (a)(aa)... fails at '!'
5 ... The engine evaluates 2^28 (268,435,456) permutations before failing!
6 Result: Node.js main thread freezes for over 4 minutes!