resafe
v1.0.3
Published
🛡️ Detects ReDoS vulnerabilities in regexes using Thompson NFA construction and spectral radius analysis
Maintainers
Readme
What is Resafe?
Resafe is a mathematical ReDoS detection engine that uses Thompson NFA construction, epsilon transition elimination, and spectral radius analysis to detect exponential backtracking vulnerabilities. By analyzing the automaton's adjacency matrix eigenvalues, Resafe determines if a regex has exponential growth patterns without executing test strings.
import { check } from "resafe";
check("(a+)+$");
/*
x [Resafe] Unsafe pattern: /(a+)+$/
! Spectral radius: 4.0 (threshold: 1.0)
Simplify regex structure to eliminate exponential paths
*/Features
- Pure Mathematical Analysis: Thompson NFA construction with spectral radius computation
- Deterministic Detection: Analyzes automaton structure, not pattern matching heuristics
- Spectral Radius: Detects exponential growth when eigenvalue > 1.0
- Fast Analysis: Average analysis time <1ms per pattern
Installation
# Using Bun (Recommended)
bun add resafe
# Using NPM
npm install resafe
# Using Yarn
yarn add resafeBasic Usage
Simple Analysis
By default, Resafe logs warnings and errors to the console if a pattern is unsafe.
import { check } from "resafe";
check(/([a-zA-Z0-9]+)*$/);Production Guard
Prevent unsafe regex from being used by throwing an error.
import { check } from "resafe";
const safeRegex = check("^[0-9]+$", {
throwErr: true,
silent: true
});Advanced Configuration
Configure detection threshold.
import { check } from "resafe";
check("a+a+", {
threshold: 1.5
});Why Resafe?
Regular expressions are powerful but can be a security bottleneck. A single poorly crafted regex can freeze a Node.js/Bun event loop. Resafe helps you:
- Educate: Developers learn why a regex is bad through the "Solution" hints.
- Automate: Run checks during CI/CD to catch ReDoS early.
- Secure: Stop malicious or accidental "Catastrophic Backtracking" patterns.
