Validate and sanitize regular expressions to prevent ReDoS attacks
npm install @philiprehberger/safe-regexValidate and sanitize regular expressions to prevent ReDoS attacks.
npm install @philiprehberger/safe-regex
import { isSafe, safeParse, escape } from '@philiprehberger/safe-regex';
isSafe('abc');
// => true
isSafe('(a+)+');
// => false (nested quantifier — catastrophic backtracking)
const regex = safeParse('abc', 'i');
// => /abc/i
const unsafe = safeParse('(a+)+');
// => null
escape('hello.world');
// => "hello\\.world"
escape('a+b*c?');
// => "a\\+b\\*c\\?"
isSafe(input: string | RegExp): booleanCheck whether a regular expression is safe from ReDoS attacks. Detects nested quantifiers and overlapping alternations that cause catastrophic backtracking.
safeParse(str: string, flags?: string): RegExp | nullCompile a regex string into a RegExp only if it passes safety checks. Returns null if the pattern is unsafe or invalid.
escape(str: string): stringEscape all regex special characters in a string so it can be used as a literal match: . * + ? ^ $ { } ( ) | [ ] \
npm install
npm run build
npm test
If you find this project useful: