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/CHANGELOG.md ADDED
@@ -0,0 +1,24 @@
1
+ # Changelog
2
+
3
+ All notable changes to this project are documented in this file.
4
+ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
5
+ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
6
+
7
+ ## [1.0.0] - Unreleased
8
+
9
+ ### Added
10
+
11
+ - `regexTimeout()`: synchronous validator for express-validator's `.custom()` that runs the
12
+ regular expression in `node:vm` with a timeout.
13
+ - `regexTimeoutAsync()`: asynchronous validator that runs the regular expression in a worker
14
+ thread, terminating the worker on timeout so the event loop is never blocked.
15
+ - `testWithTimeout()` and `testWithTimeoutAsync()` low-level helpers.
16
+ - `RegexWorkerPool` / `createRegexWorkerPool()` with `size`, `maxQueue`, `maxWaitMs` and
17
+ `resourceLimits`, plus `warmup()`, `close()` and `stats`; shared default pool
18
+ (`getDefaultPool()`, `closeDefaultPool()`).
19
+ - Secure defaults: type allowlist (strings only), `maxLength` checked before the regex,
20
+ full-match wrapping (`^(?:pattern)$`), 50 ms timeout, rejection of the `g`/`y` flags (and of
21
+ `m` in full-match mode), rejection of unknown options, fail-closed behaviour.
22
+ - `onTimeout` / `onUnavailable` monitoring hooks that never receive the input value.
23
+ - Error classes `RegexValidationError`, `RegexTimeoutError`, `RegexPoolError` and `codes`.
24
+ - CommonJS and ES module entry points sharing one implementation, and TypeScript types.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Santiago Mejía Oquendo
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.es.md ADDED
@@ -0,0 +1,162 @@
1
+ # express-validator-regex-timeout-sm (español)
2
+
3
+ **Validación con expresiones regulares protegida contra ReDoS para
4
+ [express-validator](https://express-validator.github.io/).** Ejecuta tus patrones con un límite de
5
+ tiempo, ya sea de forma síncrona con `node:vm` o asíncrona en un pool de *worker threads*, para que
6
+ una entrada maliciosa no congele tu servidor Node.js.
7
+
8
+ 🌐 **Página de presentación:** [https://smejia11.github.io/express-validator-regex-timeout-sm-page/](https://smejia11.github.io/express-validator-regex-timeout-sm-page/)
9
+
10
+ ```js
11
+ const { body } = require('express-validator');
12
+ const { regexTimeoutAsync } = require('express-validator-regex-timeout-sm');
13
+
14
+ app.post('/users', body('username').custom(regexTimeoutAsync(/[a-z0-9_]{3,16}/)), handler);
15
+ ```
16
+
17
+ Sin dependencias en tiempo de ejecución · CommonJS y ESM · tipos de TypeScript incluidos · Node.js ≥ 20
18
+
19
+ > La referencia completa de la API está en el [README en inglés](README.md#api-reference).
20
+
21
+ ## El problema: ReDoS
22
+
23
+ El motor de expresiones regulares de V8 (el que usa Node.js) trabaja con *backtracking*. Algunos
24
+ patrones, sobre todo los cuantificadores anidados como `(a+)+` o las alternativas que se solapan
25
+ como `(a|aa)*`, necesitan un número exponencial de pasos con ciertas entradas que **no** coinciden.
26
+ Esto se llama *backtracking catastrófico*. Si un atacante puede enviar esa entrada, provoca una
27
+ **denegación de servicio por expresión regular (ReDoS)**,
28
+ [CWE-1333](https://cwe.mitre.org/data/definitions/1333.html).
29
+
30
+ Tiempo medido para `/^(a+)+$/.test('a'.repeat(n) + '!')` en Node.js 22:
31
+
32
+ | n (caracteres) | 20 | 22 | 24 | 26 | 28 |
33
+ |---|---|---|---|---|---|
34
+ | tiempo | 44 ms | 169 ms | 583 ms | 2,3 s | 9,4 s |
35
+
36
+ Cada carácter extra duplica más o menos el tiempo: con 40 caracteres serían unas 10 horas.
37
+
38
+ Node.js ejecuta tu JavaScript en **un único event loop**. Mientras la regex hace backtracking, el
39
+ proceso no puede hacer nada más: todas las demás peticiones, timers y health checks esperan. Una
40
+ sola petición corta puede tumbar el servidor, y en Kubernetes la *liveness probe* puede empezar a
41
+ reiniciar los pods.
42
+
43
+ El `matches()` de express-validator (y cualquier `regex.test()` de tu código) ejecuta la expresión
44
+ directamente en el event loop, sin límite de tiempo.
45
+
46
+ ## Cómo lo resuelve
47
+
48
+ Cada validador aplica varias capas independientes (defensa en profundidad), en este orden:
49
+
50
+ 1. **Lista blanca de tipos**: solo se evalúan strings. Los arrays (`?q=a&q=b`), los objetos
51
+ (`{"$ne": ""}`), los números y `undefined` se rechazan en lugar de convertirse a texto.
52
+ 2. **Límite de longitud**: `maxLength` (1000 por defecto) se comprueba *antes* de ejecutar la regex.
53
+ 3. **Coincidencia completa por defecto**: el patrón se envuelve como `^(?:patrón)$`. Así se evitan
54
+ los dos errores clásicos: olvidar las anclas y la trampa de precedencia de `^a|b$`.
55
+ 4. **Límite de tiempo** (`timeoutMs`, 50 ms por defecto):
56
+ - `regexTimeout()` usa el `timeout` de `node:vm`, que interrumpe el motor de regex;
57
+ - `regexTimeoutAsync()` la ejecuta en un worker que se termina si se pasa del tiempo, así que el
58
+ event loop nunca se bloquea.
59
+ 5. **Falla de forma segura** (*fail closed*): un timeout, una cola llena o un worker caído
60
+ **rechazan** el valor. Los mensajes son genéricos (nunca incluyen la entrada ni el patrón) y los
61
+ hooks de monitoreo reciben la *longitud* de la entrada, nunca su contenido.
62
+
63
+ Las opciones se validan al crear el validador (opciones desconocidas, patrones inválidos, flags
64
+ peligrosos), así que los errores aparecen al arrancar y no con la primera petición.
65
+
66
+ ## Instalación
67
+
68
+ ```sh
69
+ npm install express-validator-regex-timeout-sm
70
+ ```
71
+
72
+ ## ¿Síncrono o asíncrono?
73
+
74
+ | | `regexTimeout()` (síncrono) | `regexTimeoutAsync()` (asíncrono) |
75
+ |---|---|---|
76
+ | Dónde corre la regex | hilo principal, dentro de `node:vm` | un worker de un pool |
77
+ | Event loop durante un ataque | bloqueado hasta `timeoutMs` por valor | nunca se bloquea |
78
+ | Costo por validación (medido) | ≈ 0,1 ms | ≈ 0,05 ms con el worker ya iniciado |
79
+ | Costo de arranque | ninguno | ≈ 30–50 ms por worker (primer uso o tras un timeout) |
80
+ | Recomendado para | herramientas internas, scripts, poco tráfico | endpoints públicos |
81
+
82
+ ## Casos de uso principales
83
+
84
+ ```js
85
+ const { body, query, checkSchema, validationResult } = require('express-validator');
86
+ const {
87
+ regexTimeout,
88
+ regexTimeoutAsync,
89
+ createRegexWorkerPool,
90
+ } = require('express-validator-regex-timeout-sm');
91
+
92
+ // 1. Campo del body (crea el validador una sola vez y reutilízalo)
93
+ const isUsername = regexTimeoutAsync(/[a-z0-9_]{3,16}/, { maxLength: 16 });
94
+ app.post('/users', body('username').custom(isUsername), handler);
95
+
96
+ // 2. Query string: ?q=a&q=b llega como array y se rechaza
97
+ app.get('/search', query('q').custom(regexTimeout(/[\p{L}\p{N} ]{1,50}/u, { maxLength: 50 })), handler);
98
+
99
+ // 3. Cada elemento de un array
100
+ app.post('/posts', body('tags.*').custom(regexTimeoutAsync(/[a-z0-9-]{2,30}/)).withMessage('Etiqueta inválida'), handler);
101
+
102
+ // 4. checkSchema()
103
+ app.post('/signup', checkSchema({
104
+ email: { custom: { options: regexTimeoutAsync(/[^@\s]+@[^@\s]+\.[a-z]{2,}/i, { maxLength: 254 }) } },
105
+ }, ['body']), handler);
106
+
107
+ // 5. Mensajes propios (genéricos: nunca repitas el valor enviado)
108
+ const isPhone = regexTimeout(/\+?[0-9]{7,15}/, {
109
+ messages: { noMatch: 'Número de teléfono inválido', timeout: 'No se pudo validar a tiempo' },
110
+ });
111
+
112
+ // 6. Detectar intentos de ReDoS y responder 503 si no se pudo validar
113
+ const isCode = regexTimeoutAsync(/[A-Z0-9]{8}/, {
114
+ onTimeout: (info) => logger.warn({ campo: info.path, longitud: info.inputLength }, 'Posible ReDoS'),
115
+ onUnavailable: (info, meta) => { meta.req.validationUnavailable = true; },
116
+ });
117
+ app.post('/redeem', body('code').custom(isCode), (req, res) => {
118
+ const result = validationResult(req);
119
+ if (!result.isEmpty()) {
120
+ // No devuelvas `value`: express-validator incluye ahí la entrada original.
121
+ const errors = result.array().map(({ msg, path, location }) => ({ msg, path, location }));
122
+ return res.status(req.validationUnavailable ? 503 : 400).json({ errors });
123
+ }
124
+ // ...
125
+ });
126
+
127
+ // 7. Pool dedicado para endpoints expuestos a usuarios anónimos
128
+ const pool = createRegexWorkerPool({ size: 2, maxQueue: 50, maxWaitMs: 500 });
129
+ pool.warmup(); // opcional: arranca los workers antes de recibir tráfico (devuelve una promesa)
130
+ const isSlug = regexTimeoutAsync(/[a-z0-9]+(?:-[a-z0-9]+)*/, { pool });
131
+
132
+ // 8. Apagado ordenado
133
+ process.on('SIGTERM', () => server.close(() => pool.close()));
134
+ ```
135
+
136
+ En el [README en inglés](README.md#use-cases) hay 17 casos de uso: parámetros de ruta, headers,
137
+ cookies, `.bail()`, patrones desde configuración, `fullMatch: false`, Unicode, uso sin
138
+ express-validator, pruebas y TypeScript.
139
+
140
+ ## Modelo de seguridad y limitaciones
141
+
142
+ - **Protege contra entradas maliciosas, no contra patrones maliciosos.** Los patrones deben
143
+ escribirlos los desarrolladores o venir de configuración confiable. **Nunca** construyas un
144
+ patrón con datos del usuario.
145
+ - `node:vm` **no es un sandbox de seguridad** y aquí no se usa como tal: solo se aprovecha su
146
+ `timeout`.
147
+ - El modo síncrono sigue gastando hasta `timeoutMs` de CPU del hilo principal por cada valor
148
+ malicioso. En endpoints públicos usa `regexTimeoutAsync()` y añade rate limiting.
149
+ - El timeout es una mitigación, no la solución de fondo: evita los cuantificadores anidados y las
150
+ alternativas que se solapan, o usa un motor lineal como RE2.
151
+ - `maxLength` cuenta unidades UTF-16 (`string.length`): un emoji cuenta como 2.
152
+
153
+ ## Prácticas de seguridad del proyecto
154
+
155
+ El proyecto aplica las recomendaciones de la [OpenSSF](https://openssf.org/) que se enseñan en el
156
+ curso *Developing Secure Software (LFD121)* de la Linux Foundation. El detalle está en
157
+ [docs/SECURITY-PRACTICES.md](docs/SECURITY-PRACTICES.md).
158
+
159
+ Para reportar una vulnerabilidad, sigue [SECURITY.md](SECURITY.md) (de forma privada, nunca en un
160
+ issue público).
161
+
162
+ Licencia [MIT](LICENSE) © Santiago Mejía Oquendo