A 31-character name froze this Node server for 6 seconds
Here's a signup check. A display name is words with single spaces between them. const NAME_RE = /^ (\w + \s?) *$/ ; "Ada Lovelace" passes. "Linus" passes. Each request takes about 3 ms. Then someone signs up as aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa! . That's 30 a's and an exclamation mark. The server takes 5.7 seconds to say "invalid name". And for those 5.7 seconds, it doesn't answer anyone else. The…
The issue at hand involves a Node server freezing for six seconds due to a 31-character display name. The server uses a regular expression to validate the name, which fails to match the excessively long input. This results in the server being unable to answer any other requests during the freezing period.
The regular expression in question is `/^ (\w + \s?) *$/`, which allows for one or more words, each with an optional space after it. The issue arises from the optional space, which allows for multiple ways to match the same text. When the input ends with an exclamation mark, the regular expression fails every time, causing the engine to backtrack through every possible split of the input.
This backtracking leads to an exponential increase in the time it takes to check the input, resulting in a freezing of the server. The problem is not unique to JavaScript; similar issues can occur in other languages with their respective regex engines. The solution is to modify the regular expression so that each character can only be matched one way, preventing the backtracking issue.
In summary, a 31-character display name can freeze a Node server for six seconds due to a regular expression that allows for multiple ways to match the same text. This leads to catastrophic backtracking, causing the server to become unresponsive. The solution is to modify the regular expression to prevent the backtracking issue.
Written by urgent.news from Dev.to's reporting — not their text. Machine-written — may contain errors; check the original before relying on it.