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 +24 -0
- package/LICENSE +21 -0
- package/README.es.md +162 -0
- package/README.md +586 -2
- package/SECURITY.md +66 -0
- package/esm/index.d.mts +2 -0
- package/esm/index.mjs +21 -0
- package/lib/errors.js +99 -0
- package/lib/index.d.ts +235 -0
- package/lib/index.js +74 -0
- package/lib/options.js +290 -0
- package/lib/pool.js +373 -0
- package/lib/sync.js +60 -0
- package/lib/validators.js +157 -0
- package/lib/worker.js +58 -0
- package/package.json +78 -4
package/lib/pool.js
ADDED
|
@@ -0,0 +1,373 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
const path = require('node:path');
|
|
4
|
+
const { Worker } = require('node:worker_threads');
|
|
5
|
+
const { codes, RegexTimeoutError, RegexPoolError } = require('./errors');
|
|
6
|
+
const {
|
|
7
|
+
compilePattern,
|
|
8
|
+
normalizePoolOptions,
|
|
9
|
+
normalizeTestOptions,
|
|
10
|
+
assertString,
|
|
11
|
+
} = require('./options');
|
|
12
|
+
|
|
13
|
+
const WORKER_FILE = path.join(__dirname, 'worker.js');
|
|
14
|
+
const WORKER_STARTUP_TIMEOUT_MS = 10_000;
|
|
15
|
+
const WARMUP_TIMEOUT_MS = 1000;
|
|
16
|
+
|
|
17
|
+
// Internal entry point used by the validators: the pattern was already
|
|
18
|
+
// compiled and validated when the validator was created.
|
|
19
|
+
const kRun = Symbol('RegexWorkerPool.run');
|
|
20
|
+
|
|
21
|
+
function noop() {}
|
|
22
|
+
|
|
23
|
+
function poolClosedError() {
|
|
24
|
+
return new RegexPoolError(codes.REGEX_POOL_CLOSED, 'The regex worker pool is closed');
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/**
|
|
28
|
+
* A small pool of worker threads that evaluate regular expressions.
|
|
29
|
+
*
|
|
30
|
+
* Each worker evaluates one expression at a time. If an evaluation exceeds
|
|
31
|
+
* its time limit the worker is terminated (which interrupts the regex engine)
|
|
32
|
+
* and a new one is started for the next task, so the main thread's event
|
|
33
|
+
* loop is never blocked by a malicious input.
|
|
34
|
+
*
|
|
35
|
+
* Availability limits:
|
|
36
|
+
* - at most `size` evaluations run in parallel;
|
|
37
|
+
* - at most `maxQueue` tasks wait for a free worker (more are rejected at once);
|
|
38
|
+
* - a task waits at most `maxWaitMs` in the queue (then it is rejected).
|
|
39
|
+
* Every limit fails closed: the task is rejected, never silently accepted.
|
|
40
|
+
*/
|
|
41
|
+
class RegexWorkerPool {
|
|
42
|
+
#options;
|
|
43
|
+
#slots;
|
|
44
|
+
#queue = [];
|
|
45
|
+
#closed = false;
|
|
46
|
+
#closing = null;
|
|
47
|
+
#nextId = 0;
|
|
48
|
+
|
|
49
|
+
constructor(options) {
|
|
50
|
+
this.#options = normalizePoolOptions(options);
|
|
51
|
+
this.#slots = Array.from({ length: this.#options.size }, () => ({
|
|
52
|
+
worker: null, // Worker | null
|
|
53
|
+
online: false, // whether the worker emitted 'online'
|
|
54
|
+
task: null, // task being evaluated or waiting for the worker to start
|
|
55
|
+
timer: null, // startup timer or execution timer
|
|
56
|
+
}));
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/** Maximum number of worker threads. */
|
|
60
|
+
get size() {
|
|
61
|
+
return this.#options.size;
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/** Whether close() was called. A closed pool rejects every new task. */
|
|
65
|
+
get closed() {
|
|
66
|
+
return this.#closed;
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
/** A snapshot of the pool state, useful for metrics and health checks. */
|
|
70
|
+
get stats() {
|
|
71
|
+
let workers = 0;
|
|
72
|
+
let busy = 0;
|
|
73
|
+
for (const slot of this.#slots) {
|
|
74
|
+
if (slot.worker !== null) workers += 1;
|
|
75
|
+
if (slot.task !== null) busy += 1;
|
|
76
|
+
}
|
|
77
|
+
return { size: this.#options.size, workers, busy, queued: this.#queue.length };
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
/**
|
|
81
|
+
* Evaluates `pattern` against `input` in a worker thread.
|
|
82
|
+
* Resolves to true/false; rejects with RegexTimeoutError or RegexPoolError.
|
|
83
|
+
*/
|
|
84
|
+
test(pattern, input, options) {
|
|
85
|
+
try {
|
|
86
|
+
const opts = normalizeTestOptions(options, false, 'RegexWorkerPool#test() options');
|
|
87
|
+
assertString(input);
|
|
88
|
+
const { source, flags } = compilePattern(pattern, opts.flags, opts.fullMatch);
|
|
89
|
+
return this[kRun](source, flags, input, opts.timeoutMs);
|
|
90
|
+
} catch (err) {
|
|
91
|
+
return Promise.reject(err);
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
/**
|
|
96
|
+
* Starts every worker now (for example during application startup), so the
|
|
97
|
+
* first requests do not pay the worker start-up cost.
|
|
98
|
+
*/
|
|
99
|
+
warmup() {
|
|
100
|
+
const runs = [];
|
|
101
|
+
for (let i = 0; i < this.#options.size; i += 1) {
|
|
102
|
+
runs.push(this[kRun]('^$', '', '', WARMUP_TIMEOUT_MS));
|
|
103
|
+
}
|
|
104
|
+
return Promise.all(runs).then(noop);
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
/**
|
|
108
|
+
* Terminates all workers. Queued and running tasks are rejected with
|
|
109
|
+
* ERR_REGEX_POOL_CLOSED. Safe to call more than once.
|
|
110
|
+
*/
|
|
111
|
+
close() {
|
|
112
|
+
if (this.#closing !== null) {
|
|
113
|
+
return this.#closing;
|
|
114
|
+
}
|
|
115
|
+
this.#closed = true;
|
|
116
|
+
for (const task of this.#queue.splice(0)) {
|
|
117
|
+
clearTimeout(task.queueTimer);
|
|
118
|
+
task.reject(poolClosedError());
|
|
119
|
+
}
|
|
120
|
+
const terminations = [];
|
|
121
|
+
for (const slot of this.#slots) {
|
|
122
|
+
const task = slot.task;
|
|
123
|
+
slot.task = null;
|
|
124
|
+
terminations.push(this.#discardWorker(slot));
|
|
125
|
+
if (task !== null) {
|
|
126
|
+
task.reject(poolClosedError());
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
this.#closing = Promise.all(terminations).then(noop);
|
|
130
|
+
return this.#closing;
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
[kRun](source, flags, input, timeoutMs) {
|
|
134
|
+
if (this.#closed) {
|
|
135
|
+
return Promise.reject(poolClosedError());
|
|
136
|
+
}
|
|
137
|
+
return new Promise((resolve, reject) => {
|
|
138
|
+
const task = {
|
|
139
|
+
id: this.#takeId(),
|
|
140
|
+
source,
|
|
141
|
+
flags,
|
|
142
|
+
input,
|
|
143
|
+
timeoutMs,
|
|
144
|
+
resolve,
|
|
145
|
+
reject,
|
|
146
|
+
queueTimer: null,
|
|
147
|
+
};
|
|
148
|
+
const slot = this.#slots.find((candidate) => candidate.task === null);
|
|
149
|
+
if (slot !== undefined) {
|
|
150
|
+
this.#start(slot, task);
|
|
151
|
+
return;
|
|
152
|
+
}
|
|
153
|
+
if (this.#queue.length >= this.#options.maxQueue) {
|
|
154
|
+
reject(
|
|
155
|
+
new RegexPoolError(
|
|
156
|
+
codes.REGEX_QUEUE_FULL,
|
|
157
|
+
`The regex worker pool queue is full (${this.#options.maxQueue} pending tasks)`,
|
|
158
|
+
),
|
|
159
|
+
);
|
|
160
|
+
return;
|
|
161
|
+
}
|
|
162
|
+
task.queueTimer = setTimeout(() => this.#expireQueued(task), this.#options.maxWaitMs);
|
|
163
|
+
this.#queue.push(task);
|
|
164
|
+
});
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
#takeId() {
|
|
168
|
+
this.#nextId = this.#nextId >= Number.MAX_SAFE_INTEGER ? 1 : this.#nextId + 1;
|
|
169
|
+
return this.#nextId;
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
#expireQueued(task) {
|
|
173
|
+
const index = this.#queue.indexOf(task);
|
|
174
|
+
if (index === -1) {
|
|
175
|
+
return;
|
|
176
|
+
}
|
|
177
|
+
this.#queue.splice(index, 1);
|
|
178
|
+
task.reject(
|
|
179
|
+
new RegexPoolError(
|
|
180
|
+
codes.REGEX_QUEUE_TIMEOUT,
|
|
181
|
+
`The task waited more than ${this.#options.maxWaitMs} ms for a free regex worker`,
|
|
182
|
+
),
|
|
183
|
+
);
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
#start(slot, task) {
|
|
187
|
+
slot.task = task;
|
|
188
|
+
if (slot.worker === null) {
|
|
189
|
+
try {
|
|
190
|
+
this.#spawn(slot);
|
|
191
|
+
} catch (err) {
|
|
192
|
+
slot.task = null;
|
|
193
|
+
task.reject(
|
|
194
|
+
new RegexPoolError(codes.REGEX_WORKER_FAILED, 'Could not start a regex worker', {
|
|
195
|
+
cause: err,
|
|
196
|
+
}),
|
|
197
|
+
);
|
|
198
|
+
return;
|
|
199
|
+
}
|
|
200
|
+
}
|
|
201
|
+
// Keep the process alive while there is work in progress.
|
|
202
|
+
slot.worker.ref();
|
|
203
|
+
if (slot.online) {
|
|
204
|
+
this.#post(slot);
|
|
205
|
+
}
|
|
206
|
+
// Otherwise the task is posted from the 'online' handler. Worker start-up
|
|
207
|
+
// time is deliberately not counted against the task's timeout.
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
#post(slot) {
|
|
211
|
+
const task = slot.task;
|
|
212
|
+
slot.timer = setTimeout(() => this.#onTimeout(slot, task), task.timeoutMs);
|
|
213
|
+
slot.worker.postMessage({
|
|
214
|
+
id: task.id,
|
|
215
|
+
source: task.source,
|
|
216
|
+
flags: task.flags,
|
|
217
|
+
input: task.input,
|
|
218
|
+
});
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
#spawn(slot) {
|
|
222
|
+
const worker = new Worker(WORKER_FILE, {
|
|
223
|
+
// Least privilege: evaluating a regex needs no environment variables
|
|
224
|
+
// (which often hold secrets), no CLI arguments and no inherited flags
|
|
225
|
+
// such as --inspect or --require hooks.
|
|
226
|
+
env: {},
|
|
227
|
+
argv: [],
|
|
228
|
+
execArgv: [],
|
|
229
|
+
stdin: false,
|
|
230
|
+
resourceLimits: { ...this.#options.resourceLimits },
|
|
231
|
+
});
|
|
232
|
+
slot.worker = worker;
|
|
233
|
+
slot.online = false;
|
|
234
|
+
slot.timer = setTimeout(() => {
|
|
235
|
+
this.#onWorkerFailure(
|
|
236
|
+
slot,
|
|
237
|
+
worker,
|
|
238
|
+
new Error(`The regex worker did not start within ${WORKER_STARTUP_TIMEOUT_MS} ms`),
|
|
239
|
+
);
|
|
240
|
+
}, WORKER_STARTUP_TIMEOUT_MS);
|
|
241
|
+
|
|
242
|
+
worker.on('online', () => {
|
|
243
|
+
if (slot.worker !== worker) {
|
|
244
|
+
return;
|
|
245
|
+
}
|
|
246
|
+
clearTimeout(slot.timer);
|
|
247
|
+
slot.timer = null;
|
|
248
|
+
slot.online = true;
|
|
249
|
+
if (slot.task !== null) {
|
|
250
|
+
this.#post(slot);
|
|
251
|
+
} else {
|
|
252
|
+
worker.unref();
|
|
253
|
+
}
|
|
254
|
+
});
|
|
255
|
+
worker.on('message', (message) => this.#onMessage(slot, worker, message));
|
|
256
|
+
worker.on('error', (err) => this.#onWorkerFailure(slot, worker, err));
|
|
257
|
+
worker.on('messageerror', (err) => this.#onWorkerFailure(slot, worker, err));
|
|
258
|
+
worker.on('exit', (exitCode) => {
|
|
259
|
+
this.#onWorkerFailure(slot, worker, new Error(`The regex worker exited with code ${exitCode}`));
|
|
260
|
+
});
|
|
261
|
+
}
|
|
262
|
+
|
|
263
|
+
#onMessage(slot, worker, message) {
|
|
264
|
+
if (slot.worker !== worker) {
|
|
265
|
+
return;
|
|
266
|
+
}
|
|
267
|
+
const task = slot.task;
|
|
268
|
+
if (task === null || message === null || typeof message !== 'object' || message.id !== task.id) {
|
|
269
|
+
return;
|
|
270
|
+
}
|
|
271
|
+
clearTimeout(slot.timer);
|
|
272
|
+
slot.timer = null;
|
|
273
|
+
slot.task = null;
|
|
274
|
+
if (message.ok === true) {
|
|
275
|
+
task.resolve(message.matched === true);
|
|
276
|
+
} else {
|
|
277
|
+
task.reject(
|
|
278
|
+
new RegexPoolError(
|
|
279
|
+
codes.REGEX_EXECUTION_FAILED,
|
|
280
|
+
'The regular expression could not be evaluated',
|
|
281
|
+
{ cause: new Error(String(message.error)) },
|
|
282
|
+
),
|
|
283
|
+
);
|
|
284
|
+
}
|
|
285
|
+
this.#drain(slot);
|
|
286
|
+
}
|
|
287
|
+
|
|
288
|
+
#onTimeout(slot, task) {
|
|
289
|
+
if (slot.task !== task) {
|
|
290
|
+
return;
|
|
291
|
+
}
|
|
292
|
+
slot.timer = null;
|
|
293
|
+
slot.task = null;
|
|
294
|
+
// Terminating the worker interrupts the regex engine immediately.
|
|
295
|
+
this.#discardWorker(slot);
|
|
296
|
+
task.reject(new RegexTimeoutError(task.timeoutMs, task.input.length));
|
|
297
|
+
this.#drain(slot);
|
|
298
|
+
}
|
|
299
|
+
|
|
300
|
+
#onWorkerFailure(slot, worker, err) {
|
|
301
|
+
if (slot.worker !== worker) {
|
|
302
|
+
return;
|
|
303
|
+
}
|
|
304
|
+
const task = slot.task;
|
|
305
|
+
slot.task = null;
|
|
306
|
+
this.#discardWorker(slot);
|
|
307
|
+
if (task !== null) {
|
|
308
|
+
task.reject(
|
|
309
|
+
new RegexPoolError(codes.REGEX_WORKER_FAILED, 'The regex worker failed', { cause: err }),
|
|
310
|
+
);
|
|
311
|
+
}
|
|
312
|
+
this.#drain(slot);
|
|
313
|
+
}
|
|
314
|
+
|
|
315
|
+
#discardWorker(slot) {
|
|
316
|
+
const worker = slot.worker;
|
|
317
|
+
slot.worker = null;
|
|
318
|
+
slot.online = false;
|
|
319
|
+
if (slot.timer !== null) {
|
|
320
|
+
clearTimeout(slot.timer);
|
|
321
|
+
slot.timer = null;
|
|
322
|
+
}
|
|
323
|
+
if (worker === null) {
|
|
324
|
+
return Promise.resolve();
|
|
325
|
+
}
|
|
326
|
+
return worker.terminate().then(noop, noop);
|
|
327
|
+
}
|
|
328
|
+
|
|
329
|
+
#drain(slot) {
|
|
330
|
+
while (slot.task === null && this.#queue.length > 0 && !this.#closed) {
|
|
331
|
+
const task = this.#queue.shift();
|
|
332
|
+
clearTimeout(task.queueTimer);
|
|
333
|
+
task.queueTimer = null;
|
|
334
|
+
this.#start(slot, task);
|
|
335
|
+
}
|
|
336
|
+
if (slot.task === null && slot.worker !== null) {
|
|
337
|
+
// An idle worker must not keep the process alive.
|
|
338
|
+
slot.worker.unref();
|
|
339
|
+
}
|
|
340
|
+
}
|
|
341
|
+
}
|
|
342
|
+
|
|
343
|
+
function createRegexWorkerPool(options) {
|
|
344
|
+
return new RegexWorkerPool(options);
|
|
345
|
+
}
|
|
346
|
+
|
|
347
|
+
let defaultPool = null;
|
|
348
|
+
|
|
349
|
+
/**
|
|
350
|
+
* The shared pool used by regexTimeoutAsync() and testWithTimeoutAsync()
|
|
351
|
+
* when no `pool` option is given. Created lazily on first use.
|
|
352
|
+
*/
|
|
353
|
+
function getDefaultPool() {
|
|
354
|
+
if (defaultPool === null || defaultPool.closed) {
|
|
355
|
+
defaultPool = new RegexWorkerPool();
|
|
356
|
+
}
|
|
357
|
+
return defaultPool;
|
|
358
|
+
}
|
|
359
|
+
|
|
360
|
+
/** Closes the shared pool (if it was created). A later call to it creates a new one. */
|
|
361
|
+
function closeDefaultPool() {
|
|
362
|
+
const pool = defaultPool;
|
|
363
|
+
defaultPool = null;
|
|
364
|
+
return pool === null ? Promise.resolve() : pool.close();
|
|
365
|
+
}
|
|
366
|
+
|
|
367
|
+
module.exports = {
|
|
368
|
+
kRun,
|
|
369
|
+
RegexWorkerPool,
|
|
370
|
+
createRegexWorkerPool,
|
|
371
|
+
getDefaultPool,
|
|
372
|
+
closeDefaultPool,
|
|
373
|
+
};
|
package/lib/sync.js
ADDED
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
const vm = require('node:vm');
|
|
4
|
+
const { RegexTimeoutError } = require('./errors');
|
|
5
|
+
|
|
6
|
+
// One context and one precompiled script, created lazily on first use (no
|
|
7
|
+
// work at import time). The context has a null prototype and code generation
|
|
8
|
+
// from strings disabled: the script can only see the two values placed in it.
|
|
9
|
+
//
|
|
10
|
+
// Note: node:vm is NOT a security sandbox and is not used as one here. It is
|
|
11
|
+
// only used for its `timeout` option, which interrupts a runaway regular
|
|
12
|
+
// expression. The code that runs is a constant string written by this
|
|
13
|
+
// package; untrusted input is only ever passed as data.
|
|
14
|
+
let context = null;
|
|
15
|
+
let script = null;
|
|
16
|
+
|
|
17
|
+
function ensureRunner() {
|
|
18
|
+
if (script === null) {
|
|
19
|
+
context = vm.createContext(Object.create(null), {
|
|
20
|
+
name: 'express-validator-regex-timeout-sm',
|
|
21
|
+
codeGeneration: { strings: false, wasm: false },
|
|
22
|
+
});
|
|
23
|
+
script = new vm.Script('re.test(input)', {
|
|
24
|
+
filename: 'express-validator-regex-timeout-sm/vm-runner.js',
|
|
25
|
+
});
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/**
|
|
30
|
+
* Runs `regex.test(input)` synchronously, aborting after `timeoutMs`.
|
|
31
|
+
* Blocks the event loop for at most (about) `timeoutMs`.
|
|
32
|
+
*
|
|
33
|
+
* @param {RegExp} regex a RegExp created by this package (no g/y flags)
|
|
34
|
+
* @param {string} input
|
|
35
|
+
* @param {number} timeoutMs
|
|
36
|
+
* @returns {boolean}
|
|
37
|
+
*/
|
|
38
|
+
function runWithTimeout(regex, input, timeoutMs) {
|
|
39
|
+
ensureRunner();
|
|
40
|
+
context.re = regex;
|
|
41
|
+
context.input = input;
|
|
42
|
+
try {
|
|
43
|
+
return script.runInContext(context, {
|
|
44
|
+
timeout: timeoutMs,
|
|
45
|
+
breakOnSigint: false,
|
|
46
|
+
displayErrors: false,
|
|
47
|
+
});
|
|
48
|
+
} catch (err) {
|
|
49
|
+
if (err !== null && typeof err === 'object' && err.code === 'ERR_SCRIPT_EXECUTION_TIMEOUT') {
|
|
50
|
+
throw new RegexTimeoutError(timeoutMs, input.length, { cause: err });
|
|
51
|
+
}
|
|
52
|
+
throw err;
|
|
53
|
+
} finally {
|
|
54
|
+
// Do not keep (possibly large) untrusted strings alive between calls.
|
|
55
|
+
context.re = null;
|
|
56
|
+
context.input = null;
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
module.exports = { runWithTimeout };
|
|
@@ -0,0 +1,157 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
const { normalizeValidatorOptions } = require('./options');
|
|
4
|
+
const { runWithTimeout } = require('./sync');
|
|
5
|
+
const { kRun, RegexWorkerPool, getDefaultPool } = require('./pool');
|
|
6
|
+
const { codes, RegexTimeoutError, RegexValidationError } = require('./errors');
|
|
7
|
+
|
|
8
|
+
const HOOK_WARNING_CODE = 'REGEX_TIMEOUT_HOOK_ERROR';
|
|
9
|
+
const warnedHooks = new WeakSet();
|
|
10
|
+
|
|
11
|
+
function warnHookFailure(hook, err) {
|
|
12
|
+
// One warning per hook function: a hook that keeps failing during an
|
|
13
|
+
// attack must not flood the logs.
|
|
14
|
+
if (warnedHooks.has(hook)) {
|
|
15
|
+
return;
|
|
16
|
+
}
|
|
17
|
+
warnedHooks.add(hook);
|
|
18
|
+
const detail = err instanceof Error ? err.message : String(err);
|
|
19
|
+
process.emitWarning(`An onTimeout/onUnavailable hook threw an error: ${detail}`, {
|
|
20
|
+
code: HOOK_WARNING_CODE,
|
|
21
|
+
});
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
/**
|
|
25
|
+
* Calls a monitoring hook without letting it break validation: synchronous
|
|
26
|
+
* throws and rejected promises are caught and reported as a process warning.
|
|
27
|
+
*/
|
|
28
|
+
function callHook(hook, info, meta) {
|
|
29
|
+
if (hook === undefined) {
|
|
30
|
+
return;
|
|
31
|
+
}
|
|
32
|
+
try {
|
|
33
|
+
const result = hook(info, meta);
|
|
34
|
+
if (result !== null && typeof result === 'object' && typeof result.then === 'function') {
|
|
35
|
+
result.then(undefined, (err) => warnHookFailure(hook, err));
|
|
36
|
+
}
|
|
37
|
+
} catch (err) {
|
|
38
|
+
warnHookFailure(hook, err);
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/**
|
|
43
|
+
* Information passed to the hooks. It contains the input *length* but never
|
|
44
|
+
* the input itself, so it can be logged without leaking user data.
|
|
45
|
+
*/
|
|
46
|
+
function eventInfo(config, code, value, meta, cause) {
|
|
47
|
+
const info = {
|
|
48
|
+
code,
|
|
49
|
+
mode: config.mode,
|
|
50
|
+
pattern: config.source,
|
|
51
|
+
flags: config.flags,
|
|
52
|
+
timeoutMs: config.timeoutMs,
|
|
53
|
+
inputLength: value.length,
|
|
54
|
+
cause,
|
|
55
|
+
};
|
|
56
|
+
if (meta !== null && typeof meta === 'object') {
|
|
57
|
+
if (typeof meta.path === 'string') info.path = meta.path;
|
|
58
|
+
if (typeof meta.location === 'string') info.location = meta.location;
|
|
59
|
+
}
|
|
60
|
+
return Object.freeze(info);
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
function rejectValue(code, message, cause) {
|
|
64
|
+
return new RegexValidationError(code, message, cause === undefined ? undefined : { cause });
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/** Cheap checks that run before any regular expression. */
|
|
68
|
+
function checkValue(config, value) {
|
|
69
|
+
// Allowlist on the type: arrays (?a=1&a=2), objects and numbers are rejected
|
|
70
|
+
// instead of being coerced to strings.
|
|
71
|
+
if (typeof value !== 'string') {
|
|
72
|
+
throw rejectValue(codes.VALUE_NOT_STRING, config.messages.notString);
|
|
73
|
+
}
|
|
74
|
+
if (value.length > config.maxLength) {
|
|
75
|
+
throw rejectValue(codes.VALUE_TOO_LONG, config.messages.tooLong);
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
function timeoutFailure(config, value, meta, err) {
|
|
80
|
+
callHook(config.onTimeout, eventInfo(config, codes.VALUE_TIMEOUT, value, meta, err), meta);
|
|
81
|
+
return rejectValue(codes.VALUE_TIMEOUT, config.messages.timeout, err);
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
function unavailableFailure(config, value, meta, err) {
|
|
85
|
+
callHook(config.onUnavailable, eventInfo(config, codes.VALUE_UNAVAILABLE, value, meta, err), meta);
|
|
86
|
+
return rejectValue(codes.VALUE_UNAVAILABLE, config.messages.unavailable, err);
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
/**
|
|
90
|
+
* Creates a synchronous validator for express-validator's `.custom()`.
|
|
91
|
+
*
|
|
92
|
+
* The regular expression runs on the main thread inside node:vm with a
|
|
93
|
+
* timeout: a malicious input blocks the event loop for at most `timeoutMs`.
|
|
94
|
+
* Use regexTimeoutAsync() to keep the event loop completely free.
|
|
95
|
+
*
|
|
96
|
+
* @returns {(value: unknown, meta?: object) => true}
|
|
97
|
+
*/
|
|
98
|
+
function regexTimeout(pattern, options) {
|
|
99
|
+
const config = normalizeValidatorOptions(pattern, options, 'sync');
|
|
100
|
+
|
|
101
|
+
return function regexTimeoutValidator(value, meta) {
|
|
102
|
+
checkValue(config, value);
|
|
103
|
+
let matched;
|
|
104
|
+
try {
|
|
105
|
+
matched = runWithTimeout(config.regex, value, config.timeoutMs);
|
|
106
|
+
} catch (err) {
|
|
107
|
+
if (err instanceof RegexTimeoutError) {
|
|
108
|
+
throw timeoutFailure(config, value, meta, err);
|
|
109
|
+
}
|
|
110
|
+
// For example a RangeError from the regex engine: fail closed.
|
|
111
|
+
throw unavailableFailure(config, value, meta, err);
|
|
112
|
+
}
|
|
113
|
+
if (!matched) {
|
|
114
|
+
throw rejectValue(codes.VALUE_NO_MATCH, config.messages.noMatch);
|
|
115
|
+
}
|
|
116
|
+
return true;
|
|
117
|
+
};
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
/**
|
|
121
|
+
* Creates an asynchronous validator for express-validator's `.custom()`.
|
|
122
|
+
*
|
|
123
|
+
* The regular expression runs in a worker thread. If it exceeds `timeoutMs`
|
|
124
|
+
* the worker is terminated, so the main event loop is never blocked.
|
|
125
|
+
*
|
|
126
|
+
* @returns {(value: unknown, meta?: object) => Promise<true>}
|
|
127
|
+
*/
|
|
128
|
+
function regexTimeoutAsync(pattern, options) {
|
|
129
|
+
const config = normalizeValidatorOptions(pattern, options, 'async');
|
|
130
|
+
if (config.pool !== undefined && !(config.pool instanceof RegexWorkerPool)) {
|
|
131
|
+
throw new TypeError(
|
|
132
|
+
'The "pool" option must be a RegexWorkerPool created with createRegexWorkerPool()',
|
|
133
|
+
);
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
return async function regexTimeoutAsyncValidator(value, meta) {
|
|
137
|
+
checkValue(config, value);
|
|
138
|
+
const pool = config.pool === undefined ? getDefaultPool() : config.pool;
|
|
139
|
+
let matched;
|
|
140
|
+
try {
|
|
141
|
+
matched = await pool[kRun](config.source, config.flags, value, config.timeoutMs);
|
|
142
|
+
} catch (err) {
|
|
143
|
+
if (err instanceof RegexTimeoutError) {
|
|
144
|
+
throw timeoutFailure(config, value, meta, err);
|
|
145
|
+
}
|
|
146
|
+
// Queue full, queue timeout, closed pool or failed worker: fail closed
|
|
147
|
+
// with a generic message (the original error is kept as `cause`).
|
|
148
|
+
throw unavailableFailure(config, value, meta, err);
|
|
149
|
+
}
|
|
150
|
+
if (!matched) {
|
|
151
|
+
throw rejectValue(codes.VALUE_NO_MATCH, config.messages.noMatch);
|
|
152
|
+
}
|
|
153
|
+
return true;
|
|
154
|
+
};
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
module.exports = { regexTimeout, regexTimeoutAsync };
|
package/lib/worker.js
ADDED
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
// Worker thread that evaluates regular expressions for RegexWorkerPool.
|
|
4
|
+
// If an evaluation runs too long, the main thread terminates this worker and
|
|
5
|
+
// starts a new one, so the main event loop is never blocked.
|
|
6
|
+
|
|
7
|
+
const { parentPort, isMainThread } = require('node:worker_threads');
|
|
8
|
+
|
|
9
|
+
if (isMainThread || parentPort === null) {
|
|
10
|
+
throw new Error('lib/worker.js must be run as a worker thread by RegexWorkerPool');
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
const MAX_CACHED_PATTERNS = 64;
|
|
14
|
+
const cache = new Map();
|
|
15
|
+
|
|
16
|
+
function compile(source, flags) {
|
|
17
|
+
const key = `${flags}/${source}`;
|
|
18
|
+
let regex = cache.get(key);
|
|
19
|
+
if (regex === undefined) {
|
|
20
|
+
regex = new RegExp(source, flags);
|
|
21
|
+
if (cache.size >= MAX_CACHED_PATTERNS) {
|
|
22
|
+
// Evict the least recently used entry (Map keeps insertion order).
|
|
23
|
+
cache.delete(cache.keys().next().value);
|
|
24
|
+
}
|
|
25
|
+
} else {
|
|
26
|
+
cache.delete(key);
|
|
27
|
+
}
|
|
28
|
+
cache.set(key, regex);
|
|
29
|
+
return regex;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
function describe(err) {
|
|
33
|
+
return err instanceof Error ? `${err.name}: ${err.message}` : 'Unknown error';
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
parentPort.on('message', (task) => {
|
|
37
|
+
// Validate every message, even though only RegexWorkerPool talks to us.
|
|
38
|
+
if (task === null || typeof task !== 'object' || !Number.isSafeInteger(task.id)) {
|
|
39
|
+
return;
|
|
40
|
+
}
|
|
41
|
+
const { id, source, flags, input } = task;
|
|
42
|
+
if (typeof source !== 'string' || typeof flags !== 'string' || typeof input !== 'string') {
|
|
43
|
+
parentPort.postMessage({ id, ok: false, error: 'Malformed task' });
|
|
44
|
+
return;
|
|
45
|
+
}
|
|
46
|
+
if (flags.includes('g') || flags.includes('y')) {
|
|
47
|
+
parentPort.postMessage({ id, ok: false, error: 'Stateful flags (g, y) are not allowed' });
|
|
48
|
+
return;
|
|
49
|
+
}
|
|
50
|
+
let matched;
|
|
51
|
+
try {
|
|
52
|
+
matched = compile(source, flags).test(input);
|
|
53
|
+
} catch (err) {
|
|
54
|
+
parentPort.postMessage({ id, ok: false, error: describe(err) });
|
|
55
|
+
return;
|
|
56
|
+
}
|
|
57
|
+
parentPort.postMessage({ id, ok: true, matched });
|
|
58
|
+
});
|