QA
Senior LevelNode JS

How do you defend Node.js APIs against Regular Expression Denial of Service (ReDoS) catastrophic backtracking attacks?

❓ Interview Prompt: Explain ReDoS (Regular Expression Denial of Service), catastrophic backtracking $O(2^N)$, event loop freezing, safe-regex linters, and `re2`.

Catastrophic Backtracking in vulnerable regular expressions (e.g. '/(a+)+$/') takes exponential CPU time $O(2^N)$ on non-matching inputs, freezing the single event loop thread instantly!

Defense:

1
Audit regexes using 'safe-regex' linters.
2
Use 're2' (C++ linear-time regex engine) which guarantees $O(N)$ execution time!

Code Implementation Example

javascript
import RE2 from 're2';

// Linear-time safe regex engine - IMPOSSIBLE to trigger ReDoS!
const safeRegex = new RE2(/(a+)+$/);
console.log(safeRegex.test('aaaaaaaaaaaaaaaaaaaaaaaaaaaaaX')); // Fails fast in O(N)!
💡Defending against ReDoS attacks using the RE2 linear-time regex engine.
🎯 Interview Key Takeaway

Use re2 linear-time regex engine for user-supplied patterns to prevent ReDoS event loop freezing.

#ReDoS#Regex#Security#re2#Senior
Back to all Node JS Questions→

More Node JS Interview Questions

Beginner LevelNode JS

How does the Node.js Event Loop work? Explain the 6 execution phases (Timers, Pending, Poll, Check, Close).

Beginner LevelNode JS

What does 'Single-Threaded, Event-Driven, Non-Blocking I/O' mean in Node.js?

Beginner LevelNode JS

What is the difference between process.nextTick() and setImmediate()?