Dev.to Security πŸ” Cybersecurity πŸ‘ 0 πŸ“– 1 min read

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 e

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).

1. 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 [email protected], 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.

2. Three Patterns Worth Flagging in Code Review

  1. Nested quantifiers: (a+)+, ([a-z0-9._-]+)+, (.*a){2,}
  2. Overlapping alternation inside repeated groups: (a|aa)+, (\w|\d)+
  3. 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.

3. 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):

πŸ“° Read the original article on Dev.to Security

Originally published by Dev.to Security. Aggregated on AIWithGhost for educational purposes β€” full credit and traffic to the original publisher.