@theunwalked/pressurelid 1.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +191 -0
- package/README.md +178 -0
- package/dist/analyze.d.ts +13 -0
- package/dist/analyze.js +109 -0
- package/dist/analyze.js.map +1 -0
- package/dist/pressurelid.cjs +309 -0
- package/dist/pressurelid.cjs.map +1 -0
- package/dist/pressurelid.d.ts +5 -0
- package/dist/pressurelid.js +8 -0
- package/dist/pressurelid.js.map +1 -0
- package/dist/safe-regex.d.ts +80 -0
- package/dist/safe-regex.js +182 -0
- package/dist/safe-regex.js.map +1 -0
- package/dist/types.d.ts +44 -0
- package/dist/types.js +12 -0
- package/dist/types.js.map +1 -0
- package/package.json +70 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,191 @@
|
|
|
1
|
+
Apache License
|
|
2
|
+
Version 2.0, January 2004
|
|
3
|
+
http://www.apache.org/licenses/
|
|
4
|
+
|
|
5
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
6
|
+
|
|
7
|
+
1. Definitions.
|
|
8
|
+
|
|
9
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
10
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
11
|
+
|
|
12
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
13
|
+
the copyright owner that is granting the License.
|
|
14
|
+
|
|
15
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
16
|
+
other entities that control, are controlled by, or are under common
|
|
17
|
+
control with that entity. For the purposes of this definition,
|
|
18
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
19
|
+
direction or management of such entity, whether by contract or
|
|
20
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
21
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
22
|
+
|
|
23
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
24
|
+
exercising permissions granted by this License.
|
|
25
|
+
|
|
26
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
27
|
+
including but not limited to software source code, documentation
|
|
28
|
+
source, and configuration files.
|
|
29
|
+
|
|
30
|
+
"Object" form shall mean any form resulting from mechanical
|
|
31
|
+
transformation or translation of a Source form, including but
|
|
32
|
+
not limited to compiled object code, generated documentation,
|
|
33
|
+
and conversions to other media types.
|
|
34
|
+
|
|
35
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
36
|
+
Object form, made available under the License, as indicated by a
|
|
37
|
+
copyright notice that is included in or attached to the work
|
|
38
|
+
(an example is provided in the Appendix below).
|
|
39
|
+
|
|
40
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
41
|
+
form, that is based on (or derived from) the Work and for which the
|
|
42
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
43
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
44
|
+
of this License, Derivative Works shall not include works that remain
|
|
45
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
46
|
+
the Work and Derivative Works thereof.
|
|
47
|
+
|
|
48
|
+
"Contribution" shall mean any work of authorship, including
|
|
49
|
+
the original version of the Work and any modifications or additions
|
|
50
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
51
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
52
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
53
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
54
|
+
means any form of electronic, verbal, or written communication sent
|
|
55
|
+
to the Licensor or its representatives, including but not limited to
|
|
56
|
+
communication on electronic mailing lists, source code control systems,
|
|
57
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
58
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
59
|
+
excluding communication that is conspicuously marked or otherwise
|
|
60
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
61
|
+
|
|
62
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
63
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
64
|
+
subsequently incorporated within the Work.
|
|
65
|
+
|
|
66
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
67
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
68
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
69
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
70
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
71
|
+
Work and such Derivative Works in Source or Object form.
|
|
72
|
+
|
|
73
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
74
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
75
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
76
|
+
(except as stated in this section) patent license to make, have made,
|
|
77
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
78
|
+
where such license applies only to those patent claims licensable
|
|
79
|
+
by such Contributor that are necessarily infringed by their
|
|
80
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
81
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
82
|
+
institute patent litigation against any entity (including a
|
|
83
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
84
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
85
|
+
or contributory patent infringement, then any patent licenses
|
|
86
|
+
granted to You under this License for that Work shall terminate
|
|
87
|
+
as of the date such litigation is filed.
|
|
88
|
+
|
|
89
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
90
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
91
|
+
modifications, and in Source or Object form, provided that You
|
|
92
|
+
meet the following conditions:
|
|
93
|
+
|
|
94
|
+
(a) You must give any other recipients of the Work or
|
|
95
|
+
Derivative Works a copy of this License; and
|
|
96
|
+
|
|
97
|
+
(b) You must cause any modified files to carry prominent notices
|
|
98
|
+
stating that You changed the files; and
|
|
99
|
+
|
|
100
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
101
|
+
that You distribute, all copyright, patent, trademark, and
|
|
102
|
+
attribution notices from the Source form of the Work,
|
|
103
|
+
excluding those notices that do not pertain to any part of
|
|
104
|
+
the Derivative Works; and
|
|
105
|
+
|
|
106
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
107
|
+
distribution, then any Derivative Works that You distribute must
|
|
108
|
+
include a readable copy of the attribution notices contained
|
|
109
|
+
within such NOTICE file, excluding those notices that do not
|
|
110
|
+
pertain to any part of the Derivative Works, in at least one
|
|
111
|
+
of the following places: within a NOTICE text file distributed
|
|
112
|
+
as part of the Derivative Works; within the Source form or
|
|
113
|
+
documentation, if provided along with the Derivative Works; or,
|
|
114
|
+
within a display generated by the Derivative Works, if and
|
|
115
|
+
wherever such third-party notices normally appear. The contents
|
|
116
|
+
of the NOTICE file are for informational purposes only and
|
|
117
|
+
do not modify the License. You may add Your own attribution
|
|
118
|
+
notices within Derivative Works that You distribute, alongside
|
|
119
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
120
|
+
that such additional attribution notices cannot be construed
|
|
121
|
+
as modifying the License.
|
|
122
|
+
|
|
123
|
+
You may add Your own copyright statement to Your modifications and
|
|
124
|
+
may provide additional or different license terms and conditions
|
|
125
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
126
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
127
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
128
|
+
the conditions stated in this License.
|
|
129
|
+
|
|
130
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
131
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
132
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
133
|
+
this License, without any additional terms or conditions.
|
|
134
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
135
|
+
the terms of any separate license agreement you may have executed
|
|
136
|
+
with Licensor regarding such Contributions.
|
|
137
|
+
|
|
138
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
139
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
140
|
+
except as required for reasonable and customary use in describing the
|
|
141
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
142
|
+
|
|
143
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
144
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
145
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
146
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
147
|
+
implied, including, without limitation, any warranties or conditions
|
|
148
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
149
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
150
|
+
appropriateness of using or redistributing the Work and assume any
|
|
151
|
+
risks associated with Your exercise of permissions under this License.
|
|
152
|
+
|
|
153
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
154
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
155
|
+
unless required by applicable law (such as deliberate and grossly
|
|
156
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
157
|
+
liable to You for damages, including any direct, indirect, special,
|
|
158
|
+
incidental, or consequential damages of any character arising as a
|
|
159
|
+
result of this License or out of the use or inability to use the
|
|
160
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
161
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
162
|
+
other commercial damages or losses), even if such Contributor
|
|
163
|
+
has been advised of the possibility of such damages.
|
|
164
|
+
|
|
165
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
166
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
167
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
168
|
+
or other liability obligations and/or rights consistent with this
|
|
169
|
+
License. However, in accepting such obligations, You may act only
|
|
170
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
171
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
172
|
+
defend, and hold each Contributor harmless for any liability
|
|
173
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
174
|
+
of your accepting any such warranty or additional liability.
|
|
175
|
+
|
|
176
|
+
END OF TERMS AND CONDITIONS
|
|
177
|
+
|
|
178
|
+
Copyright 2026 Tim O'Brien
|
|
179
|
+
|
|
180
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
181
|
+
you may not use this file except in compliance with the License.
|
|
182
|
+
You may obtain a copy of the License at
|
|
183
|
+
|
|
184
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
185
|
+
|
|
186
|
+
Unless required by applicable law or agreed to in writing, software
|
|
187
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
188
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
189
|
+
See the License for the specific language governing permissions and
|
|
190
|
+
limitations under the License.
|
|
191
|
+
|
package/README.md
ADDED
|
@@ -0,0 +1,178 @@
|
|
|
1
|
+
# @theunwalked/pressurelid
|
|
2
|
+
|
|
3
|
+
Safe regex handling with ReDoS protection. Keeps dangerous patterns under pressure.
|
|
4
|
+
|
|
5
|
+
[](https://www.npmjs.com/package/@theunwalked/pressurelid)
|
|
6
|
+
[](LICENSE)
|
|
7
|
+
|
|
8
|
+
## Why pressurelid?
|
|
9
|
+
|
|
10
|
+
Regular expressions are powerful but dangerous. User-provided patterns can freeze your application via **ReDoS (Regular Expression Denial of Service)** attacks. `pressurelid` provides:
|
|
11
|
+
|
|
12
|
+
- 🔍 **Pattern Analysis** - Detects dangerous regex constructs before execution
|
|
13
|
+
- ⏱️ **Timeout Protection** - Limits execution time for regex operations
|
|
14
|
+
- 🔒 **Safe Conversions** - Safely converts glob patterns and user input
|
|
15
|
+
- ⚙️ **Configurable** - Tune limits and callbacks for your use case
|
|
16
|
+
|
|
17
|
+
## Installation
|
|
18
|
+
|
|
19
|
+
```bash
|
|
20
|
+
npm install @theunwalked/pressurelid
|
|
21
|
+
```
|
|
22
|
+
|
|
23
|
+
## Quick Start
|
|
24
|
+
|
|
25
|
+
```typescript
|
|
26
|
+
import { SafeRegex, createSafeRegex, globToSafeRegex } from '@theunwalked/pressurelid';
|
|
27
|
+
|
|
28
|
+
// Basic usage
|
|
29
|
+
const safe = new SafeRegex();
|
|
30
|
+
const result = safe.create(userPattern);
|
|
31
|
+
|
|
32
|
+
if (result.safe && result.regex) {
|
|
33
|
+
result.regex.test(input);
|
|
34
|
+
} else {
|
|
35
|
+
console.error('Unsafe pattern:', result.error);
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
// Convenience function
|
|
39
|
+
const { safe: isSafe, regex, error } = createSafeRegex('^[a-z]+$');
|
|
40
|
+
|
|
41
|
+
// Convert glob patterns safely
|
|
42
|
+
const globResult = globToSafeRegex('**/*.md');
|
|
43
|
+
```
|
|
44
|
+
|
|
45
|
+
## API
|
|
46
|
+
|
|
47
|
+
### `SafeRegex` Class
|
|
48
|
+
|
|
49
|
+
```typescript
|
|
50
|
+
const safe = new SafeRegex({
|
|
51
|
+
maxLength: 500, // Maximum pattern length (default: 500)
|
|
52
|
+
timeoutMs: 1000, // Execution timeout in ms (default: 1000)
|
|
53
|
+
onBlock: (msg, pattern) => {}, // Called when pattern is blocked
|
|
54
|
+
onWarning: (msg, pattern) => {}, // Called on warnings
|
|
55
|
+
});
|
|
56
|
+
```
|
|
57
|
+
|
|
58
|
+
#### `create(pattern: string, flags?: string): SafeRegexResult`
|
|
59
|
+
|
|
60
|
+
Create a regex with safety checks.
|
|
61
|
+
|
|
62
|
+
```typescript
|
|
63
|
+
const result = safe.create('^hello$', 'i');
|
|
64
|
+
// { safe: true, regex: /^hello$/i, reason: 'ok' }
|
|
65
|
+
|
|
66
|
+
const badResult = safe.create('^(a+)+$');
|
|
67
|
+
// { safe: false, error: '...', reason: 'nested_quantifiers' }
|
|
68
|
+
```
|
|
69
|
+
|
|
70
|
+
#### `testWithTimeout(regex: RegExp, input: string): Promise<boolean>`
|
|
71
|
+
|
|
72
|
+
Execute `regex.test()` with timeout protection.
|
|
73
|
+
|
|
74
|
+
```typescript
|
|
75
|
+
try {
|
|
76
|
+
const matches = await safe.testWithTimeout(/pattern/, 'input');
|
|
77
|
+
} catch (e) {
|
|
78
|
+
// Timed out
|
|
79
|
+
}
|
|
80
|
+
```
|
|
81
|
+
|
|
82
|
+
#### `globToRegex(glob: string): SafeRegexResult`
|
|
83
|
+
|
|
84
|
+
Convert glob pattern to safe regex.
|
|
85
|
+
|
|
86
|
+
```typescript
|
|
87
|
+
const result = safe.globToRegex('*.{ts,tsx}');
|
|
88
|
+
result.regex?.test('file.ts'); // true
|
|
89
|
+
```
|
|
90
|
+
|
|
91
|
+
#### `fromUserInput(input: string): SafeRegexResult`
|
|
92
|
+
|
|
93
|
+
Escape user input for literal matching.
|
|
94
|
+
|
|
95
|
+
```typescript
|
|
96
|
+
const result = safe.fromUserInput('file (1).txt');
|
|
97
|
+
result.regex?.test('file (1).txt'); // true
|
|
98
|
+
```
|
|
99
|
+
|
|
100
|
+
### Convenience Functions
|
|
101
|
+
|
|
102
|
+
```typescript
|
|
103
|
+
// Create safe regex with defaults
|
|
104
|
+
const result = createSafeRegex(pattern, flags);
|
|
105
|
+
|
|
106
|
+
// Convert glob with defaults
|
|
107
|
+
const result = globToSafeRegex(glob);
|
|
108
|
+
|
|
109
|
+
// Escape string for regex
|
|
110
|
+
const escaped = escapeForRegex('a.b*c'); // 'a\\.b\\*c'
|
|
111
|
+
```
|
|
112
|
+
|
|
113
|
+
### Result Types
|
|
114
|
+
|
|
115
|
+
```typescript
|
|
116
|
+
interface SafeRegexResult {
|
|
117
|
+
safe: boolean; // Was the pattern deemed safe?
|
|
118
|
+
regex?: RegExp; // The compiled regex (if safe)
|
|
119
|
+
error?: string; // Error message (if not safe)
|
|
120
|
+
reason?: SafeRegexReason; // Machine-readable reason code
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
type SafeRegexReason =
|
|
124
|
+
| 'ok'
|
|
125
|
+
| 'pattern_too_long'
|
|
126
|
+
| 'nested_quantifiers'
|
|
127
|
+
| 'overlapping_alternation'
|
|
128
|
+
| 'catastrophic_backtracking'
|
|
129
|
+
| 'invalid_syntax'
|
|
130
|
+
| 'execution_timeout';
|
|
131
|
+
```
|
|
132
|
+
|
|
133
|
+
## Patterns Detected
|
|
134
|
+
|
|
135
|
+
`pressurelid` detects these dangerous patterns:
|
|
136
|
+
|
|
137
|
+
| Pattern Type | Example | Risk |
|
|
138
|
+
|-------------|---------|------|
|
|
139
|
+
| Nested quantifiers | `(a+)+` | Exponential backtracking |
|
|
140
|
+
| Overlapping alternation | `(a\|ab)+` | Polynomial backtracking |
|
|
141
|
+
| Repeated groups | `(.*a){20}` | Catastrophic backtracking |
|
|
142
|
+
| Deep nesting | `((a+)+)+` | Exponential backtracking |
|
|
143
|
+
|
|
144
|
+
## Limitations
|
|
145
|
+
|
|
146
|
+
### Static Analysis
|
|
147
|
+
|
|
148
|
+
Static analysis cannot catch all ReDoS patterns. Some limitations:
|
|
149
|
+
|
|
150
|
+
- Novel attack patterns may not be detected
|
|
151
|
+
- Some safe patterns may be incorrectly flagged (false positives)
|
|
152
|
+
- Complex patterns may evade detection
|
|
153
|
+
|
|
154
|
+
Always use `testWithTimeout()` for runtime protection.
|
|
155
|
+
|
|
156
|
+
### Timeout Behavior
|
|
157
|
+
|
|
158
|
+
JavaScript regex execution is synchronous and cannot be truly interrupted. The timeout:
|
|
159
|
+
|
|
160
|
+
1. Starts a timer
|
|
161
|
+
2. Executes the regex
|
|
162
|
+
3. Rejects the promise if timer fires first
|
|
163
|
+
|
|
164
|
+
The regex continues running in the background until completion. For truly interruptible execution, consider the `re2` package.
|
|
165
|
+
|
|
166
|
+
## Alternatives
|
|
167
|
+
|
|
168
|
+
| Package | Approach | Pros | Cons |
|
|
169
|
+
|---------|----------|------|------|
|
|
170
|
+
| `pressurelid` | Static analysis + timeout | Fast, no native deps | Cannot interrupt |
|
|
171
|
+
| `safe-regex` | Backtracking estimation | Simple | High false positives |
|
|
172
|
+
| `safe-regex2` | AST analysis | Thorough | More complex |
|
|
173
|
+
| `re2` | Native RE2 engine | Truly safe | Native dependency |
|
|
174
|
+
|
|
175
|
+
## License
|
|
176
|
+
|
|
177
|
+
Apache-2.0
|
|
178
|
+
TEST
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import { PatternAnalysis } from './types';
|
|
2
|
+
/**
|
|
3
|
+
* Analyze a regex pattern for potential ReDoS vulnerabilities.
|
|
4
|
+
*
|
|
5
|
+
* This performs static analysis only - it cannot catch all dangerous patterns.
|
|
6
|
+
* Use testWithTimeout() for runtime protection.
|
|
7
|
+
*/
|
|
8
|
+
export declare function analyzePattern(pattern: string): PatternAnalysis;
|
|
9
|
+
/**
|
|
10
|
+
* Check if a pattern is likely safe without full analysis.
|
|
11
|
+
* Use for quick rejection of obviously safe patterns.
|
|
12
|
+
*/
|
|
13
|
+
export declare function quickSafetyCheck(pattern: string): boolean;
|
package/dist/analyze.js
ADDED
|
@@ -0,0 +1,109 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Patterns known to cause exponential backtracking
|
|
3
|
+
*/ const DANGEROUS_PATTERNS = [
|
|
4
|
+
{
|
|
5
|
+
// Nested quantifiers: (a+)+, (a*)+, etc.
|
|
6
|
+
regex: /\([^)]*[+*][^)]*\)[+*]/,
|
|
7
|
+
reason: 'nested_quantifiers',
|
|
8
|
+
message: 'Pattern contains nested quantifiers which can cause exponential backtracking'
|
|
9
|
+
},
|
|
10
|
+
{
|
|
11
|
+
// Overlapping alternations with quantifiers: (a|ab)+
|
|
12
|
+
regex: /\([^)]*\|[^)]*\)[+*]/,
|
|
13
|
+
reason: 'overlapping_alternation',
|
|
14
|
+
message: 'Pattern contains alternation with quantifier which may cause backtracking'
|
|
15
|
+
},
|
|
16
|
+
{
|
|
17
|
+
// Repeated groups: (a+){n} followed by quantifier
|
|
18
|
+
regex: /\([^)]+\)\{[0-9,]+\}[+*]?/,
|
|
19
|
+
reason: 'catastrophic_backtracking',
|
|
20
|
+
message: 'Pattern contains repeated group which may cause backtracking'
|
|
21
|
+
},
|
|
22
|
+
{
|
|
23
|
+
// Deeply nested groups with quantifiers
|
|
24
|
+
regex: /\([^)]*\([^)]*[+*]\)[^)]*[+*]\)/,
|
|
25
|
+
reason: 'nested_quantifiers',
|
|
26
|
+
message: 'Pattern contains deeply nested quantifiers'
|
|
27
|
+
},
|
|
28
|
+
{
|
|
29
|
+
// Character class with quantifier followed by similar class
|
|
30
|
+
regex: /\[[^\]]+\][+*]\[[^\]]+\][+*]/,
|
|
31
|
+
reason: 'catastrophic_backtracking',
|
|
32
|
+
message: 'Pattern contains overlapping character classes with quantifiers'
|
|
33
|
+
}
|
|
34
|
+
];
|
|
35
|
+
/**
|
|
36
|
+
* Analyze a regex pattern for potential ReDoS vulnerabilities.
|
|
37
|
+
*
|
|
38
|
+
* This performs static analysis only - it cannot catch all dangerous patterns.
|
|
39
|
+
* Use testWithTimeout() for runtime protection.
|
|
40
|
+
*/ function analyzePattern(pattern) {
|
|
41
|
+
for (const dangerous of DANGEROUS_PATTERNS){
|
|
42
|
+
if (dangerous.regex.test(pattern)) {
|
|
43
|
+
return {
|
|
44
|
+
safe: false,
|
|
45
|
+
reason: dangerous.reason,
|
|
46
|
+
message: dangerous.message
|
|
47
|
+
};
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
// Check for excessive quantifier nesting depth
|
|
51
|
+
const nestingDepth = countQuantifierNesting(pattern);
|
|
52
|
+
if (nestingDepth > 2) {
|
|
53
|
+
return {
|
|
54
|
+
safe: false,
|
|
55
|
+
reason: 'nested_quantifiers',
|
|
56
|
+
message: `Pattern has excessive quantifier nesting depth (${nestingDepth})`
|
|
57
|
+
};
|
|
58
|
+
}
|
|
59
|
+
return {
|
|
60
|
+
safe: true,
|
|
61
|
+
reason: 'ok'
|
|
62
|
+
};
|
|
63
|
+
}
|
|
64
|
+
/**
|
|
65
|
+
* Count the nesting depth of quantifiers in a pattern.
|
|
66
|
+
*/ function countQuantifierNesting(pattern) {
|
|
67
|
+
let maxDepth = 0;
|
|
68
|
+
let currentDepth = 0;
|
|
69
|
+
let inGroup = 0;
|
|
70
|
+
for(let i = 0; i < pattern.length; i++){
|
|
71
|
+
const char = pattern[i];
|
|
72
|
+
const prev = pattern[i - 1];
|
|
73
|
+
// Track group depth
|
|
74
|
+
if (char === '(' && prev !== '\\') {
|
|
75
|
+
inGroup++;
|
|
76
|
+
} else if (char === ')' && prev !== '\\') {
|
|
77
|
+
inGroup = Math.max(0, inGroup - 1);
|
|
78
|
+
}
|
|
79
|
+
// Track quantifiers
|
|
80
|
+
if ((char === '+' || char === '*' || char === '?') && prev !== '\\') {
|
|
81
|
+
if (inGroup > 0) {
|
|
82
|
+
currentDepth = inGroup;
|
|
83
|
+
maxDepth = Math.max(maxDepth, currentDepth);
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
return maxDepth;
|
|
88
|
+
}
|
|
89
|
+
/**
|
|
90
|
+
* Check if a pattern is likely safe without full analysis.
|
|
91
|
+
* Use for quick rejection of obviously safe patterns.
|
|
92
|
+
*/ function quickSafetyCheck(pattern) {
|
|
93
|
+
// No quantifiers = safe
|
|
94
|
+
if (!/[+*?]/.test(pattern)) {
|
|
95
|
+
return true;
|
|
96
|
+
}
|
|
97
|
+
// No groups = generally safe
|
|
98
|
+
if (!/[()]/.test(pattern)) {
|
|
99
|
+
return true;
|
|
100
|
+
}
|
|
101
|
+
// Simple anchored patterns are usually safe
|
|
102
|
+
if (/^\^[^+*?()]+\$$/.test(pattern)) {
|
|
103
|
+
return true;
|
|
104
|
+
}
|
|
105
|
+
return false;
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
export { analyzePattern, quickSafetyCheck };
|
|
109
|
+
//# sourceMappingURL=analyze.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"analyze.js","sources":["../src/analyze.ts"],"sourcesContent":["import { PatternAnalysis, SafeRegexReason } from './types';\n\n/**\n * Patterns known to cause exponential backtracking\n */\nconst DANGEROUS_PATTERNS: Array<{ regex: RegExp; reason: SafeRegexReason; message: string }> = [\n {\n // Nested quantifiers: (a+)+, (a*)+, etc.\n regex: /\\([^)]*[+*][^)]*\\)[+*]/,\n reason: 'nested_quantifiers',\n message: 'Pattern contains nested quantifiers which can cause exponential backtracking',\n },\n {\n // Overlapping alternations with quantifiers: (a|ab)+\n regex: /\\([^)]*\\|[^)]*\\)[+*]/,\n reason: 'overlapping_alternation',\n message: 'Pattern contains alternation with quantifier which may cause backtracking',\n },\n {\n // Repeated groups: (a+){n} followed by quantifier\n regex: /\\([^)]+\\)\\{[0-9,]+\\}[+*]?/,\n reason: 'catastrophic_backtracking',\n message: 'Pattern contains repeated group which may cause backtracking',\n },\n {\n // Deeply nested groups with quantifiers\n regex: /\\([^)]*\\([^)]*[+*]\\)[^)]*[+*]\\)/,\n reason: 'nested_quantifiers',\n message: 'Pattern contains deeply nested quantifiers',\n },\n {\n // Character class with quantifier followed by similar class\n regex: /\\[[^\\]]+\\][+*]\\[[^\\]]+\\][+*]/,\n reason: 'catastrophic_backtracking',\n message: 'Pattern contains overlapping character classes with quantifiers',\n },\n];\n\n/**\n * Analyze a regex pattern for potential ReDoS vulnerabilities.\n * \n * This performs static analysis only - it cannot catch all dangerous patterns.\n * Use testWithTimeout() for runtime protection.\n */\nexport function analyzePattern(pattern: string): PatternAnalysis {\n for (const dangerous of DANGEROUS_PATTERNS) {\n if (dangerous.regex.test(pattern)) {\n return {\n safe: false,\n reason: dangerous.reason,\n message: dangerous.message,\n };\n }\n }\n\n // Check for excessive quantifier nesting depth\n const nestingDepth = countQuantifierNesting(pattern);\n if (nestingDepth > 2) {\n return {\n safe: false,\n reason: 'nested_quantifiers',\n message: `Pattern has excessive quantifier nesting depth (${nestingDepth})`,\n };\n }\n\n return { safe: true, reason: 'ok' };\n}\n\n/**\n * Count the nesting depth of quantifiers in a pattern.\n */\nfunction countQuantifierNesting(pattern: string): number {\n let maxDepth = 0;\n let currentDepth = 0;\n let inGroup = 0;\n\n for (let i = 0; i < pattern.length; i++) {\n const char = pattern[i];\n const prev = pattern[i - 1];\n\n // Track group depth\n if (char === '(' && prev !== '\\\\') {\n inGroup++;\n } else if (char === ')' && prev !== '\\\\') {\n inGroup = Math.max(0, inGroup - 1);\n }\n\n // Track quantifiers\n if ((char === '+' || char === '*' || char === '?') && prev !== '\\\\') {\n if (inGroup > 0) {\n currentDepth = inGroup;\n maxDepth = Math.max(maxDepth, currentDepth);\n }\n }\n }\n\n return maxDepth;\n}\n\n/**\n * Check if a pattern is likely safe without full analysis.\n * Use for quick rejection of obviously safe patterns.\n */\nexport function quickSafetyCheck(pattern: string): boolean {\n // No quantifiers = safe\n if (!/[+*?]/.test(pattern)) {\n return true;\n }\n\n // No groups = generally safe\n if (!/[()]/.test(pattern)) {\n return true;\n }\n\n // Simple anchored patterns are usually safe\n if (/^\\^[^+*?()]+\\$$/.test(pattern)) {\n return true;\n }\n\n return false;\n}\n\n"],"names":["DANGEROUS_PATTERNS","regex","reason","message","analyzePattern","pattern","dangerous","test","safe","nestingDepth","countQuantifierNesting","maxDepth","currentDepth","inGroup","i","length","char","prev","Math","max","quickSafetyCheck"],"mappings":"AAEA;;AAEC,IACD,MAAMA,kBAAAA,GAAyF;AAC3F,IAAA;;QAEIC,KAAAA,EAAO,wBAAA;QACPC,MAAAA,EAAQ,oBAAA;QACRC,OAAAA,EAAS;AACb,KAAA;AACA,IAAA;;QAEIF,KAAAA,EAAO,sBAAA;QACPC,MAAAA,EAAQ,yBAAA;QACRC,OAAAA,EAAS;AACb,KAAA;AACA,IAAA;;QAEIF,KAAAA,EAAO,2BAAA;QACPC,MAAAA,EAAQ,2BAAA;QACRC,OAAAA,EAAS;AACb,KAAA;AACA,IAAA;;QAEIF,KAAAA,EAAO,iCAAA;QACPC,MAAAA,EAAQ,oBAAA;QACRC,OAAAA,EAAS;AACb,KAAA;AACA,IAAA;;QAEIF,KAAAA,EAAO,8BAAA;QACPC,MAAAA,EAAQ,2BAAA;QACRC,OAAAA,EAAS;AACb;AACH,CAAA;AAED;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AA,OAAAA,GAAUK,IAAAA,CAAKC,GAAG,CAAC,CAAA,EAAGN,OAAAA,GAAU,CAAA,CAAA;AACpC,QAAA;;QAGA,IAAKG,CAAAA,IAAAA,KAAS,GAAA,IAAOA,IAAAA,KAAS,OAAOA,IAAAA,KAAS,GAAE,KAAMC,IAAAA,KAAS,IAAA,EAAM;AACjE,YAAA,IAAIJ,UAAU,CAAA,EAAG;gBACbD,YAAAA,GAAeC,OAAAA;gBACfF,QAAAA,GAAWO,IAAAA,CAAKC,GAAG,CAACR,QAAAA,EAAUC,YAAAA,CAAAA;AAClC,YAAA;AACJ,QAAA;AACJ,IAAA;IAEA,OAAOD,QAAAA;AACX;AAEA;;;IAIO,SAASS,gBAAAA,CAAiBf,OAAe,EAAA;;AAE5C,IAAA,IAAI,CAAC,OAAA,CAAQE,IAAI,CAACF,OAAAA,CAAAA,EAAU;QACxB,OAAO,IAAA;AACX,IAAA;;AAGA,IAAA,IAAI,CAAC,MAAA,CAAOE,IAAI,CAACF,OAAAA,CAAAA,EAAU;QACvB,OAAO,IAAA;AACX,IAAA;;IAGA,IAAI,iBAAA,CAAkBE,IAAI,CAACF,OAAAA,CAAAA,EAAU;QACjC,OAAO,IAAA;AACX,IAAA;IAEA,OAAO,KAAA;AACX;;;;"}
|
|
@@ -0,0 +1,309 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* Configuration for SafeRegex behavior
|
|
7
|
+
*/ /**
|
|
8
|
+
* Default configuration with secure defaults
|
|
9
|
+
*/ const DEFAULT_CONFIG = {
|
|
10
|
+
maxLength: 500,
|
|
11
|
+
timeoutMs: 1000,
|
|
12
|
+
maxBacktrackDepth: 100000
|
|
13
|
+
};
|
|
14
|
+
|
|
15
|
+
/**
|
|
16
|
+
* Patterns known to cause exponential backtracking
|
|
17
|
+
*/ const DANGEROUS_PATTERNS = [
|
|
18
|
+
{
|
|
19
|
+
// Nested quantifiers: (a+)+, (a*)+, etc.
|
|
20
|
+
regex: /\([^)]*[+*][^)]*\)[+*]/,
|
|
21
|
+
reason: 'nested_quantifiers',
|
|
22
|
+
message: 'Pattern contains nested quantifiers which can cause exponential backtracking'
|
|
23
|
+
},
|
|
24
|
+
{
|
|
25
|
+
// Overlapping alternations with quantifiers: (a|ab)+
|
|
26
|
+
regex: /\([^)]*\|[^)]*\)[+*]/,
|
|
27
|
+
reason: 'overlapping_alternation',
|
|
28
|
+
message: 'Pattern contains alternation with quantifier which may cause backtracking'
|
|
29
|
+
},
|
|
30
|
+
{
|
|
31
|
+
// Repeated groups: (a+){n} followed by quantifier
|
|
32
|
+
regex: /\([^)]+\)\{[0-9,]+\}[+*]?/,
|
|
33
|
+
reason: 'catastrophic_backtracking',
|
|
34
|
+
message: 'Pattern contains repeated group which may cause backtracking'
|
|
35
|
+
},
|
|
36
|
+
{
|
|
37
|
+
// Deeply nested groups with quantifiers
|
|
38
|
+
regex: /\([^)]*\([^)]*[+*]\)[^)]*[+*]\)/,
|
|
39
|
+
reason: 'nested_quantifiers',
|
|
40
|
+
message: 'Pattern contains deeply nested quantifiers'
|
|
41
|
+
},
|
|
42
|
+
{
|
|
43
|
+
// Character class with quantifier followed by similar class
|
|
44
|
+
regex: /\[[^\]]+\][+*]\[[^\]]+\][+*]/,
|
|
45
|
+
reason: 'catastrophic_backtracking',
|
|
46
|
+
message: 'Pattern contains overlapping character classes with quantifiers'
|
|
47
|
+
}
|
|
48
|
+
];
|
|
49
|
+
/**
|
|
50
|
+
* Analyze a regex pattern for potential ReDoS vulnerabilities.
|
|
51
|
+
*
|
|
52
|
+
* This performs static analysis only - it cannot catch all dangerous patterns.
|
|
53
|
+
* Use testWithTimeout() for runtime protection.
|
|
54
|
+
*/ function analyzePattern(pattern) {
|
|
55
|
+
for (const dangerous of DANGEROUS_PATTERNS){
|
|
56
|
+
if (dangerous.regex.test(pattern)) {
|
|
57
|
+
return {
|
|
58
|
+
safe: false,
|
|
59
|
+
reason: dangerous.reason,
|
|
60
|
+
message: dangerous.message
|
|
61
|
+
};
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
// Check for excessive quantifier nesting depth
|
|
65
|
+
const nestingDepth = countQuantifierNesting(pattern);
|
|
66
|
+
if (nestingDepth > 2) {
|
|
67
|
+
return {
|
|
68
|
+
safe: false,
|
|
69
|
+
reason: 'nested_quantifiers',
|
|
70
|
+
message: `Pattern has excessive quantifier nesting depth (${nestingDepth})`
|
|
71
|
+
};
|
|
72
|
+
}
|
|
73
|
+
return {
|
|
74
|
+
safe: true,
|
|
75
|
+
reason: 'ok'
|
|
76
|
+
};
|
|
77
|
+
}
|
|
78
|
+
/**
|
|
79
|
+
* Count the nesting depth of quantifiers in a pattern.
|
|
80
|
+
*/ function countQuantifierNesting(pattern) {
|
|
81
|
+
let maxDepth = 0;
|
|
82
|
+
let currentDepth = 0;
|
|
83
|
+
let inGroup = 0;
|
|
84
|
+
for(let i = 0; i < pattern.length; i++){
|
|
85
|
+
const char = pattern[i];
|
|
86
|
+
const prev = pattern[i - 1];
|
|
87
|
+
// Track group depth
|
|
88
|
+
if (char === '(' && prev !== '\\') {
|
|
89
|
+
inGroup++;
|
|
90
|
+
} else if (char === ')' && prev !== '\\') {
|
|
91
|
+
inGroup = Math.max(0, inGroup - 1);
|
|
92
|
+
}
|
|
93
|
+
// Track quantifiers
|
|
94
|
+
if ((char === '+' || char === '*' || char === '?') && prev !== '\\') {
|
|
95
|
+
if (inGroup > 0) {
|
|
96
|
+
currentDepth = inGroup;
|
|
97
|
+
maxDepth = Math.max(maxDepth, currentDepth);
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
return maxDepth;
|
|
102
|
+
}
|
|
103
|
+
/**
|
|
104
|
+
* Check if a pattern is likely safe without full analysis.
|
|
105
|
+
* Use for quick rejection of obviously safe patterns.
|
|
106
|
+
*/ function quickSafetyCheck(pattern) {
|
|
107
|
+
// No quantifiers = safe
|
|
108
|
+
if (!/[+*?]/.test(pattern)) {
|
|
109
|
+
return true;
|
|
110
|
+
}
|
|
111
|
+
// No groups = generally safe
|
|
112
|
+
if (!/[()]/.test(pattern)) {
|
|
113
|
+
return true;
|
|
114
|
+
}
|
|
115
|
+
// Simple anchored patterns are usually safe
|
|
116
|
+
if (/^\^[^+*?()]+\$$/.test(pattern)) {
|
|
117
|
+
return true;
|
|
118
|
+
}
|
|
119
|
+
return false;
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
function _define_property(obj, key, value) {
|
|
123
|
+
if (key in obj) {
|
|
124
|
+
Object.defineProperty(obj, key, {
|
|
125
|
+
value: value,
|
|
126
|
+
enumerable: true,
|
|
127
|
+
configurable: true,
|
|
128
|
+
writable: true
|
|
129
|
+
});
|
|
130
|
+
} else {
|
|
131
|
+
obj[key] = value;
|
|
132
|
+
}
|
|
133
|
+
return obj;
|
|
134
|
+
}
|
|
135
|
+
/**
|
|
136
|
+
* SafeRegex provides protected regex creation and execution.
|
|
137
|
+
*
|
|
138
|
+
* @example
|
|
139
|
+
* ```typescript
|
|
140
|
+
* const safe = new SafeRegex();
|
|
141
|
+
* const result = safe.create(userPattern);
|
|
142
|
+
* if (result.safe && result.regex) {
|
|
143
|
+
* result.regex.test(input);
|
|
144
|
+
* }
|
|
145
|
+
* ```
|
|
146
|
+
*/ class SafeRegex {
|
|
147
|
+
/**
|
|
148
|
+
* Create a regex with safety checks.
|
|
149
|
+
* Returns a result object indicating whether the pattern is safe.
|
|
150
|
+
*/ create(pattern, flags) {
|
|
151
|
+
// Check pattern length
|
|
152
|
+
if (pattern.length > this.config.maxLength) {
|
|
153
|
+
this.notify('block', `Pattern exceeds maximum length of ${this.config.maxLength}`, pattern);
|
|
154
|
+
return {
|
|
155
|
+
safe: false,
|
|
156
|
+
error: `Pattern exceeds maximum length of ${this.config.maxLength}`,
|
|
157
|
+
reason: 'pattern_too_long'
|
|
158
|
+
};
|
|
159
|
+
}
|
|
160
|
+
// Quick safety check for obviously safe patterns
|
|
161
|
+
if (!quickSafetyCheck(pattern)) {
|
|
162
|
+
// Full pattern analysis
|
|
163
|
+
const analysis = analyzePattern(pattern);
|
|
164
|
+
if (!analysis.safe) {
|
|
165
|
+
this.notify('block', analysis.message || 'Pattern blocked', pattern);
|
|
166
|
+
return {
|
|
167
|
+
safe: false,
|
|
168
|
+
error: analysis.message,
|
|
169
|
+
reason: analysis.reason
|
|
170
|
+
};
|
|
171
|
+
}
|
|
172
|
+
}
|
|
173
|
+
// Try to create the regex
|
|
174
|
+
try {
|
|
175
|
+
const regex = new RegExp(pattern, flags);
|
|
176
|
+
return {
|
|
177
|
+
safe: true,
|
|
178
|
+
regex,
|
|
179
|
+
reason: 'ok'
|
|
180
|
+
};
|
|
181
|
+
} catch (error) {
|
|
182
|
+
return {
|
|
183
|
+
safe: false,
|
|
184
|
+
error: `Invalid regex syntax: ${error instanceof Error ? error.message : 'Unknown error'}`,
|
|
185
|
+
reason: 'invalid_syntax'
|
|
186
|
+
};
|
|
187
|
+
}
|
|
188
|
+
}
|
|
189
|
+
/**
|
|
190
|
+
* Execute regex.test() with timeout protection.
|
|
191
|
+
*
|
|
192
|
+
* Note: JavaScript regex execution is synchronous and cannot be truly
|
|
193
|
+
* interrupted. This uses a promise-based timeout that will reject if
|
|
194
|
+
* the operation takes too long, but the regex will continue executing
|
|
195
|
+
* in the background until completion.
|
|
196
|
+
*/ async testWithTimeout(regex, input) {
|
|
197
|
+
return new Promise((resolve, reject)=>{
|
|
198
|
+
const timeout = setTimeout(()=>{
|
|
199
|
+
this.notify('warning', `Regex execution exceeded ${this.config.timeoutMs}ms timeout`, regex.source);
|
|
200
|
+
reject(new Error(`Regex execution timed out after ${this.config.timeoutMs}ms`));
|
|
201
|
+
}, this.config.timeoutMs);
|
|
202
|
+
try {
|
|
203
|
+
const result = regex.test(input);
|
|
204
|
+
clearTimeout(timeout);
|
|
205
|
+
resolve(result);
|
|
206
|
+
} catch (error) {
|
|
207
|
+
clearTimeout(timeout);
|
|
208
|
+
reject(error);
|
|
209
|
+
}
|
|
210
|
+
});
|
|
211
|
+
}
|
|
212
|
+
/**
|
|
213
|
+
* Convert a glob pattern to a safe regex.
|
|
214
|
+
*
|
|
215
|
+
* Supports: * (any), ? (single char), ** (recursive)
|
|
216
|
+
*
|
|
217
|
+
* @example
|
|
218
|
+
* ```typescript
|
|
219
|
+
* const result = safe.globToRegex('*.md');
|
|
220
|
+
* // result.regex matches 'readme.md', 'file.md', etc.
|
|
221
|
+
* ```
|
|
222
|
+
*/ globToRegex(glob) {
|
|
223
|
+
// Escape special regex characters except glob wildcards
|
|
224
|
+
let pattern = glob.replace(/[.+^${}()|[\]\\]/g, '\\$&') // Escape special chars
|
|
225
|
+
.replace(/\*\*/g, '{{GLOBSTAR}}') // Placeholder for **
|
|
226
|
+
.replace(/\*/g, '[^/]*') // * = anything except /
|
|
227
|
+
.replace(/\?/g, '[^/]') // ? = single char except /
|
|
228
|
+
.replace(/\{\{GLOBSTAR\}\}/g, '.*'); // ** = anything including /
|
|
229
|
+
// Add anchors for full match
|
|
230
|
+
pattern = `^${pattern}$`;
|
|
231
|
+
return this.create(pattern, 'i');
|
|
232
|
+
}
|
|
233
|
+
/**
|
|
234
|
+
* Create a regex from user input by escaping all special characters.
|
|
235
|
+
* Use this when you want to match the literal user input.
|
|
236
|
+
*
|
|
237
|
+
* @example
|
|
238
|
+
* ```typescript
|
|
239
|
+
* const result = safe.fromUserInput('file (1).txt');
|
|
240
|
+
* // Matches literally 'file (1).txt'
|
|
241
|
+
* ```
|
|
242
|
+
*/ fromUserInput(input) {
|
|
243
|
+
const escaped = input.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
|
|
244
|
+
return this.create(escaped, 'i');
|
|
245
|
+
}
|
|
246
|
+
/**
|
|
247
|
+
* Update configuration.
|
|
248
|
+
*/ configure(config) {
|
|
249
|
+
this.config = {
|
|
250
|
+
...this.config,
|
|
251
|
+
...config
|
|
252
|
+
};
|
|
253
|
+
}
|
|
254
|
+
/**
|
|
255
|
+
* Get current configuration.
|
|
256
|
+
*/ getConfig() {
|
|
257
|
+
return {
|
|
258
|
+
...this.config
|
|
259
|
+
};
|
|
260
|
+
}
|
|
261
|
+
/**
|
|
262
|
+
* Notify via callbacks if configured.
|
|
263
|
+
*/ notify(type, message, pattern) {
|
|
264
|
+
if (type === 'block' && this.config.onBlock) {
|
|
265
|
+
this.config.onBlock(message, pattern);
|
|
266
|
+
}
|
|
267
|
+
if (type === 'warning' && this.config.onWarning) {
|
|
268
|
+
this.config.onWarning(message, pattern);
|
|
269
|
+
}
|
|
270
|
+
}
|
|
271
|
+
constructor(config = {}){
|
|
272
|
+
_define_property(this, "config", void 0);
|
|
273
|
+
this.config = {
|
|
274
|
+
...DEFAULT_CONFIG,
|
|
275
|
+
...config
|
|
276
|
+
};
|
|
277
|
+
}
|
|
278
|
+
}
|
|
279
|
+
/**
|
|
280
|
+
* Create a safe regex with default configuration.
|
|
281
|
+
* Convenience function for simple use cases.
|
|
282
|
+
*/ function createSafeRegex(pattern, flags) {
|
|
283
|
+
const safe = new SafeRegex();
|
|
284
|
+
return safe.create(pattern, flags);
|
|
285
|
+
}
|
|
286
|
+
/**
|
|
287
|
+
* Convert a glob pattern to a safe regex.
|
|
288
|
+
* Convenience function for simple use cases.
|
|
289
|
+
*/ function globToSafeRegex(glob) {
|
|
290
|
+
const safe = new SafeRegex();
|
|
291
|
+
return safe.globToRegex(glob);
|
|
292
|
+
}
|
|
293
|
+
/**
|
|
294
|
+
* Escape a string for use as a literal regex pattern.
|
|
295
|
+
*/ function escapeForRegex(input) {
|
|
296
|
+
return input.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
|
|
297
|
+
}
|
|
298
|
+
|
|
299
|
+
const VERSION = '1.0.0';
|
|
300
|
+
|
|
301
|
+
exports.DEFAULT_CONFIG = DEFAULT_CONFIG;
|
|
302
|
+
exports.SafeRegex = SafeRegex;
|
|
303
|
+
exports.VERSION = VERSION;
|
|
304
|
+
exports.analyzePattern = analyzePattern;
|
|
305
|
+
exports.createSafeRegex = createSafeRegex;
|
|
306
|
+
exports.escapeForRegex = escapeForRegex;
|
|
307
|
+
exports.globToSafeRegex = globToSafeRegex;
|
|
308
|
+
exports.quickSafetyCheck = quickSafetyCheck;
|
|
309
|
+
//# sourceMappingURL=pressurelid.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"pressurelid.cjs","sources":["../src/types.ts","../src/analyze.ts","../src/safe-regex.ts","../src/pressurelid.ts"],"sourcesContent":["/**\n * Configuration for SafeRegex behavior\n */\nexport interface SafeRegexConfig {\n /** Maximum allowed pattern length (default: 500) */\n maxLength: number;\n \n /** Timeout in milliseconds for regex execution (default: 1000) */\n timeoutMs: number;\n \n /** Maximum backtrack depth estimate (default: 100000) */\n maxBacktrackDepth: number;\n \n /** Optional callback when a pattern is blocked */\n onBlock?: (message: string, pattern: string) => void;\n \n /** Optional callback for warnings */\n onWarning?: (message: string, pattern: string) => void;\n}\n\n/**\n * Default configuration with secure defaults\n */\nexport const DEFAULT_CONFIG: SafeRegexConfig = {\n maxLength: 500,\n timeoutMs: 1000,\n maxBacktrackDepth: 100000,\n};\n\n/**\n * Result of attempting to create a safe regex\n */\nexport interface SafeRegexResult {\n /** Whether the pattern was deemed safe */\n safe: boolean;\n \n /** The compiled regex if safe */\n regex?: RegExp;\n \n /** Error message if not safe */\n error?: string;\n \n /** Specific reason code for the result */\n reason?: SafeRegexReason;\n}\n\n/**\n * Reason codes for SafeRegexResult\n */\nexport type SafeRegexReason =\n | 'ok'\n | 'pattern_too_long'\n | 'nested_quantifiers'\n | 'overlapping_alternation'\n | 'catastrophic_backtracking'\n | 'invalid_syntax'\n | 'execution_timeout';\n\n/**\n * Result of pattern analysis (internal)\n */\nexport interface PatternAnalysis {\n safe: boolean;\n reason?: SafeRegexReason;\n message?: string;\n}\n\n","import { PatternAnalysis, SafeRegexReason } from './types';\n\n/**\n * Patterns known to cause exponential backtracking\n */\nconst DANGEROUS_PATTERNS: Array<{ regex: RegExp; reason: SafeRegexReason; message: string }> = [\n {\n // Nested quantifiers: (a+)+, (a*)+, etc.\n regex: /\\([^)]*[+*][^)]*\\)[+*]/,\n reason: 'nested_quantifiers',\n message: 'Pattern contains nested quantifiers which can cause exponential backtracking',\n },\n {\n // Overlapping alternations with quantifiers: (a|ab)+\n regex: /\\([^)]*\\|[^)]*\\)[+*]/,\n reason: 'overlapping_alternation',\n message: 'Pattern contains alternation with quantifier which may cause backtracking',\n },\n {\n // Repeated groups: (a+){n} followed by quantifier\n regex: /\\([^)]+\\)\\{[0-9,]+\\}[+*]?/,\n reason: 'catastrophic_backtracking',\n message: 'Pattern contains repeated group which may cause backtracking',\n },\n {\n // Deeply nested groups with quantifiers\n regex: /\\([^)]*\\([^)]*[+*]\\)[^)]*[+*]\\)/,\n reason: 'nested_quantifiers',\n message: 'Pattern contains deeply nested quantifiers',\n },\n {\n // Character class with quantifier followed by similar class\n regex: /\\[[^\\]]+\\][+*]\\[[^\\]]+\\][+*]/,\n reason: 'catastrophic_backtracking',\n message: 'Pattern contains overlapping character classes with quantifiers',\n },\n];\n\n/**\n * Analyze a regex pattern for potential ReDoS vulnerabilities.\n * \n * This performs static analysis only - it cannot catch all dangerous patterns.\n * Use testWithTimeout() for runtime protection.\n */\nexport function analyzePattern(pattern: string): PatternAnalysis {\n for (const dangerous of DANGEROUS_PATTERNS) {\n if (dangerous.regex.test(pattern)) {\n return {\n safe: false,\n reason: dangerous.reason,\n message: dangerous.message,\n };\n }\n }\n\n // Check for excessive quantifier nesting depth\n const nestingDepth = countQuantifierNesting(pattern);\n if (nestingDepth > 2) {\n return {\n safe: false,\n reason: 'nested_quantifiers',\n message: `Pattern has excessive quantifier nesting depth (${nestingDepth})`,\n };\n }\n\n return { safe: true, reason: 'ok' };\n}\n\n/**\n * Count the nesting depth of quantifiers in a pattern.\n */\nfunction countQuantifierNesting(pattern: string): number {\n let maxDepth = 0;\n let currentDepth = 0;\n let inGroup = 0;\n\n for (let i = 0; i < pattern.length; i++) {\n const char = pattern[i];\n const prev = pattern[i - 1];\n\n // Track group depth\n if (char === '(' && prev !== '\\\\') {\n inGroup++;\n } else if (char === ')' && prev !== '\\\\') {\n inGroup = Math.max(0, inGroup - 1);\n }\n\n // Track quantifiers\n if ((char === '+' || char === '*' || char === '?') && prev !== '\\\\') {\n if (inGroup > 0) {\n currentDepth = inGroup;\n maxDepth = Math.max(maxDepth, currentDepth);\n }\n }\n }\n\n return maxDepth;\n}\n\n/**\n * Check if a pattern is likely safe without full analysis.\n * Use for quick rejection of obviously safe patterns.\n */\nexport function quickSafetyCheck(pattern: string): boolean {\n // No quantifiers = safe\n if (!/[+*?]/.test(pattern)) {\n return true;\n }\n\n // No groups = generally safe\n if (!/[()]/.test(pattern)) {\n return true;\n }\n\n // Simple anchored patterns are usually safe\n if (/^\\^[^+*?()]+\\$$/.test(pattern)) {\n return true;\n }\n\n return false;\n}\n\n","import {\n SafeRegexConfig,\n SafeRegexResult,\n DEFAULT_CONFIG,\n} from './types';\nimport { analyzePattern, quickSafetyCheck } from './analyze';\n\n/**\n * SafeRegex provides protected regex creation and execution.\n * \n * @example\n * ```typescript\n * const safe = new SafeRegex();\n * const result = safe.create(userPattern);\n * if (result.safe && result.regex) {\n * result.regex.test(input);\n * }\n * ```\n */\nexport class SafeRegex {\n private config: SafeRegexConfig;\n\n constructor(config: Partial<SafeRegexConfig> = {}) {\n this.config = { ...DEFAULT_CONFIG, ...config };\n }\n\n /**\n * Create a regex with safety checks.\n * Returns a result object indicating whether the pattern is safe.\n */\n create(pattern: string, flags?: string): SafeRegexResult {\n // Check pattern length\n if (pattern.length > this.config.maxLength) {\n this.notify('block', `Pattern exceeds maximum length of ${this.config.maxLength}`, pattern);\n return {\n safe: false,\n error: `Pattern exceeds maximum length of ${this.config.maxLength}`,\n reason: 'pattern_too_long',\n };\n }\n\n // Quick safety check for obviously safe patterns\n if (!quickSafetyCheck(pattern)) {\n // Full pattern analysis\n const analysis = analyzePattern(pattern);\n if (!analysis.safe) {\n this.notify('block', analysis.message || 'Pattern blocked', pattern);\n return {\n safe: false,\n error: analysis.message,\n reason: analysis.reason,\n };\n }\n }\n\n // Try to create the regex\n try {\n const regex = new RegExp(pattern, flags);\n return { safe: true, regex, reason: 'ok' };\n } catch (error) {\n return {\n safe: false,\n error: `Invalid regex syntax: ${error instanceof Error ? error.message : 'Unknown error'}`,\n reason: 'invalid_syntax',\n };\n }\n }\n\n /**\n * Execute regex.test() with timeout protection.\n * \n * Note: JavaScript regex execution is synchronous and cannot be truly\n * interrupted. This uses a promise-based timeout that will reject if\n * the operation takes too long, but the regex will continue executing\n * in the background until completion.\n */\n async testWithTimeout(regex: RegExp, input: string): Promise<boolean> {\n return new Promise((resolve, reject) => {\n const timeout = setTimeout(() => {\n this.notify('warning', `Regex execution exceeded ${this.config.timeoutMs}ms timeout`, regex.source);\n reject(new Error(`Regex execution timed out after ${this.config.timeoutMs}ms`));\n }, this.config.timeoutMs);\n\n try {\n const result = regex.test(input);\n clearTimeout(timeout);\n resolve(result);\n } catch (error) {\n clearTimeout(timeout);\n reject(error);\n }\n });\n }\n\n /**\n * Convert a glob pattern to a safe regex.\n * \n * Supports: * (any), ? (single char), ** (recursive)\n * \n * @example\n * ```typescript\n * const result = safe.globToRegex('*.md');\n * // result.regex matches 'readme.md', 'file.md', etc.\n * ```\n */\n globToRegex(glob: string): SafeRegexResult {\n // Escape special regex characters except glob wildcards\n let pattern = glob\n .replace(/[.+^${}()|[\\]\\\\]/g, '\\\\$&') // Escape special chars\n .replace(/\\*\\*/g, '{{GLOBSTAR}}') // Placeholder for **\n .replace(/\\*/g, '[^/]*') // * = anything except /\n .replace(/\\?/g, '[^/]') // ? = single char except /\n .replace(/\\{\\{GLOBSTAR\\}\\}/g, '.*'); // ** = anything including /\n\n // Add anchors for full match\n pattern = `^${pattern}$`;\n\n return this.create(pattern, 'i');\n }\n\n /**\n * Create a regex from user input by escaping all special characters.\n * Use this when you want to match the literal user input.\n * \n * @example\n * ```typescript\n * const result = safe.fromUserInput('file (1).txt');\n * // Matches literally 'file (1).txt'\n * ```\n */\n fromUserInput(input: string): SafeRegexResult {\n const escaped = input.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&');\n return this.create(escaped, 'i');\n }\n\n /**\n * Update configuration.\n */\n configure(config: Partial<SafeRegexConfig>): void {\n this.config = { ...this.config, ...config };\n }\n\n /**\n * Get current configuration.\n */\n getConfig(): SafeRegexConfig {\n return { ...this.config };\n }\n\n /**\n * Notify via callbacks if configured.\n */\n private notify(type: 'block' | 'warning', message: string, pattern: string): void {\n if (type === 'block' && this.config.onBlock) {\n this.config.onBlock(message, pattern);\n }\n if (type === 'warning' && this.config.onWarning) {\n this.config.onWarning(message, pattern);\n }\n }\n}\n\n/**\n * Create a safe regex with default configuration.\n * Convenience function for simple use cases.\n */\nexport function createSafeRegex(pattern: string, flags?: string): SafeRegexResult {\n const safe = new SafeRegex();\n return safe.create(pattern, flags);\n}\n\n/**\n * Convert a glob pattern to a safe regex.\n * Convenience function for simple use cases.\n */\nexport function globToSafeRegex(glob: string): SafeRegexResult {\n const safe = new SafeRegex();\n return safe.globToRegex(glob);\n}\n\n/**\n * Escape a string for use as a literal regex pattern.\n */\nexport function escapeForRegex(input: string): string {\n return input.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&');\n}\n\n","export const VERSION = '__VERSION__';\n\n// Types\nexport type {\n SafeRegexConfig,\n SafeRegexResult,\n SafeRegexReason,\n} from './types';\n\nexport { DEFAULT_CONFIG } from './types';\n\n// Analysis (for advanced users)\nexport { analyzePattern, quickSafetyCheck } from './analyze';\n\n// Main API\nexport {\n SafeRegex,\n createSafeRegex,\n globToSafeRegex,\n escapeForRegex,\n} from './safe-regex';\n\n"],"names":["DEFAULT_CONFIG","maxLength","timeoutMs","maxBacktrackDepth","DANGEROUS_PATTERNS","regex","reason","message","analyzePattern","pattern","dangerous","test","safe","nestingDepth","countQuantifierNesting","maxDepth","currentDepth","inGroup","i","length","char","prev","Math","max","quickSafetyCheck","SafeRegex","create","flags","config","notify","error","analysis","RegExp","Error","testWithTimeout","input","Promise","resolve","reject","timeout","setTimeout","source","result","clearTimeout","globToRegex","glob","replace","fromUserInput","escaped","configure","getConfig","type","onBlock","onWarning","createSafeRegex","globToSafeRegex","escapeForRegex","VERSION"],"mappings":";;;;AAAA;;;;UAuBaA,cAAAA,GAAkC;IAC3CC,SAAAA,EAAW,GAAA;IACXC,SAAAA,EAAW,IAAA;IACXC,iBAAAA,EAAmB;AACvB;;ACzBA;;AAEC,IACD,MAAMC,kBAAAA,GAAyF;AAC3F,IAAA;;QAEIC,KAAAA,EAAO,wBAAA;QACPC,MAAAA,EAAQ,oBAAA;QACRC,OAAAA,EAAS;AACb,KAAA;AACA,IAAA;;QAEIF,KAAAA,EAAO,sBAAA;QACPC,MAAAA,EAAQ,yBAAA;QACRC,OAAAA,EAAS;AACb,KAAA;AACA,IAAA;;QAEIF,KAAAA,EAAO,2BAAA;QACPC,MAAAA,EAAQ,2BAAA;QACRC,OAAAA,EAAS;AACb,KAAA;AACA,IAAA;;QAEIF,KAAAA,EAAO,iCAAA;QACPC,MAAAA,EAAQ,oBAAA;QACRC,OAAAA,EAAS;AACb,KAAA;AACA,IAAA;;QAEIF,KAAAA,EAAO,8BAAA;QACPC,MAAAA,EAAQ,2BAAA;QACRC,OAAAA,EAAS;AACb;AACH,CAAA;AAED;;;;;IAMO,SAASC,cAAAA,CAAeC,OAAe,EAAA;IAC1C,KAAK,MAAMC,aAAaN,kBAAAA,CAAoB;AACxC,QAAA,IAAIM,SAAAA,CAAUL,KAAK,CAACM,IAAI,CAACF,OAAAA,CAAAA,EAAU;YAC/B,OAAO;gBACHG,IAAAA,EAAM,KAAA;AACNN,gBAAAA,MAAAA,EAAQI,UAAUJ,MAAM;AACxBC,gBAAAA,OAAAA,EAASG,UAAUH;AACvB,aAAA;AACJ,QAAA;AACJ,IAAA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
export { DEFAULT_CONFIG } from './types';
|
|
4
|
+
export { analyzePattern, quickSafetyCheck } from './analyze';
|
|
5
|
+
export { SafeRegex, createSafeRegex, globToSafeRegex, escapeForRegex, } from './safe-regex';
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
export { DEFAULT_CONFIG } from './types.js';
|
|
2
|
+
export { analyzePattern, quickSafetyCheck } from './analyze.js';
|
|
3
|
+
export { SafeRegex, createSafeRegex, escapeForRegex, globToSafeRegex } from './safe-regex.js';
|
|
4
|
+
|
|
5
|
+
const VERSION = '1.0.0';
|
|
6
|
+
|
|
7
|
+
export { VERSION };
|
|
8
|
+
//# sourceMappingURL=pressurelid.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"pressurelid.js","sources":["../src/pressurelid.ts"],"sourcesContent":["export const VERSION = '__VERSION__';\n\n// Types\nexport type {\n SafeRegexConfig,\n SafeRegexResult,\n SafeRegexReason,\n} from './types';\n\nexport { DEFAULT_CONFIG } from './types';\n\n// Analysis (for advanced users)\nexport { analyzePattern, quickSafetyCheck } from './analyze';\n\n// Main API\nexport {\n SafeRegex,\n createSafeRegex,\n globToSafeRegex,\n escapeForRegex,\n} from './safe-regex';\n\n"],"names":["VERSION"],"mappings":";;;;AAAO,MAAMA,UAAU;;;;"}
|
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
import { SafeRegexConfig, SafeRegexResult } from './types';
|
|
2
|
+
/**
|
|
3
|
+
* SafeRegex provides protected regex creation and execution.
|
|
4
|
+
*
|
|
5
|
+
* @example
|
|
6
|
+
* ```typescript
|
|
7
|
+
* const safe = new SafeRegex();
|
|
8
|
+
* const result = safe.create(userPattern);
|
|
9
|
+
* if (result.safe && result.regex) {
|
|
10
|
+
* result.regex.test(input);
|
|
11
|
+
* }
|
|
12
|
+
* ```
|
|
13
|
+
*/
|
|
14
|
+
export declare class SafeRegex {
|
|
15
|
+
private config;
|
|
16
|
+
constructor(config?: Partial<SafeRegexConfig>);
|
|
17
|
+
/**
|
|
18
|
+
* Create a regex with safety checks.
|
|
19
|
+
* Returns a result object indicating whether the pattern is safe.
|
|
20
|
+
*/
|
|
21
|
+
create(pattern: string, flags?: string): SafeRegexResult;
|
|
22
|
+
/**
|
|
23
|
+
* Execute regex.test() with timeout protection.
|
|
24
|
+
*
|
|
25
|
+
* Note: JavaScript regex execution is synchronous and cannot be truly
|
|
26
|
+
* interrupted. This uses a promise-based timeout that will reject if
|
|
27
|
+
* the operation takes too long, but the regex will continue executing
|
|
28
|
+
* in the background until completion.
|
|
29
|
+
*/
|
|
30
|
+
testWithTimeout(regex: RegExp, input: string): Promise<boolean>;
|
|
31
|
+
/**
|
|
32
|
+
* Convert a glob pattern to a safe regex.
|
|
33
|
+
*
|
|
34
|
+
* Supports: * (any), ? (single char), ** (recursive)
|
|
35
|
+
*
|
|
36
|
+
* @example
|
|
37
|
+
* ```typescript
|
|
38
|
+
* const result = safe.globToRegex('*.md');
|
|
39
|
+
* // result.regex matches 'readme.md', 'file.md', etc.
|
|
40
|
+
* ```
|
|
41
|
+
*/
|
|
42
|
+
globToRegex(glob: string): SafeRegexResult;
|
|
43
|
+
/**
|
|
44
|
+
* Create a regex from user input by escaping all special characters.
|
|
45
|
+
* Use this when you want to match the literal user input.
|
|
46
|
+
*
|
|
47
|
+
* @example
|
|
48
|
+
* ```typescript
|
|
49
|
+
* const result = safe.fromUserInput('file (1).txt');
|
|
50
|
+
* // Matches literally 'file (1).txt'
|
|
51
|
+
* ```
|
|
52
|
+
*/
|
|
53
|
+
fromUserInput(input: string): SafeRegexResult;
|
|
54
|
+
/**
|
|
55
|
+
* Update configuration.
|
|
56
|
+
*/
|
|
57
|
+
configure(config: Partial<SafeRegexConfig>): void;
|
|
58
|
+
/**
|
|
59
|
+
* Get current configuration.
|
|
60
|
+
*/
|
|
61
|
+
getConfig(): SafeRegexConfig;
|
|
62
|
+
/**
|
|
63
|
+
* Notify via callbacks if configured.
|
|
64
|
+
*/
|
|
65
|
+
private notify;
|
|
66
|
+
}
|
|
67
|
+
/**
|
|
68
|
+
* Create a safe regex with default configuration.
|
|
69
|
+
* Convenience function for simple use cases.
|
|
70
|
+
*/
|
|
71
|
+
export declare function createSafeRegex(pattern: string, flags?: string): SafeRegexResult;
|
|
72
|
+
/**
|
|
73
|
+
* Convert a glob pattern to a safe regex.
|
|
74
|
+
* Convenience function for simple use cases.
|
|
75
|
+
*/
|
|
76
|
+
export declare function globToSafeRegex(glob: string): SafeRegexResult;
|
|
77
|
+
/**
|
|
78
|
+
* Escape a string for use as a literal regex pattern.
|
|
79
|
+
*/
|
|
80
|
+
export declare function escapeForRegex(input: string): string;
|
|
@@ -0,0 +1,182 @@
|
|
|
1
|
+
import { DEFAULT_CONFIG } from './types.js';
|
|
2
|
+
import { quickSafetyCheck, analyzePattern } from './analyze.js';
|
|
3
|
+
|
|
4
|
+
function _define_property(obj, key, value) {
|
|
5
|
+
if (key in obj) {
|
|
6
|
+
Object.defineProperty(obj, key, {
|
|
7
|
+
value: value,
|
|
8
|
+
enumerable: true,
|
|
9
|
+
configurable: true,
|
|
10
|
+
writable: true
|
|
11
|
+
});
|
|
12
|
+
} else {
|
|
13
|
+
obj[key] = value;
|
|
14
|
+
}
|
|
15
|
+
return obj;
|
|
16
|
+
}
|
|
17
|
+
/**
|
|
18
|
+
* SafeRegex provides protected regex creation and execution.
|
|
19
|
+
*
|
|
20
|
+
* @example
|
|
21
|
+
* ```typescript
|
|
22
|
+
* const safe = new SafeRegex();
|
|
23
|
+
* const result = safe.create(userPattern);
|
|
24
|
+
* if (result.safe && result.regex) {
|
|
25
|
+
* result.regex.test(input);
|
|
26
|
+
* }
|
|
27
|
+
* ```
|
|
28
|
+
*/ class SafeRegex {
|
|
29
|
+
/**
|
|
30
|
+
* Create a regex with safety checks.
|
|
31
|
+
* Returns a result object indicating whether the pattern is safe.
|
|
32
|
+
*/ create(pattern, flags) {
|
|
33
|
+
// Check pattern length
|
|
34
|
+
if (pattern.length > this.config.maxLength) {
|
|
35
|
+
this.notify('block', `Pattern exceeds maximum length of ${this.config.maxLength}`, pattern);
|
|
36
|
+
return {
|
|
37
|
+
safe: false,
|
|
38
|
+
error: `Pattern exceeds maximum length of ${this.config.maxLength}`,
|
|
39
|
+
reason: 'pattern_too_long'
|
|
40
|
+
};
|
|
41
|
+
}
|
|
42
|
+
// Quick safety check for obviously safe patterns
|
|
43
|
+
if (!quickSafetyCheck(pattern)) {
|
|
44
|
+
// Full pattern analysis
|
|
45
|
+
const analysis = analyzePattern(pattern);
|
|
46
|
+
if (!analysis.safe) {
|
|
47
|
+
this.notify('block', analysis.message || 'Pattern blocked', pattern);
|
|
48
|
+
return {
|
|
49
|
+
safe: false,
|
|
50
|
+
error: analysis.message,
|
|
51
|
+
reason: analysis.reason
|
|
52
|
+
};
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
// Try to create the regex
|
|
56
|
+
try {
|
|
57
|
+
const regex = new RegExp(pattern, flags);
|
|
58
|
+
return {
|
|
59
|
+
safe: true,
|
|
60
|
+
regex,
|
|
61
|
+
reason: 'ok'
|
|
62
|
+
};
|
|
63
|
+
} catch (error) {
|
|
64
|
+
return {
|
|
65
|
+
safe: false,
|
|
66
|
+
error: `Invalid regex syntax: ${error instanceof Error ? error.message : 'Unknown error'}`,
|
|
67
|
+
reason: 'invalid_syntax'
|
|
68
|
+
};
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
/**
|
|
72
|
+
* Execute regex.test() with timeout protection.
|
|
73
|
+
*
|
|
74
|
+
* Note: JavaScript regex execution is synchronous and cannot be truly
|
|
75
|
+
* interrupted. This uses a promise-based timeout that will reject if
|
|
76
|
+
* the operation takes too long, but the regex will continue executing
|
|
77
|
+
* in the background until completion.
|
|
78
|
+
*/ async testWithTimeout(regex, input) {
|
|
79
|
+
return new Promise((resolve, reject)=>{
|
|
80
|
+
const timeout = setTimeout(()=>{
|
|
81
|
+
this.notify('warning', `Regex execution exceeded ${this.config.timeoutMs}ms timeout`, regex.source);
|
|
82
|
+
reject(new Error(`Regex execution timed out after ${this.config.timeoutMs}ms`));
|
|
83
|
+
}, this.config.timeoutMs);
|
|
84
|
+
try {
|
|
85
|
+
const result = regex.test(input);
|
|
86
|
+
clearTimeout(timeout);
|
|
87
|
+
resolve(result);
|
|
88
|
+
} catch (error) {
|
|
89
|
+
clearTimeout(timeout);
|
|
90
|
+
reject(error);
|
|
91
|
+
}
|
|
92
|
+
});
|
|
93
|
+
}
|
|
94
|
+
/**
|
|
95
|
+
* Convert a glob pattern to a safe regex.
|
|
96
|
+
*
|
|
97
|
+
* Supports: * (any), ? (single char), ** (recursive)
|
|
98
|
+
*
|
|
99
|
+
* @example
|
|
100
|
+
* ```typescript
|
|
101
|
+
* const result = safe.globToRegex('*.md');
|
|
102
|
+
* // result.regex matches 'readme.md', 'file.md', etc.
|
|
103
|
+
* ```
|
|
104
|
+
*/ globToRegex(glob) {
|
|
105
|
+
// Escape special regex characters except glob wildcards
|
|
106
|
+
let pattern = glob.replace(/[.+^${}()|[\]\\]/g, '\\$&') // Escape special chars
|
|
107
|
+
.replace(/\*\*/g, '{{GLOBSTAR}}') // Placeholder for **
|
|
108
|
+
.replace(/\*/g, '[^/]*') // * = anything except /
|
|
109
|
+
.replace(/\?/g, '[^/]') // ? = single char except /
|
|
110
|
+
.replace(/\{\{GLOBSTAR\}\}/g, '.*'); // ** = anything including /
|
|
111
|
+
// Add anchors for full match
|
|
112
|
+
pattern = `^${pattern}$`;
|
|
113
|
+
return this.create(pattern, 'i');
|
|
114
|
+
}
|
|
115
|
+
/**
|
|
116
|
+
* Create a regex from user input by escaping all special characters.
|
|
117
|
+
* Use this when you want to match the literal user input.
|
|
118
|
+
*
|
|
119
|
+
* @example
|
|
120
|
+
* ```typescript
|
|
121
|
+
* const result = safe.fromUserInput('file (1).txt');
|
|
122
|
+
* // Matches literally 'file (1).txt'
|
|
123
|
+
* ```
|
|
124
|
+
*/ fromUserInput(input) {
|
|
125
|
+
const escaped = input.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
|
|
126
|
+
return this.create(escaped, 'i');
|
|
127
|
+
}
|
|
128
|
+
/**
|
|
129
|
+
* Update configuration.
|
|
130
|
+
*/ configure(config) {
|
|
131
|
+
this.config = {
|
|
132
|
+
...this.config,
|
|
133
|
+
...config
|
|
134
|
+
};
|
|
135
|
+
}
|
|
136
|
+
/**
|
|
137
|
+
* Get current configuration.
|
|
138
|
+
*/ getConfig() {
|
|
139
|
+
return {
|
|
140
|
+
...this.config
|
|
141
|
+
};
|
|
142
|
+
}
|
|
143
|
+
/**
|
|
144
|
+
* Notify via callbacks if configured.
|
|
145
|
+
*/ notify(type, message, pattern) {
|
|
146
|
+
if (type === 'block' && this.config.onBlock) {
|
|
147
|
+
this.config.onBlock(message, pattern);
|
|
148
|
+
}
|
|
149
|
+
if (type === 'warning' && this.config.onWarning) {
|
|
150
|
+
this.config.onWarning(message, pattern);
|
|
151
|
+
}
|
|
152
|
+
}
|
|
153
|
+
constructor(config = {}){
|
|
154
|
+
_define_property(this, "config", void 0);
|
|
155
|
+
this.config = {
|
|
156
|
+
...DEFAULT_CONFIG,
|
|
157
|
+
...config
|
|
158
|
+
};
|
|
159
|
+
}
|
|
160
|
+
}
|
|
161
|
+
/**
|
|
162
|
+
* Create a safe regex with default configuration.
|
|
163
|
+
* Convenience function for simple use cases.
|
|
164
|
+
*/ function createSafeRegex(pattern, flags) {
|
|
165
|
+
const safe = new SafeRegex();
|
|
166
|
+
return safe.create(pattern, flags);
|
|
167
|
+
}
|
|
168
|
+
/**
|
|
169
|
+
* Convert a glob pattern to a safe regex.
|
|
170
|
+
* Convenience function for simple use cases.
|
|
171
|
+
*/ function globToSafeRegex(glob) {
|
|
172
|
+
const safe = new SafeRegex();
|
|
173
|
+
return safe.globToRegex(glob);
|
|
174
|
+
}
|
|
175
|
+
/**
|
|
176
|
+
* Escape a string for use as a literal regex pattern.
|
|
177
|
+
*/ function escapeForRegex(input) {
|
|
178
|
+
return input.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
export { SafeRegex, createSafeRegex, escapeForRegex, globToSafeRegex };
|
|
182
|
+
//# sourceMappingURL=safe-regex.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"safe-regex.js","sources":["../src/safe-regex.ts"],"sourcesContent":["import {\n SafeRegexConfig,\n SafeRegexResult,\n DEFAULT_CONFIG,\n} from './types';\nimport { analyzePattern, quickSafetyCheck } from './analyze';\n\n/**\n * SafeRegex provides protected regex creation and execution.\n * \n * @example\n * ```typescript\n * const safe = new SafeRegex();\n * const result = safe.create(userPattern);\n * if (result.safe && result.regex) {\n * result.regex.test(input);\n * }\n * ```\n */\nexport class SafeRegex {\n private config: SafeRegexConfig;\n\n constructor(config: Partial<SafeRegexConfig> = {}) {\n this.config = { ...DEFAULT_CONFIG, ...config };\n }\n\n /**\n * Create a regex with safety checks.\n * Returns a result object indicating whether the pattern is safe.\n */\n create(pattern: string, flags?: string): SafeRegexResult {\n // Check pattern length\n if (pattern.length > this.config.maxLength) {\n this.notify('block', `Pattern exceeds maximum length of ${this.config.maxLength}`, pattern);\n return {\n safe: false,\n error: `Pattern exceeds maximum length of ${this.config.maxLength}`,\n reason: 'pattern_too_long',\n };\n }\n\n // Quick safety check for obviously safe patterns\n if (!quickSafetyCheck(pattern)) {\n // Full pattern analysis\n const analysis = analyzePattern(pattern);\n if (!analysis.safe) {\n this.notify('block', analysis.message || 'Pattern blocked', pattern);\n return {\n safe: false,\n error: analysis.message,\n reason: analysis.reason,\n };\n }\n }\n\n // Try to create the regex\n try {\n const regex = new RegExp(pattern, flags);\n return { safe: true, regex, reason: 'ok' };\n } catch (error) {\n return {\n safe: false,\n error: `Invalid regex syntax: ${error instanceof Error ? error.message : 'Unknown error'}`,\n reason: 'invalid_syntax',\n };\n }\n }\n\n /**\n * Execute regex.test() with timeout protection.\n * \n * Note: JavaScript regex execution is synchronous and cannot be truly\n * interrupted. This uses a promise-based timeout that will reject if\n * the operation takes too long, but the regex will continue executing\n * in the background until completion.\n */\n async testWithTimeout(regex: RegExp, input: string): Promise<boolean> {\n return new Promise((resolve, reject) => {\n const timeout = setTimeout(() => {\n this.notify('warning', `Regex execution exceeded ${this.config.timeoutMs}ms timeout`, regex.source);\n reject(new Error(`Regex execution timed out after ${this.config.timeoutMs}ms`));\n }, this.config.timeoutMs);\n\n try {\n const result = regex.test(input);\n clearTimeout(timeout);\n resolve(result);\n } catch (error) {\n clearTimeout(timeout);\n reject(error);\n }\n });\n }\n\n /**\n * Convert a glob pattern to a safe regex.\n * \n * Supports: * (any), ? (single char), ** (recursive)\n * \n * @example\n * ```typescript\n * const result = safe.globToRegex('*.md');\n * // result.regex matches 'readme.md', 'file.md', etc.\n * ```\n */\n globToRegex(glob: string): SafeRegexResult {\n // Escape special regex characters except glob wildcards\n let pattern = glob\n .replace(/[.+^${}()|[\\]\\\\]/g, '\\\\$&') // Escape special chars\n .replace(/\\*\\*/g, '{{GLOBSTAR}}') // Placeholder for **\n .replace(/\\*/g, '[^/]*') // * = anything except /\n .replace(/\\?/g, '[^/]') // ? = single char except /\n .replace(/\\{\\{GLOBSTAR\\}\\}/g, '.*'); // ** = anything including /\n\n // Add anchors for full match\n pattern = `^${pattern}$`;\n\n return this.create(pattern, 'i');\n }\n\n /**\n * Create a regex from user input by escaping all special characters.\n * Use this when you want to match the literal user input.\n * \n * @example\n * ```typescript\n * const result = safe.fromUserInput('file (1).txt');\n * // Matches literally 'file (1).txt'\n * ```\n */\n fromUserInput(input: string): SafeRegexResult {\n const escaped = input.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&');\n return this.create(escaped, 'i');\n }\n\n /**\n * Update configuration.\n */\n configure(config: Partial<SafeRegexConfig>): void {\n this.config = { ...this.config, ...config };\n }\n\n /**\n * Get current configuration.\n */\n getConfig(): SafeRegexConfig {\n return { ...this.config };\n }\n\n /**\n * Notify via callbacks if configured.\n */\n private notify(type: 'block' | 'warning', message: string, pattern: string): void {\n if (type === 'block' && this.config.onBlock) {\n this.config.onBlock(message, pattern);\n }\n if (type === 'warning' && this.config.onWarning) {\n this.config.onWarning(message, pattern);\n }\n }\n}\n\n/**\n * Create a safe regex with default configuration.\n * Convenience function for simple use cases.\n */\nexport function createSafeRegex(pattern: string, flags?: string): SafeRegexResult {\n const safe = new SafeRegex();\n return safe.create(pattern, flags);\n}\n\n/**\n * Convert a glob pattern to a safe regex.\n * Convenience function for simple use cases.\n */\nexport function globToSafeRegex(glob: string): SafeRegexResult {\n const safe = new SafeRegex();\n return safe.globToRegex(glob);\n}\n\n/**\n * Escape a string for use as a literal regex pattern.\n */\nexport function escapeForRegex(input: string): string {\n return input.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&');\n}\n\n"],"names":["SafeRegex","create","pattern","flags","length","config","maxLength","notify","safe","error","reason","quickSafetyCheck","analysis","analyzePattern","message","regex","RegExp","Error","testWithTimeout","input","Promise","resolve","reject","timeout","setTimeout","timeoutMs","source","result","test","clearTimeout","globToRegex","glob","replace","fromUserInput","escaped","configure","getConfig","type","onBlock","onWarning","DEFAULT_CONFIG","createSafeRegex","globToSafeRegex","escapeForRegex"],"mappings":";;;;;;;;;;;;;;;;AAOA;;;;;;;;;;;AAWC,IACM,MAAMA,SAAAA,CAAAA;AAOT;;;AAGC,QACDC,MAAAA,CAAOC,OAAe,EAAEC,KAAc,EAAmB;;QAErD,IAAID,OAAAA,CAAQE,MAAM,GAAG,IAAI,CAACC,MAAM,CAACC,SAAS,EAAE;AACxC,YAAA,IAAI,CAACC,MAAM,CAAC,OAAA,EAAS,CAAC,kCAAkC,EAAE,IAAI,CAACF,MAAM,CAACC,SAAS,EAAE,EAAEJ,OAAAA,CAAAA;YACnF,OAAO;gBACHM,IAAAA,EAAM,KAAA;gBACNC,KAAAA,EAAO,CAAC,kCAAkC,EAAE,IAAI,CAACJ,MAAM,CAACC,SAAS,CAAA,CAAE;gBACnEI,MAAAA,EAAQ;AAC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IACxC,OAAOA,KAAAA,CAAMa,OAAO,CAAC,qBAAA,EAAuB,MAAA,CAAA;AAChD;;;;"}
|
package/dist/types.d.ts
ADDED
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Configuration for SafeRegex behavior
|
|
3
|
+
*/
|
|
4
|
+
export interface SafeRegexConfig {
|
|
5
|
+
/** Maximum allowed pattern length (default: 500) */
|
|
6
|
+
maxLength: number;
|
|
7
|
+
/** Timeout in milliseconds for regex execution (default: 1000) */
|
|
8
|
+
timeoutMs: number;
|
|
9
|
+
/** Maximum backtrack depth estimate (default: 100000) */
|
|
10
|
+
maxBacktrackDepth: number;
|
|
11
|
+
/** Optional callback when a pattern is blocked */
|
|
12
|
+
onBlock?: (message: string, pattern: string) => void;
|
|
13
|
+
/** Optional callback for warnings */
|
|
14
|
+
onWarning?: (message: string, pattern: string) => void;
|
|
15
|
+
}
|
|
16
|
+
/**
|
|
17
|
+
* Default configuration with secure defaults
|
|
18
|
+
*/
|
|
19
|
+
export declare const DEFAULT_CONFIG: SafeRegexConfig;
|
|
20
|
+
/**
|
|
21
|
+
* Result of attempting to create a safe regex
|
|
22
|
+
*/
|
|
23
|
+
export interface SafeRegexResult {
|
|
24
|
+
/** Whether the pattern was deemed safe */
|
|
25
|
+
safe: boolean;
|
|
26
|
+
/** The compiled regex if safe */
|
|
27
|
+
regex?: RegExp;
|
|
28
|
+
/** Error message if not safe */
|
|
29
|
+
error?: string;
|
|
30
|
+
/** Specific reason code for the result */
|
|
31
|
+
reason?: SafeRegexReason;
|
|
32
|
+
}
|
|
33
|
+
/**
|
|
34
|
+
* Reason codes for SafeRegexResult
|
|
35
|
+
*/
|
|
36
|
+
export type SafeRegexReason = 'ok' | 'pattern_too_long' | 'nested_quantifiers' | 'overlapping_alternation' | 'catastrophic_backtracking' | 'invalid_syntax' | 'execution_timeout';
|
|
37
|
+
/**
|
|
38
|
+
* Result of pattern analysis (internal)
|
|
39
|
+
*/
|
|
40
|
+
export interface PatternAnalysis {
|
|
41
|
+
safe: boolean;
|
|
42
|
+
reason?: SafeRegexReason;
|
|
43
|
+
message?: string;
|
|
44
|
+
}
|
package/dist/types.js
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Configuration for SafeRegex behavior
|
|
3
|
+
*/ /**
|
|
4
|
+
* Default configuration with secure defaults
|
|
5
|
+
*/ const DEFAULT_CONFIG = {
|
|
6
|
+
maxLength: 500,
|
|
7
|
+
timeoutMs: 1000,
|
|
8
|
+
maxBacktrackDepth: 100000
|
|
9
|
+
};
|
|
10
|
+
|
|
11
|
+
export { DEFAULT_CONFIG };
|
|
12
|
+
//# sourceMappingURL=types.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"types.js","sources":["../src/types.ts"],"sourcesContent":["/**\n * Configuration for SafeRegex behavior\n */\nexport interface SafeRegexConfig {\n /** Maximum allowed pattern length (default: 500) */\n maxLength: number;\n \n /** Timeout in milliseconds for regex execution (default: 1000) */\n timeoutMs: number;\n \n /** Maximum backtrack depth estimate (default: 100000) */\n maxBacktrackDepth: number;\n \n /** Optional callback when a pattern is blocked */\n onBlock?: (message: string, pattern: string) => void;\n \n /** Optional callback for warnings */\n onWarning?: (message: string, pattern: string) => void;\n}\n\n/**\n * Default configuration with secure defaults\n */\nexport const DEFAULT_CONFIG: SafeRegexConfig = {\n maxLength: 500,\n timeoutMs: 1000,\n maxBacktrackDepth: 100000,\n};\n\n/**\n * Result of attempting to create a safe regex\n */\nexport interface SafeRegexResult {\n /** Whether the pattern was deemed safe */\n safe: boolean;\n \n /** The compiled regex if safe */\n regex?: RegExp;\n \n /** Error message if not safe */\n error?: string;\n \n /** Specific reason code for the result */\n reason?: SafeRegexReason;\n}\n\n/**\n * Reason codes for SafeRegexResult\n */\nexport type SafeRegexReason =\n | 'ok'\n | 'pattern_too_long'\n | 'nested_quantifiers'\n | 'overlapping_alternation'\n | 'catastrophic_backtracking'\n | 'invalid_syntax'\n | 'execution_timeout';\n\n/**\n * Result of pattern analysis (internal)\n */\nexport interface PatternAnalysis {\n safe: boolean;\n reason?: SafeRegexReason;\n message?: string;\n}\n\n"],"names":["DEFAULT_CONFIG","maxLength","timeoutMs","maxBacktrackDepth"],"mappings":"AAAA;;;;UAuBaA,cAAAA,GAAkC;IAC3CC,SAAAA,EAAW,GAAA;IACXC,SAAAA,EAAW,IAAA;IACXC,iBAAAA,EAAmB;AACvB;;;;"}
|
package/package.json
ADDED
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@theunwalked/pressurelid",
|
|
3
|
+
"version": "1.0.0",
|
|
4
|
+
"description": "Safe regex handling with ReDoS protection - keeps dangerous patterns under pressure.",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"main": "./dist/pressurelid.cjs",
|
|
7
|
+
"module": "./dist/pressurelid.js",
|
|
8
|
+
"types": "./dist/pressurelid.d.ts",
|
|
9
|
+
"repository": {
|
|
10
|
+
"type": "git",
|
|
11
|
+
"url": "git+https://github.com/utilarium/pressurelid.git"
|
|
12
|
+
},
|
|
13
|
+
"exports": {
|
|
14
|
+
".": {
|
|
15
|
+
"types": "./dist/pressurelid.d.ts",
|
|
16
|
+
"import": "./dist/pressurelid.js",
|
|
17
|
+
"require": "./dist/pressurelid.cjs"
|
|
18
|
+
},
|
|
19
|
+
"./package.json": "./package.json"
|
|
20
|
+
},
|
|
21
|
+
"files": [
|
|
22
|
+
"dist",
|
|
23
|
+
"README.md",
|
|
24
|
+
"LICENSE"
|
|
25
|
+
],
|
|
26
|
+
"scripts": {
|
|
27
|
+
"build": "npm run lint && tsc --noEmit && vite build",
|
|
28
|
+
"dev": "vite build --watch",
|
|
29
|
+
"watch": "vite build --watch",
|
|
30
|
+
"test": "vitest run --coverage",
|
|
31
|
+
"precommit": "npm run lint && npm run test",
|
|
32
|
+
"lint": "eslint . --ext .ts",
|
|
33
|
+
"lint:fix": "eslint . --ext .ts --fix",
|
|
34
|
+
"clean": "rm -rf dist",
|
|
35
|
+
"prepublishOnly": "npm run clean && npm run build"
|
|
36
|
+
},
|
|
37
|
+
"keywords": [
|
|
38
|
+
"regex",
|
|
39
|
+
"redos",
|
|
40
|
+
"security",
|
|
41
|
+
"safe-regex",
|
|
42
|
+
"validation",
|
|
43
|
+
"denial-of-service",
|
|
44
|
+
"pattern-matching"
|
|
45
|
+
],
|
|
46
|
+
"author": "Tim O'Brien <tobrien@discursive.com>",
|
|
47
|
+
"license": "Apache-2.0",
|
|
48
|
+
"homepage": "https://utilarium.github.io/pressurelid/",
|
|
49
|
+
"engines": {
|
|
50
|
+
"node": ">=24.0.0"
|
|
51
|
+
},
|
|
52
|
+
"devDependencies": {
|
|
53
|
+
"@eslint/eslintrc": "^3.3.1",
|
|
54
|
+
"@eslint/js": "^9.30.1",
|
|
55
|
+
"@rollup/plugin-replace": "^6.0.2",
|
|
56
|
+
"@swc/core": "^1.12.11",
|
|
57
|
+
"@types/node": "^25.0.3",
|
|
58
|
+
"@typescript-eslint/eslint-plugin": "^8.36.0",
|
|
59
|
+
"@typescript-eslint/parser": "^8.36.0",
|
|
60
|
+
"@vitest/coverage-v8": "^4.0.16",
|
|
61
|
+
"eslint": "^9.30.1",
|
|
62
|
+
"eslint-plugin-import": "^2.32.0",
|
|
63
|
+
"globals": "^17.0.0",
|
|
64
|
+
"typescript": "^5.8.3",
|
|
65
|
+
"vite": "^7.0.4",
|
|
66
|
+
"vite-plugin-dts": "^4.5.4",
|
|
67
|
+
"vite-plugin-node": "^7.0.0",
|
|
68
|
+
"vitest": "^4.0.16"
|
|
69
|
+
}
|
|
70
|
+
}
|