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/errors.js
ADDED
|
@@ -0,0 +1,99 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Error codes used by this package. They are stable and safe to compare
|
|
5
|
+
* against in application code (for example to choose an HTTP status code).
|
|
6
|
+
*/
|
|
7
|
+
const codes = Object.freeze({
|
|
8
|
+
// Low-level evaluation errors.
|
|
9
|
+
REGEX_TIMEOUT: 'ERR_REGEX_TIMEOUT',
|
|
10
|
+
REGEX_QUEUE_FULL: 'ERR_REGEX_QUEUE_FULL',
|
|
11
|
+
REGEX_QUEUE_TIMEOUT: 'ERR_REGEX_QUEUE_TIMEOUT',
|
|
12
|
+
REGEX_POOL_CLOSED: 'ERR_REGEX_POOL_CLOSED',
|
|
13
|
+
REGEX_WORKER_FAILED: 'ERR_REGEX_WORKER_FAILED',
|
|
14
|
+
REGEX_EXECUTION_FAILED: 'ERR_REGEX_EXECUTION_FAILED',
|
|
15
|
+
// Validation results thrown by the validator functions.
|
|
16
|
+
VALUE_NOT_STRING: 'ERR_VALUE_NOT_STRING',
|
|
17
|
+
VALUE_TOO_LONG: 'ERR_VALUE_TOO_LONG',
|
|
18
|
+
VALUE_NO_MATCH: 'ERR_VALUE_NO_MATCH',
|
|
19
|
+
VALUE_TIMEOUT: 'ERR_VALUE_TIMEOUT',
|
|
20
|
+
VALUE_UNAVAILABLE: 'ERR_VALUE_UNAVAILABLE',
|
|
21
|
+
});
|
|
22
|
+
|
|
23
|
+
const POOL_CODES = new Set([
|
|
24
|
+
codes.REGEX_QUEUE_FULL,
|
|
25
|
+
codes.REGEX_QUEUE_TIMEOUT,
|
|
26
|
+
codes.REGEX_POOL_CLOSED,
|
|
27
|
+
codes.REGEX_WORKER_FAILED,
|
|
28
|
+
codes.REGEX_EXECUTION_FAILED,
|
|
29
|
+
]);
|
|
30
|
+
|
|
31
|
+
const VALIDATION_CODES = new Set([
|
|
32
|
+
codes.VALUE_NOT_STRING,
|
|
33
|
+
codes.VALUE_TOO_LONG,
|
|
34
|
+
codes.VALUE_NO_MATCH,
|
|
35
|
+
codes.VALUE_TIMEOUT,
|
|
36
|
+
codes.VALUE_UNAVAILABLE,
|
|
37
|
+
]);
|
|
38
|
+
|
|
39
|
+
function setName(ErrorClass, name) {
|
|
40
|
+
Object.defineProperty(ErrorClass.prototype, 'name', {
|
|
41
|
+
value: name,
|
|
42
|
+
writable: true,
|
|
43
|
+
enumerable: false,
|
|
44
|
+
configurable: true,
|
|
45
|
+
});
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
/**
|
|
49
|
+
* The regular expression did not finish within the time limit.
|
|
50
|
+
*
|
|
51
|
+
* The message never contains the input or the pattern, so it is safe to
|
|
52
|
+
* forward to clients. Only the input length is kept, for diagnostics.
|
|
53
|
+
*/
|
|
54
|
+
class RegexTimeoutError extends Error {
|
|
55
|
+
constructor(timeoutMs, inputLength, options) {
|
|
56
|
+
super(`Regular expression evaluation exceeded ${timeoutMs} ms`, options);
|
|
57
|
+
this.code = codes.REGEX_TIMEOUT;
|
|
58
|
+
this.timeoutMs = timeoutMs;
|
|
59
|
+
this.inputLength = inputLength;
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
setName(RegexTimeoutError, 'RegexTimeoutError');
|
|
63
|
+
|
|
64
|
+
/**
|
|
65
|
+
* The worker pool could not evaluate the expression: the queue is full, the
|
|
66
|
+
* task waited too long, the pool is closed, or a worker failed.
|
|
67
|
+
*/
|
|
68
|
+
class RegexPoolError extends Error {
|
|
69
|
+
constructor(code, message, options) {
|
|
70
|
+
if (!POOL_CODES.has(code)) {
|
|
71
|
+
throw new TypeError(`Unknown RegexPoolError code: ${String(code)}`);
|
|
72
|
+
}
|
|
73
|
+
super(message, options);
|
|
74
|
+
this.code = code;
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
setName(RegexPoolError, 'RegexPoolError');
|
|
78
|
+
|
|
79
|
+
/**
|
|
80
|
+
* Thrown by the validator functions when a value is rejected. Its message is
|
|
81
|
+
* the (configurable, generic) text that express-validator reports to clients.
|
|
82
|
+
*/
|
|
83
|
+
class RegexValidationError extends Error {
|
|
84
|
+
constructor(code, message, options) {
|
|
85
|
+
if (!VALIDATION_CODES.has(code)) {
|
|
86
|
+
throw new TypeError(`Unknown RegexValidationError code: ${String(code)}`);
|
|
87
|
+
}
|
|
88
|
+
super(message, options);
|
|
89
|
+
this.code = code;
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
setName(RegexValidationError, 'RegexValidationError');
|
|
93
|
+
|
|
94
|
+
module.exports = {
|
|
95
|
+
codes,
|
|
96
|
+
RegexTimeoutError,
|
|
97
|
+
RegexPoolError,
|
|
98
|
+
RegexValidationError,
|
|
99
|
+
};
|
package/lib/index.d.ts
ADDED
|
@@ -0,0 +1,235 @@
|
|
|
1
|
+
// Type definitions for express-validator-regex-timeout-sm.
|
|
2
|
+
// They do not depend on @types/node or on express-validator's own types.
|
|
3
|
+
|
|
4
|
+
/** A pattern written by the developer: a RegExp, or a string plus the `flags` option. */
|
|
5
|
+
export type PatternLike = RegExp | string;
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* The `meta` argument that express-validator passes to `.custom()` validators.
|
|
9
|
+
* Only `path` and `location` are read (to enrich the hook information).
|
|
10
|
+
*/
|
|
11
|
+
export interface ValidatorMeta {
|
|
12
|
+
/** The Express request (typed loosely so hooks can flag it, e.g. `meta.req.validationUnavailable = true`). */
|
|
13
|
+
req?: any;
|
|
14
|
+
location?: string;
|
|
15
|
+
path?: string;
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
export declare const codes: {
|
|
19
|
+
readonly REGEX_TIMEOUT: 'ERR_REGEX_TIMEOUT';
|
|
20
|
+
readonly REGEX_QUEUE_FULL: 'ERR_REGEX_QUEUE_FULL';
|
|
21
|
+
readonly REGEX_QUEUE_TIMEOUT: 'ERR_REGEX_QUEUE_TIMEOUT';
|
|
22
|
+
readonly REGEX_POOL_CLOSED: 'ERR_REGEX_POOL_CLOSED';
|
|
23
|
+
readonly REGEX_WORKER_FAILED: 'ERR_REGEX_WORKER_FAILED';
|
|
24
|
+
readonly REGEX_EXECUTION_FAILED: 'ERR_REGEX_EXECUTION_FAILED';
|
|
25
|
+
readonly VALUE_NOT_STRING: 'ERR_VALUE_NOT_STRING';
|
|
26
|
+
readonly VALUE_TOO_LONG: 'ERR_VALUE_TOO_LONG';
|
|
27
|
+
readonly VALUE_NO_MATCH: 'ERR_VALUE_NO_MATCH';
|
|
28
|
+
readonly VALUE_TIMEOUT: 'ERR_VALUE_TIMEOUT';
|
|
29
|
+
readonly VALUE_UNAVAILABLE: 'ERR_VALUE_UNAVAILABLE';
|
|
30
|
+
};
|
|
31
|
+
|
|
32
|
+
export type RegexPoolErrorCode =
|
|
33
|
+
| 'ERR_REGEX_QUEUE_FULL'
|
|
34
|
+
| 'ERR_REGEX_QUEUE_TIMEOUT'
|
|
35
|
+
| 'ERR_REGEX_POOL_CLOSED'
|
|
36
|
+
| 'ERR_REGEX_WORKER_FAILED'
|
|
37
|
+
| 'ERR_REGEX_EXECUTION_FAILED';
|
|
38
|
+
|
|
39
|
+
export type RegexValidationErrorCode =
|
|
40
|
+
| 'ERR_VALUE_NOT_STRING'
|
|
41
|
+
| 'ERR_VALUE_TOO_LONG'
|
|
42
|
+
| 'ERR_VALUE_NO_MATCH'
|
|
43
|
+
| 'ERR_VALUE_TIMEOUT'
|
|
44
|
+
| 'ERR_VALUE_UNAVAILABLE';
|
|
45
|
+
|
|
46
|
+
export type ErrorCode = (typeof codes)[keyof typeof codes];
|
|
47
|
+
|
|
48
|
+
/** The regular expression did not finish within the time limit. */
|
|
49
|
+
export declare class RegexTimeoutError extends Error {
|
|
50
|
+
constructor(timeoutMs: number, inputLength: number, options?: { cause?: unknown });
|
|
51
|
+
readonly code: 'ERR_REGEX_TIMEOUT';
|
|
52
|
+
readonly timeoutMs: number;
|
|
53
|
+
readonly inputLength: number;
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/** The worker pool could not evaluate the expression. */
|
|
57
|
+
export declare class RegexPoolError extends Error {
|
|
58
|
+
constructor(code: RegexPoolErrorCode, message: string, options?: { cause?: unknown });
|
|
59
|
+
readonly code: RegexPoolErrorCode;
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/** Thrown (or used to reject) by the validators when a value is rejected. */
|
|
63
|
+
export declare class RegexValidationError extends Error {
|
|
64
|
+
constructor(code: RegexValidationErrorCode, message: string, options?: { cause?: unknown });
|
|
65
|
+
readonly code: RegexValidationErrorCode;
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
/** Messages reported to the client. Use generic texts: never echo the input. */
|
|
69
|
+
export interface RegexTimeoutMessages {
|
|
70
|
+
/** The value is not a string (arrays, objects, numbers...). */
|
|
71
|
+
notString?: string;
|
|
72
|
+
/** The value is longer than `maxLength`. */
|
|
73
|
+
tooLong?: string;
|
|
74
|
+
/** The value does not match the pattern. */
|
|
75
|
+
noMatch?: string;
|
|
76
|
+
/** The evaluation exceeded `timeoutMs`. */
|
|
77
|
+
timeout?: string;
|
|
78
|
+
/** The value could not be evaluated (queue full, pool closed, worker failure...). */
|
|
79
|
+
unavailable?: string;
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
/** Information passed to `onTimeout` / `onUnavailable`. It never contains the input. */
|
|
83
|
+
export interface RegexEventInfo {
|
|
84
|
+
readonly code: 'ERR_VALUE_TIMEOUT' | 'ERR_VALUE_UNAVAILABLE';
|
|
85
|
+
readonly mode: 'sync' | 'async';
|
|
86
|
+
/** The effective pattern source (wrapped as `^(?:...)$` when `fullMatch` is true). */
|
|
87
|
+
readonly pattern: string;
|
|
88
|
+
readonly flags: string;
|
|
89
|
+
readonly timeoutMs: number;
|
|
90
|
+
/** Length of the rejected value in UTF-16 code units. */
|
|
91
|
+
readonly inputLength: number;
|
|
92
|
+
/** Field path, when called by express-validator. */
|
|
93
|
+
readonly path?: string;
|
|
94
|
+
/** Request location (body, query, params...), when called by express-validator. */
|
|
95
|
+
readonly location?: string;
|
|
96
|
+
/** The underlying error (RegexTimeoutError, RegexPoolError...). */
|
|
97
|
+
readonly cause: unknown;
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
/** A monitoring hook. Errors it throws (or rejections) never affect validation. */
|
|
101
|
+
export type RegexEventHook = (info: RegexEventInfo, meta: ValidatorMeta | undefined) => unknown;
|
|
102
|
+
|
|
103
|
+
export interface RegexTimeoutOptions {
|
|
104
|
+
/** Maximum evaluation time in milliseconds (1-60000). Default: 50. */
|
|
105
|
+
timeoutMs?: number;
|
|
106
|
+
/** Maximum value length in UTF-16 code units, checked before the regex runs. Default: 1000. */
|
|
107
|
+
maxLength?: number;
|
|
108
|
+
/** Flags for string patterns (not allowed with a RegExp). `g` and `y` are rejected. */
|
|
109
|
+
flags?: string;
|
|
110
|
+
/** Require the whole value to match (wraps the pattern as `^(?:...)$`). Default: true. */
|
|
111
|
+
fullMatch?: boolean;
|
|
112
|
+
/** Custom (generic) error messages. */
|
|
113
|
+
messages?: RegexTimeoutMessages;
|
|
114
|
+
/** Called when an evaluation times out (possible ReDoS attempt). */
|
|
115
|
+
onTimeout?: RegexEventHook;
|
|
116
|
+
/** Called when a value could not be evaluated for another reason. */
|
|
117
|
+
onUnavailable?: RegexEventHook;
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
export interface RegexTimeoutAsyncOptions extends RegexTimeoutOptions {
|
|
121
|
+
/** Pool to run the evaluation in. Default: the shared pool (`getDefaultPool()`). */
|
|
122
|
+
pool?: RegexWorkerPool;
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
/** A validator for express-validator's `.custom()`. Returns true or throws RegexValidationError. */
|
|
126
|
+
export type RegexTimeoutValidator = (value: unknown, meta?: ValidatorMeta) => true;
|
|
127
|
+
|
|
128
|
+
/** An async validator for express-validator's `.custom()`. Resolves to true or rejects with RegexValidationError. */
|
|
129
|
+
export type RegexTimeoutAsyncValidator = (value: unknown, meta?: ValidatorMeta) => Promise<true>;
|
|
130
|
+
|
|
131
|
+
/**
|
|
132
|
+
* Creates a synchronous validator (node:vm with a timeout). A malicious input
|
|
133
|
+
* blocks the event loop for at most `timeoutMs`.
|
|
134
|
+
*/
|
|
135
|
+
export declare function regexTimeout(
|
|
136
|
+
pattern: PatternLike,
|
|
137
|
+
options?: RegexTimeoutOptions,
|
|
138
|
+
): RegexTimeoutValidator;
|
|
139
|
+
|
|
140
|
+
/**
|
|
141
|
+
* Creates an asynchronous validator (worker thread with a timeout). The event
|
|
142
|
+
* loop is never blocked by the regular expression.
|
|
143
|
+
*/
|
|
144
|
+
export declare function regexTimeoutAsync(
|
|
145
|
+
pattern: PatternLike,
|
|
146
|
+
options?: RegexTimeoutAsyncOptions,
|
|
147
|
+
): RegexTimeoutAsyncValidator;
|
|
148
|
+
|
|
149
|
+
export interface TestWithTimeoutOptions {
|
|
150
|
+
/** Maximum evaluation time in milliseconds (1-60000). Default: 50. */
|
|
151
|
+
timeoutMs?: number;
|
|
152
|
+
/** Flags for string patterns. `g` and `y` are rejected. */
|
|
153
|
+
flags?: string;
|
|
154
|
+
/** Require the whole input to match. Default: true. */
|
|
155
|
+
fullMatch?: boolean;
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
export interface TestWithTimeoutAsyncOptions extends TestWithTimeoutOptions {
|
|
159
|
+
pool?: RegexWorkerPool;
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
/** Evaluates a pattern synchronously with a timeout. Throws RegexTimeoutError on timeout. */
|
|
163
|
+
export declare function testWithTimeout(
|
|
164
|
+
pattern: PatternLike,
|
|
165
|
+
input: string,
|
|
166
|
+
options?: TestWithTimeoutOptions,
|
|
167
|
+
): boolean;
|
|
168
|
+
|
|
169
|
+
/** Evaluates a pattern in a worker thread. Rejects with RegexTimeoutError or RegexPoolError. */
|
|
170
|
+
export declare function testWithTimeoutAsync(
|
|
171
|
+
pattern: PatternLike,
|
|
172
|
+
input: string,
|
|
173
|
+
options?: TestWithTimeoutAsyncOptions,
|
|
174
|
+
): Promise<boolean>;
|
|
175
|
+
|
|
176
|
+
/**
|
|
177
|
+
* Resource limits for each worker thread (see Node's `Worker` `resourceLimits`).
|
|
178
|
+
* Each value must be between 1 and 65536 (`stackSizeMb`: 1 to 1024); very small values are
|
|
179
|
+
* rejected because they can crash Node.js.
|
|
180
|
+
*/
|
|
181
|
+
export interface RegexWorkerResourceLimits {
|
|
182
|
+
maxOldGenerationSizeMb?: number;
|
|
183
|
+
maxYoungGenerationSizeMb?: number;
|
|
184
|
+
codeRangeSizeMb?: number;
|
|
185
|
+
stackSizeMb?: number;
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
export interface RegexWorkerPoolOptions {
|
|
189
|
+
/** Number of worker threads (1-64). Default: 1. */
|
|
190
|
+
size?: number;
|
|
191
|
+
/** Maximum number of tasks waiting for a free worker (0-1000000). Default: 100. */
|
|
192
|
+
maxQueue?: number;
|
|
193
|
+
/** Maximum time a task may wait in the queue, in milliseconds. Default: 1000. */
|
|
194
|
+
maxWaitMs?: number;
|
|
195
|
+
/** Memory/stack limits for each worker. */
|
|
196
|
+
resourceLimits?: RegexWorkerResourceLimits;
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
export interface RegexWorkerPoolStats {
|
|
200
|
+
size: number;
|
|
201
|
+
workers: number;
|
|
202
|
+
busy: number;
|
|
203
|
+
queued: number;
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
/** A pool of worker threads that evaluate regular expressions with a timeout. */
|
|
207
|
+
export declare class RegexWorkerPool {
|
|
208
|
+
constructor(options?: RegexWorkerPoolOptions);
|
|
209
|
+
readonly size: number;
|
|
210
|
+
readonly closed: boolean;
|
|
211
|
+
readonly stats: RegexWorkerPoolStats;
|
|
212
|
+
test(pattern: PatternLike, input: string, options?: TestWithTimeoutOptions): Promise<boolean>;
|
|
213
|
+
warmup(): Promise<void>;
|
|
214
|
+
close(): Promise<void>;
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
export declare function createRegexWorkerPool(options?: RegexWorkerPoolOptions): RegexWorkerPool;
|
|
218
|
+
|
|
219
|
+
/** The shared pool used when no `pool` option is given (created lazily). */
|
|
220
|
+
export declare function getDefaultPool(): RegexWorkerPool;
|
|
221
|
+
|
|
222
|
+
/** Closes the shared pool. A later use creates a new one. */
|
|
223
|
+
export declare function closeDefaultPool(): Promise<void>;
|
|
224
|
+
|
|
225
|
+
export declare const defaults: {
|
|
226
|
+
readonly timeoutMs: number;
|
|
227
|
+
readonly maxLength: number;
|
|
228
|
+
readonly fullMatch: boolean;
|
|
229
|
+
readonly pool: {
|
|
230
|
+
readonly size: number;
|
|
231
|
+
readonly maxQueue: number;
|
|
232
|
+
readonly maxWaitMs: number;
|
|
233
|
+
readonly resourceLimits: Readonly<Required<RegexWorkerResourceLimits>>;
|
|
234
|
+
};
|
|
235
|
+
};
|
package/lib/index.js
ADDED
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
const { defaults, compilePattern, normalizeTestOptions, assertString } = require('./options');
|
|
4
|
+
const { runWithTimeout } = require('./sync');
|
|
5
|
+
const {
|
|
6
|
+
RegexWorkerPool,
|
|
7
|
+
createRegexWorkerPool,
|
|
8
|
+
getDefaultPool,
|
|
9
|
+
closeDefaultPool,
|
|
10
|
+
} = require('./pool');
|
|
11
|
+
const { regexTimeout, regexTimeoutAsync } = require('./validators');
|
|
12
|
+
const {
|
|
13
|
+
codes,
|
|
14
|
+
RegexTimeoutError,
|
|
15
|
+
RegexPoolError,
|
|
16
|
+
RegexValidationError,
|
|
17
|
+
} = require('./errors');
|
|
18
|
+
|
|
19
|
+
/**
|
|
20
|
+
* Low-level helper: evaluates `pattern` against `input` synchronously with a
|
|
21
|
+
* timeout. Returns true/false or throws RegexTimeoutError.
|
|
22
|
+
* The pattern is compiled on every call; prefer regexTimeout() in hot paths.
|
|
23
|
+
*/
|
|
24
|
+
function testWithTimeout(pattern, input, options) {
|
|
25
|
+
const opts = normalizeTestOptions(options, false, 'testWithTimeout() options');
|
|
26
|
+
assertString(input);
|
|
27
|
+
const { regex } = compilePattern(pattern, opts.flags, opts.fullMatch);
|
|
28
|
+
return runWithTimeout(regex, input, opts.timeoutMs);
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/**
|
|
32
|
+
* Low-level helper: evaluates `pattern` against `input` in a worker thread.
|
|
33
|
+
* Resolves to true/false; rejects with RegexTimeoutError or RegexPoolError.
|
|
34
|
+
*/
|
|
35
|
+
function testWithTimeoutAsync(pattern, input, options) {
|
|
36
|
+
let opts;
|
|
37
|
+
try {
|
|
38
|
+
opts = normalizeTestOptions(options, true, 'testWithTimeoutAsync() options');
|
|
39
|
+
if (opts.pool !== undefined && !(opts.pool instanceof RegexWorkerPool)) {
|
|
40
|
+
throw new TypeError(
|
|
41
|
+
'The "pool" option must be a RegexWorkerPool created with createRegexWorkerPool()',
|
|
42
|
+
);
|
|
43
|
+
}
|
|
44
|
+
} catch (err) {
|
|
45
|
+
return Promise.reject(err);
|
|
46
|
+
}
|
|
47
|
+
const pool = opts.pool === undefined ? getDefaultPool() : opts.pool;
|
|
48
|
+
return pool.test(pattern, input, {
|
|
49
|
+
timeoutMs: opts.timeoutMs,
|
|
50
|
+
flags: opts.flags,
|
|
51
|
+
fullMatch: opts.fullMatch,
|
|
52
|
+
});
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
module.exports = {
|
|
56
|
+
// express-validator validators
|
|
57
|
+
regexTimeout,
|
|
58
|
+
regexTimeoutAsync,
|
|
59
|
+
// low-level helpers
|
|
60
|
+
testWithTimeout,
|
|
61
|
+
testWithTimeoutAsync,
|
|
62
|
+
// worker pool
|
|
63
|
+
RegexWorkerPool,
|
|
64
|
+
createRegexWorkerPool,
|
|
65
|
+
getDefaultPool,
|
|
66
|
+
closeDefaultPool,
|
|
67
|
+
// errors
|
|
68
|
+
codes,
|
|
69
|
+
RegexTimeoutError,
|
|
70
|
+
RegexPoolError,
|
|
71
|
+
RegexValidationError,
|
|
72
|
+
// configuration
|
|
73
|
+
defaults,
|
|
74
|
+
};
|
package/lib/options.js
ADDED
|
@@ -0,0 +1,290 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
const { types } = require('node:util');
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* Secure defaults. Every value can be overridden per validator or per pool,
|
|
7
|
+
* but the defaults are chosen so that forgetting an option is still safe.
|
|
8
|
+
*/
|
|
9
|
+
const defaults = Object.freeze({
|
|
10
|
+
timeoutMs: 50,
|
|
11
|
+
maxLength: 1000,
|
|
12
|
+
fullMatch: true,
|
|
13
|
+
pool: Object.freeze({
|
|
14
|
+
size: 1,
|
|
15
|
+
maxQueue: 100,
|
|
16
|
+
maxWaitMs: 1000,
|
|
17
|
+
resourceLimits: Object.freeze({
|
|
18
|
+
maxOldGenerationSizeMb: 32,
|
|
19
|
+
maxYoungGenerationSizeMb: 8,
|
|
20
|
+
codeRangeSizeMb: 8,
|
|
21
|
+
stackSizeMb: 4,
|
|
22
|
+
}),
|
|
23
|
+
}),
|
|
24
|
+
});
|
|
25
|
+
|
|
26
|
+
const LIMITS = Object.freeze({
|
|
27
|
+
maxTimeoutMs: 60_000,
|
|
28
|
+
maxPoolSize: 64,
|
|
29
|
+
maxQueue: 1_000_000,
|
|
30
|
+
maxWaitMs: 600_000,
|
|
31
|
+
minResourceLimitMb: 1,
|
|
32
|
+
maxResourceLimitMb: 65_536,
|
|
33
|
+
maxStackSizeMb: 1024,
|
|
34
|
+
});
|
|
35
|
+
|
|
36
|
+
const MESSAGE_KEYS = Object.freeze(['notString', 'tooLong', 'noMatch', 'timeout', 'unavailable']);
|
|
37
|
+
const VALIDATOR_KEYS = Object.freeze([
|
|
38
|
+
'timeoutMs',
|
|
39
|
+
'maxLength',
|
|
40
|
+
'flags',
|
|
41
|
+
'fullMatch',
|
|
42
|
+
'messages',
|
|
43
|
+
'onTimeout',
|
|
44
|
+
'onUnavailable',
|
|
45
|
+
]);
|
|
46
|
+
const ASYNC_VALIDATOR_KEYS = Object.freeze([...VALIDATOR_KEYS, 'pool']);
|
|
47
|
+
const TEST_KEYS = Object.freeze(['timeoutMs', 'flags', 'fullMatch']);
|
|
48
|
+
const ASYNC_TEST_KEYS = Object.freeze([...TEST_KEYS, 'pool']);
|
|
49
|
+
const POOL_KEYS = Object.freeze(['size', 'maxQueue', 'maxWaitMs', 'resourceLimits']);
|
|
50
|
+
const RESOURCE_LIMIT_KEYS = Object.freeze(Object.keys(defaults.pool.resourceLimits));
|
|
51
|
+
|
|
52
|
+
/**
|
|
53
|
+
* Reads an options object exactly once into a fresh null-prototype object,
|
|
54
|
+
* rejecting unknown keys. Reading once avoids time-of-check/time-of-use bugs
|
|
55
|
+
* with getters, and rejecting unknown keys catches typos such as `timeout`
|
|
56
|
+
* instead of `timeoutMs` at startup instead of silently using a default.
|
|
57
|
+
*/
|
|
58
|
+
function readOptions(options, allowedKeys, what) {
|
|
59
|
+
const result = Object.create(null);
|
|
60
|
+
if (options === undefined) {
|
|
61
|
+
return result;
|
|
62
|
+
}
|
|
63
|
+
if (options === null || typeof options !== 'object' || Array.isArray(options)) {
|
|
64
|
+
throw new TypeError(`${what} must be an object`);
|
|
65
|
+
}
|
|
66
|
+
for (const key of Object.keys(options)) {
|
|
67
|
+
if (!allowedKeys.includes(key)) {
|
|
68
|
+
throw new TypeError(
|
|
69
|
+
`Unknown option "${key}" in ${what}. Valid options are: ${allowedKeys.join(', ')}`,
|
|
70
|
+
);
|
|
71
|
+
}
|
|
72
|
+
result[key] = options[key];
|
|
73
|
+
}
|
|
74
|
+
return result;
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
function integerOption(value, name, min, max) {
|
|
78
|
+
if (typeof value !== 'number' || !Number.isSafeInteger(value)) {
|
|
79
|
+
throw new TypeError(`The "${name}" option must be an integer`);
|
|
80
|
+
}
|
|
81
|
+
if (value < min || value > max) {
|
|
82
|
+
throw new RangeError(`The "${name}" option must be between ${min} and ${max}`);
|
|
83
|
+
}
|
|
84
|
+
return value;
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
function booleanOption(value, name) {
|
|
88
|
+
if (typeof value !== 'boolean') {
|
|
89
|
+
throw new TypeError(`The "${name}" option must be a boolean`);
|
|
90
|
+
}
|
|
91
|
+
return value;
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
function functionOption(value, name) {
|
|
95
|
+
if (typeof value !== 'function') {
|
|
96
|
+
throw new TypeError(`The "${name}" option must be a function`);
|
|
97
|
+
}
|
|
98
|
+
return value;
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
function timeoutOption(value) {
|
|
102
|
+
return value === undefined
|
|
103
|
+
? defaults.timeoutMs
|
|
104
|
+
: integerOption(value, 'timeoutMs', 1, LIMITS.maxTimeoutMs);
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
function fullMatchOption(value) {
|
|
108
|
+
return value === undefined ? defaults.fullMatch : booleanOption(value, 'fullMatch');
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
/**
|
|
112
|
+
* Validates and compiles a pattern once, when the validator is created
|
|
113
|
+
* (fail fast at startup instead of on the first request).
|
|
114
|
+
*
|
|
115
|
+
* - Accepts a RegExp or a string (with the `flags` option).
|
|
116
|
+
* - Rejects the `g` and `y` flags, which make RegExp#test() stateful.
|
|
117
|
+
* - With `fullMatch` (the default) wraps the pattern as `^(?:pattern)$`, so
|
|
118
|
+
* the whole value must match. This fixes the two classic mistakes: missing
|
|
119
|
+
* anchors and the `^a|b$` precedence trap. The `m` flag is rejected in that
|
|
120
|
+
* mode because it would turn `^`/`$` into line anchors ("evil\nok" would
|
|
121
|
+
* pass).
|
|
122
|
+
*
|
|
123
|
+
* Patterns must come from the developer, never from user input: this package
|
|
124
|
+
* protects against malicious *input*, not against malicious *patterns*.
|
|
125
|
+
*/
|
|
126
|
+
function compilePattern(pattern, flagsOption, fullMatch) {
|
|
127
|
+
let source;
|
|
128
|
+
let flags;
|
|
129
|
+
if (types.isRegExp(pattern)) {
|
|
130
|
+
if (flagsOption !== undefined) {
|
|
131
|
+
throw new TypeError('The "flags" option can only be used when the pattern is a string');
|
|
132
|
+
}
|
|
133
|
+
source = pattern.source;
|
|
134
|
+
flags = pattern.flags;
|
|
135
|
+
} else if (typeof pattern === 'string') {
|
|
136
|
+
if (flagsOption !== undefined && typeof flagsOption !== 'string') {
|
|
137
|
+
throw new TypeError('The "flags" option must be a string');
|
|
138
|
+
}
|
|
139
|
+
source = pattern;
|
|
140
|
+
flags = flagsOption === undefined ? '' : flagsOption;
|
|
141
|
+
} else {
|
|
142
|
+
throw new TypeError('The pattern must be a RegExp or a string');
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
// Compile the pattern exactly as written first. A syntactically valid
|
|
146
|
+
// pattern cannot "escape" the wrapper group added below (e.g. "a)|(.*" is
|
|
147
|
+
// rejected here as invalid before it could become "^(?:a)|(.*)$").
|
|
148
|
+
const original = new RegExp(source, flags);
|
|
149
|
+
flags = original.flags;
|
|
150
|
+
|
|
151
|
+
if (flags.includes('g') || flags.includes('y')) {
|
|
152
|
+
throw new TypeError(
|
|
153
|
+
'The "g" and "y" flags are not allowed: they make RegExp#test() stateful (lastIndex)',
|
|
154
|
+
);
|
|
155
|
+
}
|
|
156
|
+
if (fullMatch && flags.includes('m')) {
|
|
157
|
+
throw new TypeError(
|
|
158
|
+
'The "m" flag cannot be used with fullMatch: it turns ^ and $ into line anchors, ' +
|
|
159
|
+
'so a value such as "evil\\nvalid" would pass. Remove the flag or set fullMatch: false',
|
|
160
|
+
);
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
// Always build a new RegExp owned by this package: a RegExp object passed
|
|
164
|
+
// in by the caller could carry an overridden `exec` method.
|
|
165
|
+
const effectiveSource = fullMatch ? `^(?:${original.source})$` : original.source;
|
|
166
|
+
return {
|
|
167
|
+
regex: new RegExp(effectiveSource, flags),
|
|
168
|
+
source: effectiveSource,
|
|
169
|
+
flags,
|
|
170
|
+
};
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
function messagesOption(value, maxLength) {
|
|
174
|
+
const messages = {
|
|
175
|
+
notString: 'Value must be a string',
|
|
176
|
+
tooLong: `Value must be at most ${maxLength} characters long`,
|
|
177
|
+
noMatch: 'Value has an invalid format',
|
|
178
|
+
timeout: 'Value could not be validated in time',
|
|
179
|
+
unavailable: 'Value could not be validated',
|
|
180
|
+
};
|
|
181
|
+
const custom = readOptions(value, MESSAGE_KEYS, 'the "messages" option');
|
|
182
|
+
for (const key of Object.keys(custom)) {
|
|
183
|
+
if (typeof custom[key] !== 'string' || custom[key].length === 0) {
|
|
184
|
+
throw new TypeError(`messages.${key} must be a non-empty string`);
|
|
185
|
+
}
|
|
186
|
+
messages[key] = custom[key];
|
|
187
|
+
}
|
|
188
|
+
return Object.freeze(messages);
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
/**
|
|
192
|
+
* Normalizes the options of regexTimeout() (mode "sync") and
|
|
193
|
+
* regexTimeoutAsync() (mode "async"). Returns a frozen config object.
|
|
194
|
+
*/
|
|
195
|
+
function normalizeValidatorOptions(pattern, options, mode) {
|
|
196
|
+
const isAsync = mode === 'async';
|
|
197
|
+
const fnName = isAsync ? 'regexTimeoutAsync()' : 'regexTimeout()';
|
|
198
|
+
const raw = readOptions(options, isAsync ? ASYNC_VALIDATOR_KEYS : VALIDATOR_KEYS, `${fnName} options`);
|
|
199
|
+
|
|
200
|
+
const timeoutMs = timeoutOption(raw.timeoutMs);
|
|
201
|
+
const maxLength =
|
|
202
|
+
raw.maxLength === undefined
|
|
203
|
+
? defaults.maxLength
|
|
204
|
+
: integerOption(raw.maxLength, 'maxLength', 0, Number.MAX_SAFE_INTEGER);
|
|
205
|
+
const fullMatch = fullMatchOption(raw.fullMatch);
|
|
206
|
+
const onTimeout = raw.onTimeout === undefined ? undefined : functionOption(raw.onTimeout, 'onTimeout');
|
|
207
|
+
const onUnavailable =
|
|
208
|
+
raw.onUnavailable === undefined ? undefined : functionOption(raw.onUnavailable, 'onUnavailable');
|
|
209
|
+
const messages = messagesOption(raw.messages, maxLength);
|
|
210
|
+
const { regex, source, flags } = compilePattern(pattern, raw.flags, fullMatch);
|
|
211
|
+
|
|
212
|
+
return Object.freeze({
|
|
213
|
+
mode,
|
|
214
|
+
regex,
|
|
215
|
+
source,
|
|
216
|
+
flags,
|
|
217
|
+
timeoutMs,
|
|
218
|
+
maxLength,
|
|
219
|
+
messages,
|
|
220
|
+
onTimeout,
|
|
221
|
+
onUnavailable,
|
|
222
|
+
pool: raw.pool,
|
|
223
|
+
});
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
/**
|
|
227
|
+
* Normalizes the options of testWithTimeout()/testWithTimeoutAsync() and
|
|
228
|
+
* RegexWorkerPool#test().
|
|
229
|
+
*/
|
|
230
|
+
function normalizeTestOptions(options, allowPool, what) {
|
|
231
|
+
const raw = readOptions(options, allowPool ? ASYNC_TEST_KEYS : TEST_KEYS, what);
|
|
232
|
+
return {
|
|
233
|
+
timeoutMs: timeoutOption(raw.timeoutMs),
|
|
234
|
+
flags: raw.flags,
|
|
235
|
+
fullMatch: fullMatchOption(raw.fullMatch),
|
|
236
|
+
pool: raw.pool,
|
|
237
|
+
};
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
function normalizePoolOptions(options) {
|
|
241
|
+
const raw = readOptions(options, POOL_KEYS, 'RegexWorkerPool options');
|
|
242
|
+
const resourceLimits = { ...defaults.pool.resourceLimits };
|
|
243
|
+
const customLimits = readOptions(raw.resourceLimits, RESOURCE_LIMIT_KEYS, 'the "resourceLimits" option');
|
|
244
|
+
for (const key of Object.keys(customLimits)) {
|
|
245
|
+
const value = customLimits[key];
|
|
246
|
+
if (typeof value !== 'number' || !Number.isFinite(value)) {
|
|
247
|
+
throw new TypeError(`resourceLimits.${key} must be a number`);
|
|
248
|
+
}
|
|
249
|
+
// Very small limits are rejected on purpose: a worker started with a tiny
|
|
250
|
+
// stack (e.g. stackSizeMb: 0.1) can crash the whole Node.js process.
|
|
251
|
+
const max = key === 'stackSizeMb' ? LIMITS.maxStackSizeMb : LIMITS.maxResourceLimitMb;
|
|
252
|
+
if (value < LIMITS.minResourceLimitMb || value > max) {
|
|
253
|
+
throw new RangeError(
|
|
254
|
+
`resourceLimits.${key} must be between ${LIMITS.minResourceLimitMb} and ${max}`,
|
|
255
|
+
);
|
|
256
|
+
}
|
|
257
|
+
resourceLimits[key] = value;
|
|
258
|
+
}
|
|
259
|
+
return Object.freeze({
|
|
260
|
+
size:
|
|
261
|
+
raw.size === undefined
|
|
262
|
+
? defaults.pool.size
|
|
263
|
+
: integerOption(raw.size, 'size', 1, LIMITS.maxPoolSize),
|
|
264
|
+
maxQueue:
|
|
265
|
+
raw.maxQueue === undefined
|
|
266
|
+
? defaults.pool.maxQueue
|
|
267
|
+
: integerOption(raw.maxQueue, 'maxQueue', 0, LIMITS.maxQueue),
|
|
268
|
+
maxWaitMs:
|
|
269
|
+
raw.maxWaitMs === undefined
|
|
270
|
+
? defaults.pool.maxWaitMs
|
|
271
|
+
: integerOption(raw.maxWaitMs, 'maxWaitMs', 1, LIMITS.maxWaitMs),
|
|
272
|
+
resourceLimits: Object.freeze(resourceLimits),
|
|
273
|
+
});
|
|
274
|
+
}
|
|
275
|
+
|
|
276
|
+
function assertString(input) {
|
|
277
|
+
if (typeof input !== 'string') {
|
|
278
|
+
throw new TypeError('The input must be a string');
|
|
279
|
+
}
|
|
280
|
+
}
|
|
281
|
+
|
|
282
|
+
module.exports = {
|
|
283
|
+
defaults,
|
|
284
|
+
LIMITS,
|
|
285
|
+
compilePattern,
|
|
286
|
+
normalizeValidatorOptions,
|
|
287
|
+
normalizeTestOptions,
|
|
288
|
+
normalizePoolOptions,
|
|
289
|
+
assertString,
|
|
290
|
+
};
|