Why One Regex Freezes Your Node.js Event Loop: Detecting Catastrophic Backtracking (ReDoS)
A single copy-pasted validation regex can pin a Node.js API server at 100% CPU with just one 35-byte request. Because JavaScript's V8 regex engine uses backtracking NFA execution, ambiguous quantifiers can explode into exponential work on non-matching input - a class of bug known as ReDoS (Regular Expression Denial of Service).
Why Valid Tests Pass While One Bad Input Freezes the Server
Consider this common email validation mistake:
// Vulnerable: nested quantifier ([a-zA-Z0-9._-]+)+
const badEmail = /^([a-zA-Z0-9._-]+)+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/;
// Matches instantly on valid input, stalls exponentially on missing '@'
badEmail.test("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa!");
On u***@example.com, the engine succeeds on its first pass, so unit tests stay green. When the trailing @ is missing, V8 backtracks through every possible partition of the as - roughly 2^N steps - blocking the single-threaded event loop for all concurrent users.
Three Patterns Worth Flagging in Code Review
- Nested quantifiers:
(a+)+,([a-z0-9._-]+)+,(.*a){2,} - Overlapping alternation inside repeated groups:
(a|aa)+,(\w|\d)+ - Multiple unbounded wildcards in one expression:
.*.*target
Flattening the group to a single linear character class (^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$) and enforcing a max input length check before invoking .test() eliminates the cliff.
Zero-Dependency CLI & Client-Side Visualizer
I put together a tiny MIT zero-dependency Node.js CLI (redos-lint) to catch these heuristics in CI, plus browser-only regex visualizers that keep your test strings strictly in local memory (0 bytes uploaded):
- Open-Source CLI (
redos-lint, MIT,node --testpassing): https://github.com/JangYS0/redos-lint - Browser Regex Visualizer (0B upload): https://global-utils.com/en/regex-visualizer
- Browser Regex Tester: https://global-utils.com/en/regex-tester
- ReDoS Hardening Toolkit: https://global-utils.com/en/assets/redos-guard-and-regex-hardening-toolkit
Comments
No comments yet. Start the discussion.