express-validator-regex-timeout-sm 0.0.0-stage → 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/README.md CHANGED
@@ -1,3 +1,587 @@
1
- # Temporary Holding Version
1
+ # express-validator-regex-timeout-sm
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ [![CI](https://github.com/Smejia11/express-validator-regex-timeout-sm/actions/workflows/ci.yml/badge.svg)](https://github.com/Smejia11/express-validator-regex-timeout-sm/actions/workflows/ci.yml)
4
+ [![CodeQL](https://github.com/Smejia11/express-validator-regex-timeout-sm/actions/workflows/codeql.yml/badge.svg)](https://github.com/Smejia11/express-validator-regex-timeout-sm/actions/workflows/codeql.yml)
5
+ [![OpenSSF Scorecard](https://api.scorecard.dev/projects/github.com/Smejia11/express-validator-regex-timeout-sm/badge)](https://scorecard.dev/viewer/?uri=github.com/Smejia11/express-validator-regex-timeout-sm)
6
+ [![npm](https://img.shields.io/npm/v/express-validator-regex-timeout-sm)](https://www.npmjs.com/package/express-validator-regex-timeout-sm)
7
+ [![License: MIT](https://img.shields.io/badge/license-MIT-blue.svg)](LICENSE)
8
+
9
+ **ReDoS-safe regex validation for [express-validator](https://express-validator.github.io/).**
10
+ Run your patterns with a time limit — synchronously with `node:vm` or asynchronously in a
11
+ worker thread pool — so a malicious input can't freeze your Node.js server.
12
+
13
+ 🌐 **Overview page (Spanish):** [https://smejia11.github.io/express-validator-regex-timeout-sm-page/](https://smejia11.github.io/express-validator-regex-timeout-sm-page/)
14
+
15
+ ```js
16
+ const { body } = require('express-validator');
17
+ const { regexTimeoutAsync } = require('express-validator-regex-timeout-sm');
18
+
19
+ app.post('/users', body('username').custom(regexTimeoutAsync(/[a-z0-9_]{3,16}/)), handler);
20
+ ```
21
+
22
+ Zero runtime dependencies · CommonJS and ESM · TypeScript types included · Node.js ≥ 20
23
+
24
+ 🇪🇸 [Leer en español](README.es.md)
25
+
26
+ ## Contents
27
+
28
+ - [The problem: ReDoS](#the-problem-redos)
29
+ - [How this package solves it](#how-this-package-solves-it)
30
+ - [Installation](#installation)
31
+ - [Quick start](#quick-start)
32
+ - [Sync or async?](#sync-or-async)
33
+ - [Use cases](#use-cases)
34
+ - [API reference](#api-reference)
35
+ - [Security model and limitations](#security-model-and-limitations)
36
+ - [Security practices of this project](#security-practices-of-this-project)
37
+ - [Compatibility](#compatibility)
38
+ - [Contributing, security policy and license](#contributing-security-policy-and-license)
39
+
40
+ ## The problem: ReDoS
41
+
42
+ Most regular expression engines, including V8's (used by Node.js), use *backtracking*.
43
+ Some patterns — typically nested quantifiers such as `(a+)+` or overlapping
44
+ alternatives such as `(a|aa)*` — need an exponential number of steps on certain inputs
45
+ that **do not** match. This is called *catastrophic backtracking*, and an attacker who
46
+ can send such an input causes a **Regular expression Denial of Service (ReDoS)**,
47
+ [CWE-1333](https://cwe.mitre.org/data/definitions/1333.html).
48
+
49
+ Time measured for `/^(a+)+$/.test('a'.repeat(n) + '!')` on Node.js 22:
50
+
51
+ | n (characters) | 20 | 22 | 24 | 26 | 28 |
52
+ |---|---|---|---|---|---|
53
+ | time | 44 ms | 169 ms | 583 ms | 2.3 s | 9.4 s |
54
+
55
+ Each extra character roughly doubles the time: 40 characters would take about 10 hours.
56
+
57
+ Node.js runs your JavaScript on **a single event loop**. While a regular expression is
58
+ backtracking, the process cannot do anything else: every other request, timer and health
59
+ check waits. One short request can take a whole server down, and in Kubernetes the liveness
60
+ probe can start restarting pods.
61
+
62
+ express-validator's built-in `matches()` (and any `regex.test()` in your code) runs the
63
+ expression directly on the event loop, with no time limit. Writing safe patterns is the real
64
+ fix, but in practice vulnerable patterns slip through code review, come from shared
65
+ configuration or from third-party code.
66
+
67
+ ## How this package solves it
68
+
69
+ Every validator applies several independent layers (defense in depth), in this order:
70
+
71
+ 1. **Type allowlist** — only strings are evaluated. Arrays (`?q=a&q=b`), objects
72
+ (`{"$ne": ""}`), numbers and `undefined` are rejected instead of being converted to strings.
73
+ 2. **Length limit** — `maxLength` (default 1000) is checked *before* the regex runs, which
74
+ is cheap and removes most attack inputs.
75
+ 3. **Full match by default** — the pattern is wrapped as `^(?:pattern)$`, so the whole value
76
+ must match. This prevents the two classic validation bugs: forgotten anchors, and the
77
+ `^a|b$` precedence trap (which only checks that the value *starts* with `a` or *ends*
78
+ with `b`).
79
+ 4. **Time limit** — the regex runs with `timeoutMs` (default 50 ms):
80
+ - `regexTimeout()` uses `node:vm`'s `timeout`, which interrupts the regex engine;
81
+ - `regexTimeoutAsync()` runs it in a worker thread that is terminated on timeout, so the
82
+ event loop is never blocked.
83
+ 5. **Fail closed** — a timeout, a full queue or a worker failure *rejects* the value. Error
84
+ messages are generic (they never contain the input or the pattern) and monitoring hooks
85
+ receive the input *length*, never the input itself.
86
+
87
+ Options are validated when the validator is created (unknown options, invalid patterns,
88
+ dangerous flags), so mistakes fail at startup instead of on the first request.
89
+
90
+ ## Installation
91
+
92
+ ```sh
93
+ npm install express-validator-regex-timeout-sm
94
+ ```
95
+
96
+ - Node.js 20 or newer.
97
+ - `express-validator` 6 or newer if you use it (optional peer dependency): the validators are
98
+ plain functions for `.custom()`, so the package itself does not import express-validator.
99
+
100
+ ## Quick start
101
+
102
+ ### CommonJS
103
+
104
+ ```js
105
+ const express = require('express');
106
+ const { body, validationResult } = require('express-validator');
107
+ const { regexTimeoutAsync } = require('express-validator-regex-timeout-sm');
108
+
109
+ const app = express();
110
+ app.use(express.json({ limit: '10kb' }));
111
+
112
+ app.post(
113
+ '/users',
114
+ body('username').custom(regexTimeoutAsync(/[a-z0-9_]{3,16}/, { maxLength: 16 })),
115
+ (req, res) => {
116
+ const result = validationResult(req);
117
+ if (!result.isEmpty()) {
118
+ // Do not send back `value`: express-validator includes the submitted input in each error.
119
+ const errors = result.array().map(({ msg, path, location }) => ({ msg, path, location }));
120
+ return res.status(400).json({ errors });
121
+ }
122
+ res.status(201).json({ username: req.body.username });
123
+ },
124
+ );
125
+ ```
126
+
127
+ ### ES modules
128
+
129
+ ```js
130
+ import { body } from 'express-validator';
131
+ import { regexTimeout, regexTimeoutAsync } from 'express-validator-regex-timeout-sm';
132
+ ```
133
+
134
+ A rejected value produces an express-validator error such as:
135
+
136
+ ```json
137
+ { "type": "field", "value": "John Doe!", "msg": "Value has an invalid format", "path": "username", "location": "body" }
138
+ ```
139
+
140
+ The `msg` from this package never contains the input, but express-validator adds the raw input as
141
+ `value`. Do not return `value` to the client (as in the example above): reflecting a malicious
142
+ payload back can enable injection attacks and leaks data into logs and proxies.
143
+
144
+ ## Sync or async?
145
+
146
+ | | `regexTimeout()` (sync) | `regexTimeoutAsync()` (async) |
147
+ |---|---|---|
148
+ | Where the regex runs | main thread, inside `node:vm` | a worker thread from a pool |
149
+ | Event loop during an attack | blocked for up to `timeoutMs` per value | never blocked |
150
+ | Overhead per validation (measured) | ≈ 0.1 ms (vm watchdog thread) | ≈ 0.05 ms round trip on a warm worker |
151
+ | Extra start-up cost | none | ≈ 30–50 ms per worker start (first use, or after a timeout) |
152
+ | Extra resources | none | one thread per worker (`size`, default 1) |
153
+ | Recommended for | internal tools, scripts, low-traffic services | public endpoints and anything reachable by attackers |
154
+
155
+ Both give exactly the same validation result (this is checked by differential tests).
156
+
157
+ ## Use cases
158
+
159
+ ### 1. Validate a body field
160
+
161
+ ```js
162
+ const { body } = require('express-validator');
163
+ const { regexTimeout } = require('express-validator-regex-timeout-sm');
164
+
165
+ const isUsername = regexTimeout(/[a-z0-9_]{3,16}/, { maxLength: 16 });
166
+
167
+ app.post('/users', body('username').custom(isUsername), handler);
168
+ ```
169
+
170
+ Create the validator **once** (at module load) and reuse it: the pattern is compiled and the
171
+ options are validated only once.
172
+
173
+ ### 2. Public endpoints: never block the event loop
174
+
175
+ ```js
176
+ const { regexTimeoutAsync } = require('express-validator-regex-timeout-sm');
177
+
178
+ const isCoupon = regexTimeoutAsync(/[A-Z0-9]{4}(?:-[A-Z0-9]{4}){3}/, { timeoutMs: 100 });
179
+
180
+ app.post('/redeem', body('coupon').custom(isCoupon), handler);
181
+ ```
182
+
183
+ Without a `pool` option, async validators share one lazily created pool
184
+ (`getDefaultPool()`), with one worker by default.
185
+
186
+ ### 3. Query strings, route parameters, headers and cookies
187
+
188
+ ```js
189
+ const { query, param, header, cookie } = require('express-validator');
190
+
191
+ app.get('/search', query('q').custom(regexTimeout(/[\p{L}\p{N} ]{1,50}/u, { maxLength: 50 })), handler);
192
+ app.get('/products/:sku', param('sku').custom(regexTimeout(/[A-Z]{3}-\d{4}/)), handler);
193
+ app.get('/me', header('x-request-id').custom(regexTimeout(/[0-9a-f-]{36}/i)), handler);
194
+ app.get('/prefs', cookie('theme').custom(regexTimeout(/light|dark/)), handler); // needs cookie-parser
195
+ ```
196
+
197
+ `?q=a&q=b` arrives as an array and is rejected with "Value must be a string" (express-validator's
198
+ standard validators would instead validate each element converted to a string).
199
+
200
+ ### 4. Arrays and nested fields
201
+
202
+ ```js
203
+ app.post(
204
+ '/posts',
205
+ body('tags').isArray({ min: 1, max: 10 }),
206
+ body('tags.*').custom(regexTimeoutAsync(/[a-z0-9-]{2,30}/)).withMessage('Invalid tag'),
207
+ body('author.email').custom(regexTimeoutAsync(/[^@\s]+@[^@\s]+\.[a-z]{2,}/i, { maxLength: 254 })),
208
+ handler,
209
+ );
210
+ ```
211
+
212
+ ### 5. `checkSchema()`
213
+
214
+ ```js
215
+ const { checkSchema } = require('express-validator');
216
+
217
+ app.post(
218
+ '/signup',
219
+ checkSchema(
220
+ {
221
+ email: { custom: { options: regexTimeoutAsync(/[^@\s]+@[^@\s]+\.[a-z]{2,}/i, { maxLength: 254 }) } },
222
+ nickname: { optional: true, custom: { options: regexTimeout(/[a-zA-Z]{2,12}/) } },
223
+ },
224
+ ['body'],
225
+ ),
226
+ handler,
227
+ );
228
+ ```
229
+
230
+ ### 6. Combine with other validators
231
+
232
+ Put cheap checks first and use `.bail()` so the regex only runs when they pass:
233
+
234
+ ```js
235
+ body('name')
236
+ .optional()
237
+ .isLength({ max: 40 }).withMessage('Too long')
238
+ .bail()
239
+ .custom(regexTimeout(/[\p{L} '-]+/u, { maxLength: 40 }))
240
+ .withMessage('Use only letters, spaces, apostrophes and hyphens');
241
+ ```
242
+
243
+ `.withMessage()` replaces the message of the validator just before it, including ours.
244
+
245
+ ### 7. Custom or translated messages
246
+
247
+ ```js
248
+ const isPhone = regexTimeout(/\+?[0-9]{7,15}/, {
249
+ maxLength: 16,
250
+ messages: {
251
+ notString: 'Debe ser texto',
252
+ tooLong: 'Máximo 16 caracteres',
253
+ noMatch: 'Número de teléfono inválido',
254
+ timeout: 'No se pudo validar a tiempo',
255
+ unavailable: 'No se pudo validar, intenta de nuevo',
256
+ },
257
+ });
258
+ ```
259
+
260
+ Keep messages generic: never include the submitted value.
261
+
262
+ ### 8. Detect and log ReDoS attempts
263
+
264
+ ```js
265
+ const isCode = regexTimeoutAsync(/(?:[a-z]+\d*)+/, {
266
+ onTimeout(info) {
267
+ logger.warn(
268
+ {
269
+ event: 'regex_timeout',
270
+ path: info.path, // field, e.g. "code"
271
+ location: info.location, // "body", "query"...
272
+ inputLength: info.inputLength,
273
+ pattern: info.pattern,
274
+ timeoutMs: info.timeoutMs,
275
+ },
276
+ 'Possible ReDoS attempt',
277
+ );
278
+ },
279
+ });
280
+ ```
281
+
282
+ A timeout on a pattern you wrote is either an attack or a pattern that needs fixing; both deserve
283
+ an alert. Hooks can be async; if a hook throws or rejects, validation still fails closed and a
284
+ single process warning (`REGEX_TIMEOUT_HOOK_ERROR`) is emitted per hook.
285
+
286
+ ### 9. Answer 503 when a value could not be validated
287
+
288
+ A full queue or a closed pool is not the client's fault. The hooks receive express-validator's
289
+ `meta` object (with `req`), so you can flag the request:
290
+
291
+ ```js
292
+ const isCode = regexTimeoutAsync(/[A-Z0-9]{8}/, {
293
+ onUnavailable: (info, meta) => {
294
+ meta.req.validationUnavailable = true;
295
+ },
296
+ });
297
+
298
+ app.post('/redeem', body('code').custom(isCode), (req, res) => {
299
+ const result = validationResult(req);
300
+ if (!result.isEmpty()) {
301
+ const status = req.validationUnavailable ? 503 : 400;
302
+ const errors = result.array().map(({ msg, path, location }) => ({ msg, path, location }));
303
+ return res.status(status).json({ errors });
304
+ }
305
+ // ...
306
+ });
307
+ ```
308
+
309
+ ### 10. Size and tune the worker pool
310
+
311
+ ```js
312
+ import { createRegexWorkerPool, regexTimeoutAsync } from 'express-validator-regex-timeout-sm';
313
+
314
+ const pool = createRegexWorkerPool({
315
+ size: 2, // parallel evaluations (worker threads)
316
+ maxQueue: 50, // waiting tasks; more are rejected at once
317
+ maxWaitMs: 500, // a task waits at most 500 ms for a free worker
318
+ resourceLimits: { maxOldGenerationSizeMb: 32 },
319
+ });
320
+
321
+ await pool.warmup(); // optional: start the workers before accepting traffic
322
+
323
+ const isSlug = regexTimeoutAsync(/[a-z0-9]+(?:-[a-z0-9]+)*/, { pool });
324
+
325
+ // Metrics / health checks:
326
+ console.log(pool.stats); // { size: 2, workers: 2, busy: 0, queued: 0 }
327
+ ```
328
+
329
+ Guidelines:
330
+
331
+ - Use a **dedicated pool** for endpoints exposed to anonymous users, so an attack on them cannot
332
+ slow down validation elsewhere.
333
+ - Under attack each timeout costs `timeoutMs` plus a worker restart. Worst-case wait for a queued
334
+ task is bounded by `maxWaitMs`. Combine this package with **rate limiting** (for example
335
+ `express-rate-limit`) and request size limits (`express.json({ limit })`).
336
+ - `size` should not exceed the CPU cores you can spare.
337
+
338
+ ### 11. Graceful shutdown
339
+
340
+ Idle workers never keep the process alive, but closing pools explicitly is cleaner:
341
+
342
+ ```js
343
+ const { closeDefaultPool } = require('express-validator-regex-timeout-sm');
344
+
345
+ process.on('SIGTERM', () => {
346
+ server.close(async () => {
347
+ await Promise.all([pool.close(), closeDefaultPool()]);
348
+ });
349
+ });
350
+ ```
351
+
352
+ Tasks still running or queued when a pool closes are rejected (fail closed).
353
+
354
+ ### 12. Patterns from configuration
355
+
356
+ ```js
357
+ // config.json: { "skuPattern": "[A-Z]{3}-\\d{4}", "skuFlags": "" }
358
+ const isSku = regexTimeout(config.skuPattern, { flags: config.skuFlags });
359
+ ```
360
+
361
+ The pattern is compiled when the validator is created, so an invalid pattern stops the
362
+ application at startup. Patterns must come from developers or trusted configuration —
363
+ **never from user input** (see [Security model](#security-model-and-limitations)).
364
+
365
+ ### 13. Search instead of full match
366
+
367
+ ```js
368
+ // Passes if the value *contains* a digit anywhere.
369
+ const hasDigit = regexTimeout(/\d/, { fullMatch: false });
370
+ ```
371
+
372
+ With `fullMatch: false` the `m` flag is allowed. With the default `fullMatch: true` it is rejected,
373
+ because it turns `^`/`$` into line anchors and `"evil\nvalid"` would pass.
374
+
375
+ ### 14. Unicode
376
+
377
+ ```js
378
+ const isName = regexTimeout(/[\p{L}\p{M}' -]{1,60}/u, { maxLength: 60 });
379
+ isName('José María'); // true
380
+ ```
381
+
382
+ `maxLength` counts UTF-16 code units (JavaScript `string.length`): an emoji such as 😀 counts as 2.
383
+ Consider normalizing input (`value.normalize('NFC')`) with a sanitizer before validating.
384
+
385
+ ### 15. Without express-validator
386
+
387
+ The validators are plain functions, and the low-level helpers return booleans:
388
+
389
+ ```js
390
+ const { regexTimeoutAsync, testWithTimeoutAsync, RegexValidationError } = require('express-validator-regex-timeout-sm');
391
+
392
+ // Plain Express middleware
393
+ const isSku = regexTimeoutAsync(/[A-Z]{3}-\d{4}/);
394
+
395
+ async function validateSku(req, res, next) {
396
+ try {
397
+ await isSku(req.params.sku);
398
+ next();
399
+ } catch (err) {
400
+ if (err instanceof RegexValidationError) {
401
+ res.status(400).json({ error: err.message });
402
+ return;
403
+ }
404
+ next(err);
405
+ }
406
+ }
407
+
408
+ app.get('/products/:sku', validateSku, showProduct);
409
+
410
+ // Scripts, queues, other frameworks
411
+ async function isValidSku(text) {
412
+ return testWithTimeoutAsync(/[A-Z]{3}-\d{4}/, text, { timeoutMs: 100 });
413
+ }
414
+ ```
415
+
416
+ `testWithTimeout()` / `testWithTimeoutAsync()` compile the pattern on every call; prefer the
417
+ validators in hot paths.
418
+
419
+ ### 16. Testing your application
420
+
421
+ ```js
422
+ const { closeDefaultPool } = require('express-validator-regex-timeout-sm');
423
+
424
+ afterAll(async () => {
425
+ await closeDefaultPool(); // and close any pool you created
426
+ });
427
+ ```
428
+
429
+ ### 17. TypeScript
430
+
431
+ Types are included for both module systems:
432
+
433
+ ```ts
434
+ import { body } from 'express-validator';
435
+ import {
436
+ regexTimeoutAsync,
437
+ RegexValidationError,
438
+ codes,
439
+ type RegexEventInfo,
440
+ } from 'express-validator-regex-timeout-sm';
441
+
442
+ const isUsername = regexTimeoutAsync(/[a-z0-9_]{3,16}/, {
443
+ onTimeout: (info: RegexEventInfo) => metrics.increment('regex_timeout', { field: info.path }),
444
+ });
445
+
446
+ router.post('/users', body('username').custom(isUsername));
447
+ ```
448
+
449
+ ## API reference
450
+
451
+ ### `regexTimeout(pattern, options?)`
452
+
453
+ Creates a **synchronous** validator `(value, meta?) => true`. It returns `true` or throws a
454
+ `RegexValidationError`.
455
+
456
+ ### `regexTimeoutAsync(pattern, options?)`
457
+
458
+ Creates an **asynchronous** validator `(value, meta?) => Promise<true>`. It resolves to `true` or
459
+ rejects with a `RegexValidationError`. It never throws synchronously.
460
+
461
+ `pattern` is a `RegExp` or a string. Options (both validators):
462
+
463
+ | Option | Type | Default | Description |
464
+ |---|---|---|---|
465
+ | `timeoutMs` | integer 1–60000 | `50` | Maximum evaluation time. |
466
+ | `maxLength` | integer ≥ 0 | `1000` | Maximum length (UTF-16 code units), checked before the regex runs. |
467
+ | `flags` | string | `''` | Flags for **string** patterns only. `g` and `y` are rejected (they make `test()` stateful). |
468
+ | `fullMatch` | boolean | `true` | Wrap the pattern as `^(?:pattern)$`. `m` is rejected when `true`. |
469
+ | `messages` | object | see below | Custom messages: `notString`, `tooLong`, `noMatch`, `timeout`, `unavailable`. |
470
+ | `onTimeout` | `(info, meta) => unknown` | — | Called when an evaluation times out. |
471
+ | `onUnavailable` | `(info, meta) => unknown` | — | Called when a value could not be evaluated (queue full, queue timeout, closed pool, worker or engine failure). |
472
+ | `pool` | `RegexWorkerPool` | shared pool | **Async only.** Pool to run the evaluation in. |
473
+
474
+ Unknown options throw a `TypeError` (this catches typos like `timeout` instead of `timeoutMs`).
475
+
476
+ Default messages:
477
+
478
+ | Code | Default message |
479
+ |---|---|
480
+ | `ERR_VALUE_NOT_STRING` | `Value must be a string` |
481
+ | `ERR_VALUE_TOO_LONG` | `Value must be at most {maxLength} characters long` |
482
+ | `ERR_VALUE_NO_MATCH` | `Value has an invalid format` |
483
+ | `ERR_VALUE_TIMEOUT` | `Value could not be validated in time` |
484
+ | `ERR_VALUE_UNAVAILABLE` | `Value could not be validated` |
485
+
486
+ Hook `info` object (frozen): `{ code, mode: 'sync' | 'async', pattern, flags, timeoutMs, inputLength, path?, location?, cause }`.
487
+ `pattern` is the effective pattern (after the full-match wrapping). `meta` is express-validator's
488
+ `meta` argument (`{ req, location, path, ... }`), or `undefined` outside express-validator.
489
+
490
+ ### `testWithTimeout(pattern, input, options?)` → `boolean`
491
+
492
+ Synchronous helper. Options: `timeoutMs`, `flags`, `fullMatch`. Throws `RegexTimeoutError` on timeout
493
+ and `TypeError` if `input` is not a string.
494
+
495
+ ### `testWithTimeoutAsync(pattern, input, options?)` → `Promise<boolean>`
496
+
497
+ Asynchronous helper. Options: `timeoutMs`, `flags`, `fullMatch`, `pool`. Rejects with
498
+ `RegexTimeoutError` or `RegexPoolError`.
499
+
500
+ ### `createRegexWorkerPool(options?)` / `new RegexWorkerPool(options?)`
501
+
502
+ | Option | Type | Default | Description |
503
+ |---|---|---|---|
504
+ | `size` | integer 1–64 | `1` | Number of worker threads (parallel evaluations). |
505
+ | `maxQueue` | integer ≥ 0 | `100` | Tasks allowed to wait for a free worker; more are rejected with `ERR_REGEX_QUEUE_FULL`. |
506
+ | `maxWaitMs` | integer ≥ 1 | `1000` | Maximum time in the queue; then `ERR_REGEX_QUEUE_TIMEOUT`. |
507
+ | `resourceLimits` | object | `{ maxOldGenerationSizeMb: 32, maxYoungGenerationSizeMb: 8, codeRangeSizeMb: 8, stackSizeMb: 4 }` | Per-worker limits (values from 1 to 65536; `stackSizeMb` up to 1024). Very small values are rejected because they can crash Node.js. |
508
+
509
+ Members:
510
+
511
+ - `pool.test(pattern, input, options?)` → `Promise<boolean>` (options: `timeoutMs`, `flags`, `fullMatch`).
512
+ - `pool.warmup()` → `Promise<void>`: starts all workers now.
513
+ - `pool.close()` → `Promise<void>`: terminates the workers and rejects pending tasks with `ERR_REGEX_POOL_CLOSED`. Idempotent.
514
+ - `pool.stats` → `{ size, workers, busy, queued }`.
515
+ - `pool.size`, `pool.closed`.
516
+
517
+ Workers start lazily, run with an empty environment (`env: {}`, so they cannot read secrets from
518
+ `process.env`), no inherited `execArgv`, and the configured `resourceLimits`. Idle workers are
519
+ `unref()`-ed, so they never keep the process alive.
520
+
521
+ ### `getDefaultPool()` / `closeDefaultPool()`
522
+
523
+ The shared pool used when no `pool` option is given. It is created on first use (and again after
524
+ `closeDefaultPool()`).
525
+
526
+ ### Errors
527
+
528
+ | Class | `code` values | Thrown by |
529
+ |---|---|---|
530
+ | `RegexValidationError` | `ERR_VALUE_NOT_STRING`, `ERR_VALUE_TOO_LONG`, `ERR_VALUE_NO_MATCH`, `ERR_VALUE_TIMEOUT`, `ERR_VALUE_UNAVAILABLE` | the validators (`cause` holds the underlying error) |
531
+ | `RegexTimeoutError` | `ERR_REGEX_TIMEOUT` (+ `timeoutMs`, `inputLength`) | helpers and pools |
532
+ | `RegexPoolError` | `ERR_REGEX_QUEUE_FULL`, `ERR_REGEX_QUEUE_TIMEOUT`, `ERR_REGEX_POOL_CLOSED`, `ERR_REGEX_WORKER_FAILED`, `ERR_REGEX_EXECUTION_FAILED` | async helpers and pools |
533
+
534
+ All codes are also available as constants in `codes` (for example `codes.VALUE_TIMEOUT`).
535
+ Invalid patterns throw `SyntaxError`; invalid options throw `TypeError` or `RangeError`.
536
+
537
+ ### `defaults`
538
+
539
+ A frozen object with the default values listed above.
540
+
541
+ ## Security model and limitations
542
+
543
+ - **This package protects against malicious input, not malicious patterns.** Patterns must be
544
+ written by developers or come from trusted configuration. Never build a pattern from user
545
+ input — use a fixed pattern, or escape the text first.
546
+ - **`node:vm` is not a security sandbox** and is not used as one: it is only used for its
547
+ `timeout` option. The code it runs is a constant written by this package; the input is passed
548
+ as data.
549
+ - **Sync mode still spends up to `timeoutMs` of main-thread CPU per malicious value.** An attacker
550
+ sending many requests can degrade a service that uses only `regexTimeout()`. Use
551
+ `regexTimeoutAsync()` on public endpoints, keep `timeoutMs` small, and add rate limiting.
552
+ - **Async mode bounds, but does not eliminate, the cost of an attack**: each timeout uses one
553
+ worker for `timeoutMs` and restarts it. `size`, `maxQueue` and `maxWaitMs` keep resource usage
554
+ and waiting time bounded, and everything fails closed.
555
+ - **A timeout is a mitigation, not a fix.** Prefer patterns without nested quantifiers or
556
+ overlapping alternatives, test them with long non-matching inputs, and consider a linear-time
557
+ engine such as [RE2](https://github.com/google/re2) for complex patterns.
558
+ - `maxLength` counts UTF-16 code units, not bytes or user-perceived characters.
559
+ - Requires `worker_threads` (Node.js). If you bundle your server (webpack, esbuild…), mark this
560
+ package as external so that `lib/worker.js` stays available at runtime.
561
+
562
+ Further reading: OpenSSF's
563
+ [Correctly Using Regular Expressions for Secure Input Validation](https://best.openssf.org/Correctly-Using-Regular-Expressions)
564
+ and OWASP's
565
+ [ReDoS article](https://owasp.org/www-community/attacks/Regular_expression_Denial_of_Service_-_ReDoS).
566
+
567
+ ## Security practices of this project
568
+
569
+ This project follows the [OpenSSF](https://openssf.org/) recommendations taught in the Linux
570
+ Foundation course *Developing Secure Software (LFD121)*: zero runtime dependencies, least privilege
571
+ in the code and in CI, actions pinned by commit SHA, CodeQL, OpenSSF Scorecard, Dependabot,
572
+ npm provenance, a security policy and a documented release process. See
573
+ [docs/SECURITY-PRACTICES.md](docs/SECURITY-PRACTICES.md) for the full mapping.
574
+
575
+ ## Compatibility
576
+
577
+ - Node.js ≥ 20 (tested in CI on 20, 22, 24 and 26 on Linux, and on 24 on macOS and Windows).
578
+ - express-validator ≥ 6 (tested with 7) and Express 4 or 5 (tested with 5).
579
+ - CommonJS (`require`) and ES modules (`import`). Both entry points share the same
580
+ implementation, so `instanceof` checks and the default pool are the same from both.
581
+ - TypeScript types for both entry points, with no dependency on `@types/node` or express-validator's types.
582
+
583
+ ## Contributing, security policy and license
584
+
585
+ - Contributions are welcome: see [CONTRIBUTING.md](CONTRIBUTING.md).
586
+ - Please report vulnerabilities privately as described in [SECURITY.md](SECURITY.md).
587
+ - [MIT](LICENSE) © Santiago Mejía Oquendo
package/SECURITY.md ADDED
@@ -0,0 +1,66 @@
1
+ # Security Policy
2
+
3
+ This package exists to make input validation safer, so security reports are very welcome.
4
+
5
+ ## Supported versions
6
+
7
+ | Version | Supported |
8
+ |---|---|
9
+ | 1.x (latest minor) | ✅ |
10
+ | < 1.0 | ❌ |
11
+
12
+ Security fixes are released as a new patch or minor version of the latest major line.
13
+
14
+ ## Reporting a vulnerability
15
+
16
+ **Please do not report security vulnerabilities through public GitHub issues, discussions or pull
17
+ requests.**
18
+
19
+ Report them privately through GitHub's private vulnerability reporting:
20
+ <https://github.com/Smejia11/express-validator-regex-timeout-sm/security/advisories/new>
21
+
22
+ Please include:
23
+
24
+ - the affected version(s) and the Node.js version;
25
+ - a description of the issue and its impact;
26
+ - a minimal proof of concept (pattern, options and input), if possible;
27
+ - any suggested fix or mitigation.
28
+
29
+ ## What to expect
30
+
31
+ - **Acknowledgement** within 7 days.
32
+ - **Initial assessment** (confirmed or not, severity) within 14 days.
33
+ - **Fix**: we aim to release a fix within 30 days for critical/high severity issues and within
34
+ 60 days for the rest. Publicly known vulnerabilities are prioritised.
35
+ - **Disclosure**: once a fix is available we publish a GitHub Security Advisory (requesting a CVE
36
+ when appropriate) and credit the reporter, unless they prefer to stay anonymous.
37
+
38
+ Please give us a reasonable time to release a fix before any public disclosure.
39
+
40
+ ## Scope
41
+
42
+ In scope, for example:
43
+
44
+ - a way to make a validator block the event loop for (much) longer than `timeoutMs`, or to make
45
+ `regexTimeoutAsync()` block it at all;
46
+ - a value accepted when it should be rejected (bypass of the type check, `maxLength` or the
47
+ full-match wrapping);
48
+ - input data leaking into error messages or hook information;
49
+ - a crash of the host process caused by input data;
50
+ - problems in the published package or in the release pipeline (supply chain).
51
+
52
+ Out of scope:
53
+
54
+ - patterns supplied by an attacker: patterns must be written by developers (see
55
+ "Security model and limitations" in the README);
56
+ - denial of service that only consumes the resources allowed by the documented limits
57
+ (`timeoutMs`, pool `size`, `maxQueue`, `maxWaitMs`).
58
+
59
+ ## Verifying releases
60
+
61
+ Releases are published from GitHub Actions with npm provenance. You can verify the registry
62
+ signatures and provenance attestations of your installed dependencies with:
63
+
64
+ ```sh
65
+ npm audit signatures
66
+ ```
@@ -0,0 +1,2 @@
1
+ // Types for the ESM entry point: the same API as the CommonJS entry point.
2
+ export * from '../lib/index.js';
package/esm/index.mjs ADDED
@@ -0,0 +1,21 @@
1
+ // ESM entry point. It re-exports the CommonJS implementation instead of
2
+ // shipping a second copy of the code, so `import` and `require` share the
3
+ // same classes and the same default worker pool (no "dual package hazard":
4
+ // `instanceof` checks and pools work the same from both module systems).
5
+ import cjs from '../lib/index.js';
6
+
7
+ export const {
8
+ regexTimeout,
9
+ regexTimeoutAsync,
10
+ testWithTimeout,
11
+ testWithTimeoutAsync,
12
+ RegexWorkerPool,
13
+ createRegexWorkerPool,
14
+ getDefaultPool,
15
+ closeDefaultPool,
16
+ codes,
17
+ RegexTimeoutError,
18
+ RegexPoolError,
19
+ RegexValidationError,
20
+ defaults,
21
+ } = cjs;