valireq 0.0.0-stage → 0.2.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 +39 -0
- package/LICENSE +9 -0
- package/README.md +409 -2
- package/examples/basic.js +81 -0
- package/examples/custom-validation.js +136 -0
- package/examples/nested.js +125 -0
- package/package.json +32 -4
- package/src/index.js +618 -0
package/src/index.js
ADDED
|
@@ -0,0 +1,618 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
const DANGEROUS_KEYS = new Set(['__proto__', 'prototype', 'constructor']);
|
|
4
|
+
const VALID_TYPES = new Set([
|
|
5
|
+
'string',
|
|
6
|
+
'number',
|
|
7
|
+
'integer',
|
|
8
|
+
'boolean',
|
|
9
|
+
'array',
|
|
10
|
+
'object',
|
|
11
|
+
'date',
|
|
12
|
+
]);
|
|
13
|
+
const VALID_UNKNOWN_POLICIES = new Set(['strip', 'strict', 'passthrough']);
|
|
14
|
+
const VALID_SOURCES = new Set(['body', 'query', 'params']);
|
|
15
|
+
|
|
16
|
+
const DEFAULT_OPTIONS = Object.freeze({
|
|
17
|
+
unknown: 'strip',
|
|
18
|
+
maxDepth: 20,
|
|
19
|
+
maxArrayLength: 1000,
|
|
20
|
+
maxObjectKeys: 1000,
|
|
21
|
+
abortEarly: false,
|
|
22
|
+
source: 'body',
|
|
23
|
+
output: 'validated',
|
|
24
|
+
});
|
|
25
|
+
|
|
26
|
+
const own = (object, key) => Object.prototype.hasOwnProperty.call(object, key);
|
|
27
|
+
const isPlainObject = value => {
|
|
28
|
+
if (value === null || typeof value !== 'object') return false;
|
|
29
|
+
const prototype = Object.getPrototypeOf(value);
|
|
30
|
+
return prototype === Object.prototype || prototype === null;
|
|
31
|
+
};
|
|
32
|
+
const isSafeIntegerOption = value => Number.isSafeInteger(value) && value >= 0;
|
|
33
|
+
|
|
34
|
+
class ValidationError extends Error {
|
|
35
|
+
constructor(errors, status = 400) {
|
|
36
|
+
super('Validation failed');
|
|
37
|
+
this.name = 'ValidationError';
|
|
38
|
+
this.errors = errors;
|
|
39
|
+
this.status = status;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
toJSON() {
|
|
43
|
+
return {
|
|
44
|
+
success: false,
|
|
45
|
+
message: this.message,
|
|
46
|
+
errors: this.errors,
|
|
47
|
+
};
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
function pathFor(parent, key) {
|
|
52
|
+
if (!parent) return String(key);
|
|
53
|
+
return /^\d+$/.test(String(key)) ? `${parent}[${key}]` : `${parent}.${key}`;
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
function addError(errors, field, rule, message) {
|
|
57
|
+
errors.push({ field, rule, message });
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
function errorMessage(rule, fallback) {
|
|
61
|
+
return typeof rule.message === 'string' && rule.message.length > 0
|
|
62
|
+
? rule.message
|
|
63
|
+
: fallback;
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
function validateOptions(options) {
|
|
67
|
+
if (!isPlainObject(options)) {
|
|
68
|
+
throw new TypeError('Validation options must be a plain object.');
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
const result = { ...DEFAULT_OPTIONS, ...options };
|
|
72
|
+
if (!VALID_UNKNOWN_POLICIES.has(result.unknown)) {
|
|
73
|
+
throw new TypeError('unknown must be "strip", "strict", or "passthrough".');
|
|
74
|
+
}
|
|
75
|
+
if (!isSafeIntegerOption(result.maxDepth)) {
|
|
76
|
+
throw new TypeError('maxDepth must be a non-negative safe integer.');
|
|
77
|
+
}
|
|
78
|
+
if (!isSafeIntegerOption(result.maxArrayLength)) {
|
|
79
|
+
throw new TypeError('maxArrayLength must be a non-negative safe integer.');
|
|
80
|
+
}
|
|
81
|
+
if (!isSafeIntegerOption(result.maxObjectKeys)) {
|
|
82
|
+
throw new TypeError('maxObjectKeys must be a non-negative safe integer.');
|
|
83
|
+
}
|
|
84
|
+
if (typeof result.abortEarly !== 'boolean') {
|
|
85
|
+
throw new TypeError('abortEarly must be a boolean.');
|
|
86
|
+
}
|
|
87
|
+
if (!VALID_SOURCES.has(result.source)) {
|
|
88
|
+
throw new TypeError('source must be "body", "query", or "params".');
|
|
89
|
+
}
|
|
90
|
+
if (!['validated', 'bySource'].includes(result.output)) {
|
|
91
|
+
throw new TypeError('output must be "validated" or "bySource".');
|
|
92
|
+
}
|
|
93
|
+
if (result.onError !== undefined && typeof result.onError !== 'function') {
|
|
94
|
+
throw new TypeError('onError must be a function.');
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
return result;
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
/**
|
|
101
|
+
* Deep-clone an input value safely. Prevents prototype pollution and enforces
|
|
102
|
+
* depth limits. Returns a new value that shares no object references with the
|
|
103
|
+
* original.
|
|
104
|
+
*/
|
|
105
|
+
function cloneInput(value, depth, maxDepth) {
|
|
106
|
+
if (depth > maxDepth) {
|
|
107
|
+
throw new ValidationError([
|
|
108
|
+
{
|
|
109
|
+
field: '',
|
|
110
|
+
rule: 'maxDepth',
|
|
111
|
+
message: 'Maximum object depth exceeded.',
|
|
112
|
+
},
|
|
113
|
+
]);
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
if (value instanceof Date) return new Date(value.getTime());
|
|
117
|
+
if (Array.isArray(value)) {
|
|
118
|
+
return value.map(item => cloneInput(item, depth + 1, maxDepth));
|
|
119
|
+
}
|
|
120
|
+
if (isPlainObject(value)) {
|
|
121
|
+
const clone = Object.create(null);
|
|
122
|
+
for (const [key, child] of Object.entries(value)) {
|
|
123
|
+
if (!DANGEROUS_KEYS.has(key)) {
|
|
124
|
+
clone[key] = cloneInput(child, depth + 1, maxDepth);
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
return clone;
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
return value;
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
/**
|
|
134
|
+
* Apply sanitization to a string value. Only modifies the string when the
|
|
135
|
+
* developer explicitly enabled the corresponding option.
|
|
136
|
+
*
|
|
137
|
+
* Order of operations matters:
|
|
138
|
+
* 1. removeNullBytes — strip dangerous bytes first
|
|
139
|
+
* 2. trim — remove surrounding whitespace
|
|
140
|
+
* 3. removeExtraSpaces — collapse internal whitespace
|
|
141
|
+
* 4. stripHtml — remove HTML tags
|
|
142
|
+
* 5. normalizeEmail — conservative email normalization
|
|
143
|
+
* 6. lowercase / uppercase — case conversion
|
|
144
|
+
* 7. escapeHtml — escape special characters (after all other transforms)
|
|
145
|
+
*/
|
|
146
|
+
function sanitizeString(value, rule) {
|
|
147
|
+
if (typeof value !== 'string') return value;
|
|
148
|
+
|
|
149
|
+
let result = value;
|
|
150
|
+
if (rule.removeNullBytes) result = result.replace(/\0/g, '');
|
|
151
|
+
if (rule.trim) result = result.trim();
|
|
152
|
+
if (rule.removeExtraSpaces) result = result.replace(/\s+/g, ' ');
|
|
153
|
+
if (rule.stripHtml) result = result.replace(/<[^>]*>/g, '');
|
|
154
|
+
if (rule.normalizeEmail) {
|
|
155
|
+
// Conservative normalization: trim, lowercase, and remove dots from the
|
|
156
|
+
// local part for gmail/googlemail addresses. Does NOT modify other providers
|
|
157
|
+
// beyond lowercasing, which is safe per RFC 5321 §2.4.
|
|
158
|
+
result = result.trim().toLowerCase();
|
|
159
|
+
const atIndex = result.lastIndexOf('@');
|
|
160
|
+
if (atIndex > 0) {
|
|
161
|
+
let local = result.slice(0, atIndex);
|
|
162
|
+
const domain = result.slice(atIndex + 1);
|
|
163
|
+
if (domain === 'gmail.com' || domain === 'googlemail.com') {
|
|
164
|
+
// Remove dots and plus-addressing from Gmail local part.
|
|
165
|
+
const plusIndex = local.indexOf('+');
|
|
166
|
+
if (plusIndex >= 0) local = local.slice(0, plusIndex);
|
|
167
|
+
local = local.replace(/\./g, '');
|
|
168
|
+
}
|
|
169
|
+
result = local + '@' + domain;
|
|
170
|
+
}
|
|
171
|
+
}
|
|
172
|
+
// Apply case conversion only as sanitization. Validation checks for
|
|
173
|
+
// isLowercase / isUppercase are separate rule keys (see addStringErrors).
|
|
174
|
+
if (rule.lowercase) result = result.toLowerCase();
|
|
175
|
+
if (rule.uppercase) result = result.toUpperCase();
|
|
176
|
+
if (rule.escapeHtml) {
|
|
177
|
+
result = result.replace(/[&<>"']/g, character => ({
|
|
178
|
+
'&': '&',
|
|
179
|
+
'<': '<',
|
|
180
|
+
'>': '>',
|
|
181
|
+
'"': '"',
|
|
182
|
+
"'": ''',
|
|
183
|
+
})[character]);
|
|
184
|
+
}
|
|
185
|
+
return result;
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
/**
|
|
189
|
+
* Coerce a string value to the expected type. Returns the original value
|
|
190
|
+
* unchanged when coercion is not applicable or would be ambiguous.
|
|
191
|
+
*/
|
|
192
|
+
function coerceValue(value, type) {
|
|
193
|
+
if (typeof value !== 'string') return value;
|
|
194
|
+
|
|
195
|
+
if (type === 'number') {
|
|
196
|
+
if (value.trim() === '') return value;
|
|
197
|
+
const number = Number(value);
|
|
198
|
+
return Number.isFinite(number) ? number : value;
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
if (type === 'integer') {
|
|
202
|
+
if (value.trim() === '') return value;
|
|
203
|
+
const number = Number(value);
|
|
204
|
+
// Only coerce if the result is a safe integer. "3.5" stays as a string
|
|
205
|
+
// and will fail the type check, which is the documented behavior.
|
|
206
|
+
return Number.isSafeInteger(number) ? number : value;
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
if (type === 'boolean') {
|
|
210
|
+
if (value === 'true' || value === '1') return true;
|
|
211
|
+
if (value === 'false' || value === '0') return false;
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
if (type === 'date') {
|
|
215
|
+
const date = new Date(value);
|
|
216
|
+
if (!Number.isNaN(date.getTime())) return date;
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
return value;
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
function matchesType(value, type) {
|
|
223
|
+
switch (type) {
|
|
224
|
+
case 'string': return typeof value === 'string';
|
|
225
|
+
case 'number': return typeof value === 'number' && Number.isFinite(value);
|
|
226
|
+
case 'integer': return Number.isSafeInteger(value);
|
|
227
|
+
case 'boolean': return typeof value === 'boolean';
|
|
228
|
+
case 'array': return Array.isArray(value);
|
|
229
|
+
case 'object': return isPlainObject(value);
|
|
230
|
+
case 'date': return value instanceof Date && !Number.isNaN(value.getTime());
|
|
231
|
+
default: return false;
|
|
232
|
+
}
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
function validateRule(rule, field) {
|
|
236
|
+
if (!isPlainObject(rule)) {
|
|
237
|
+
throw new TypeError(`Schema rule at "${field}" must be a plain object.`);
|
|
238
|
+
}
|
|
239
|
+
if (rule.type !== undefined && !VALID_TYPES.has(rule.type)) {
|
|
240
|
+
throw new TypeError(`Unsupported type at "${field}": ${String(rule.type)}.`);
|
|
241
|
+
}
|
|
242
|
+
if (rule.transform !== undefined && typeof rule.transform !== 'function') {
|
|
243
|
+
throw new TypeError(`transform at "${field}" must be a function.`);
|
|
244
|
+
}
|
|
245
|
+
if (rule.custom !== undefined && typeof rule.custom !== 'function') {
|
|
246
|
+
throw new TypeError(`custom at "${field}" must be a function.`);
|
|
247
|
+
}
|
|
248
|
+
if (rule.matches !== undefined && !(rule.matches instanceof RegExp)) {
|
|
249
|
+
throw new TypeError(`matches at "${field}" must be a RegExp.`);
|
|
250
|
+
}
|
|
251
|
+
if (rule.properties !== undefined && !isPlainObject(rule.properties)) {
|
|
252
|
+
throw new TypeError(`properties at "${field}" must be a plain object.`);
|
|
253
|
+
}
|
|
254
|
+
if (rule.items !== undefined && !isPlainObject(rule.items)) {
|
|
255
|
+
throw new TypeError(`items at "${field}" must be a plain object.`);
|
|
256
|
+
}
|
|
257
|
+
for (const key of ['enum', 'oneOf']) {
|
|
258
|
+
if (rule[key] !== undefined && !Array.isArray(rule[key])) {
|
|
259
|
+
throw new TypeError(`${key} at "${field}" must be an array.`);
|
|
260
|
+
}
|
|
261
|
+
}
|
|
262
|
+
}
|
|
263
|
+
|
|
264
|
+
/**
|
|
265
|
+
* String-specific validation checks. These run AFTER sanitization, so values
|
|
266
|
+
* have already been trimmed/lowered/etc. if the developer configured it.
|
|
267
|
+
*
|
|
268
|
+
* Note: `lowercase` and `uppercase` as rule keys are sanitizers (they convert
|
|
269
|
+
* the value). For validation-only checks ("must already be lowercase"), use
|
|
270
|
+
* `isLowercase: true` or `isUppercase: true`.
|
|
271
|
+
*/
|
|
272
|
+
function addStringErrors(value, rule, field, errors) {
|
|
273
|
+
const lengthRules = [
|
|
274
|
+
['minLength', (length, limit) => length < limit, limit => `Must be at least ${limit} characters.`],
|
|
275
|
+
['maxLength', (length, limit) => length > limit, limit => `Must be at most ${limit} characters.`],
|
|
276
|
+
['exactLength', (length, limit) => length !== limit, limit => `Must be exactly ${limit} characters.`],
|
|
277
|
+
];
|
|
278
|
+
|
|
279
|
+
for (const [key, fails, message] of lengthRules) {
|
|
280
|
+
if (rule[key] !== undefined && fails(value.length, rule[key])) {
|
|
281
|
+
addError(errors, field, key, errorMessage(rule, message(rule[key])));
|
|
282
|
+
}
|
|
283
|
+
}
|
|
284
|
+
|
|
285
|
+
// Improved email regex: requires at least two chars in TLD, disallows
|
|
286
|
+
// consecutive dots in domain, and limits overall length.
|
|
287
|
+
const emailValid = rule.email
|
|
288
|
+
? /^[^\s@]+@[^\s@]+\.[^\s@]{2,}$/.test(value)
|
|
289
|
+
&& !/\.\./.test(value)
|
|
290
|
+
&& value.length <= 254
|
|
291
|
+
: true;
|
|
292
|
+
|
|
293
|
+
const checks = [
|
|
294
|
+
['email', emailValid, 'Must be a valid email address.'],
|
|
295
|
+
['url', !rule.url || isValidUrl(value), 'Must be a valid URL.'],
|
|
296
|
+
['uuid', !rule.uuid || /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(value), 'Must be a valid UUID.'],
|
|
297
|
+
['alphanumeric', !rule.alphanumeric || /^[a-z0-9]+$/i.test(value), 'Must be alphanumeric.'],
|
|
298
|
+
['numeric', !rule.numeric || /^-?\d+(\.\d+)?$/.test(value), 'Must be a numeric string.'],
|
|
299
|
+
['alphabetic', !rule.alphabetic || /^[a-z]+$/i.test(value), 'Must be alphabetic.'],
|
|
300
|
+
// isLowercase / isUppercase are validation-only (do not transform).
|
|
301
|
+
// lowercase / uppercase are sanitizers (transform the value).
|
|
302
|
+
['isLowercase', !rule.isLowercase || value === value.toLowerCase(), 'Must be lowercase.'],
|
|
303
|
+
['isUppercase', !rule.isUppercase || value === value.toUpperCase(), 'Must be uppercase.'],
|
|
304
|
+
['startsWith', rule.startsWith === undefined || value.startsWith(rule.startsWith), 'Has an invalid prefix.'],
|
|
305
|
+
['endsWith', rule.endsWith === undefined || value.endsWith(rule.endsWith), 'Has an invalid suffix.'],
|
|
306
|
+
['contains', rule.contains === undefined || value.includes(rule.contains), 'Does not contain the required value.'],
|
|
307
|
+
['matches', !rule.matches || testRegex(rule.matches, value), 'Has an invalid format.'],
|
|
308
|
+
];
|
|
309
|
+
|
|
310
|
+
for (const [name, valid, message] of checks) {
|
|
311
|
+
if (!valid) addError(errors, field, name, errorMessage(rule, message));
|
|
312
|
+
}
|
|
313
|
+
}
|
|
314
|
+
|
|
315
|
+
function isValidUrl(value) {
|
|
316
|
+
try {
|
|
317
|
+
const url = new URL(value);
|
|
318
|
+
return Boolean(url.protocol && url.hostname);
|
|
319
|
+
} catch {
|
|
320
|
+
return false;
|
|
321
|
+
}
|
|
322
|
+
}
|
|
323
|
+
|
|
324
|
+
function testRegex(regex, value) {
|
|
325
|
+
regex.lastIndex = 0;
|
|
326
|
+
const result = regex.test(value);
|
|
327
|
+
regex.lastIndex = 0;
|
|
328
|
+
return result;
|
|
329
|
+
}
|
|
330
|
+
|
|
331
|
+
function addNumberErrors(value, rule, field, errors) {
|
|
332
|
+
const checks = [
|
|
333
|
+
['min', value >= rule.min, `Must be at least ${rule.min}.`],
|
|
334
|
+
['max', value <= rule.max, `Must be at most ${rule.max}.`],
|
|
335
|
+
['integer', Number.isInteger(value), 'Must be an integer.'],
|
|
336
|
+
['positive', value > 0, 'Must be positive.'],
|
|
337
|
+
['negative', value < 0, 'Must be negative.'],
|
|
338
|
+
['finite', Number.isFinite(value), 'Must be finite.'],
|
|
339
|
+
];
|
|
340
|
+
|
|
341
|
+
for (const [name, valid, message] of checks) {
|
|
342
|
+
const enabled = name === 'min' || name === 'max'
|
|
343
|
+
? rule[name] !== undefined
|
|
344
|
+
: Boolean(rule[name]);
|
|
345
|
+
if (enabled && !valid) addError(errors, field, name, errorMessage(rule, message));
|
|
346
|
+
}
|
|
347
|
+
}
|
|
348
|
+
|
|
349
|
+
function validateValueRules(value, rule, field, errors) {
|
|
350
|
+
if (typeof value === 'string') addStringErrors(value, rule, field, errors);
|
|
351
|
+
if (typeof value === 'number') addNumberErrors(value, rule, field, errors);
|
|
352
|
+
|
|
353
|
+
if (rule.enum && !rule.enum.includes(value)) {
|
|
354
|
+
addError(errors, field, 'enum', errorMessage(rule, 'Must be one of the allowed values.'));
|
|
355
|
+
}
|
|
356
|
+
if (rule.oneOf && !rule.oneOf.includes(value)) {
|
|
357
|
+
addError(errors, field, 'oneOf', errorMessage(rule, 'Must be one of the allowed values.'));
|
|
358
|
+
}
|
|
359
|
+
if (rule.equals !== undefined && value !== rule.equals) {
|
|
360
|
+
addError(errors, field, 'equals', errorMessage(rule, 'Has an unexpected value.'));
|
|
361
|
+
}
|
|
362
|
+
if (rule.notEquals !== undefined && value === rule.notEquals) {
|
|
363
|
+
addError(errors, field, 'notEquals', errorMessage(rule, 'Has a disallowed value.'));
|
|
364
|
+
}
|
|
365
|
+
}
|
|
366
|
+
|
|
367
|
+
/**
|
|
368
|
+
* Run the user-defined custom validation function. The function MUST return
|
|
369
|
+
* exactly `true` to pass. Any other value (including other truthy values like
|
|
370
|
+
* 1, "yes", etc.) is treated as a validation failure. This prevents subtle bugs
|
|
371
|
+
* where falsy-but-valid values (0, "") cause false positives.
|
|
372
|
+
*/
|
|
373
|
+
async function runCustom(value, rule, field, errors) {
|
|
374
|
+
if (!rule.custom) return;
|
|
375
|
+
try {
|
|
376
|
+
const result = await rule.custom(value);
|
|
377
|
+
if (result !== true) {
|
|
378
|
+
addError(errors, field, 'custom', errorMessage(rule, 'Validation failed.'));
|
|
379
|
+
}
|
|
380
|
+
} catch {
|
|
381
|
+
addError(errors, field, 'custom', errorMessage(rule, 'Validation failed.'));
|
|
382
|
+
}
|
|
383
|
+
}
|
|
384
|
+
|
|
385
|
+
async function processArray(value, rule, options, field, errors, depth) {
|
|
386
|
+
if (value.length > options.maxArrayLength) {
|
|
387
|
+
addError(errors, field, 'maxArrayLength', 'Array is too large.');
|
|
388
|
+
return [];
|
|
389
|
+
}
|
|
390
|
+
|
|
391
|
+
// Validate array-level constraints.
|
|
392
|
+
if (rule.minItems !== undefined && value.length < rule.minItems) {
|
|
393
|
+
addError(errors, field, 'minItems', `Array must have at least ${rule.minItems} items.`);
|
|
394
|
+
}
|
|
395
|
+
if (rule.maxItems !== undefined && value.length > rule.maxItems) {
|
|
396
|
+
addError(errors, field, 'maxItems', `Array must have at most ${rule.maxItems} items.`);
|
|
397
|
+
}
|
|
398
|
+
|
|
399
|
+
if (!rule.items) {
|
|
400
|
+
// No item schema: clone the array to prevent mutation of the input.
|
|
401
|
+
return cloneInput(value, depth + 1, options.maxDepth);
|
|
402
|
+
}
|
|
403
|
+
|
|
404
|
+
const output = [];
|
|
405
|
+
for (let index = 0; index < value.length; index += 1) {
|
|
406
|
+
const itemPath = pathFor(field, index);
|
|
407
|
+
const itemResult = await processField(value[index], rule.items, options, itemPath, errors, depth + 1);
|
|
408
|
+
// Always push the item to maintain correct indices. If an item fails
|
|
409
|
+
// validation, errors are collected and the validated value (or undefined)
|
|
410
|
+
// is placed at the correct index. The caller will check errors.length
|
|
411
|
+
// to decide whether to use the output.
|
|
412
|
+
output.push(itemResult.present ? itemResult.value : undefined);
|
|
413
|
+
if (options.abortEarly && errors.length > 0) break;
|
|
414
|
+
}
|
|
415
|
+
return output;
|
|
416
|
+
}
|
|
417
|
+
|
|
418
|
+
async function processField(input, rule, options, field, errors, depth) {
|
|
419
|
+
validateRule(rule, field);
|
|
420
|
+
let value = input;
|
|
421
|
+
|
|
422
|
+
// Apply default value when input is undefined.
|
|
423
|
+
if (value === undefined && own(rule, 'default')) {
|
|
424
|
+
try {
|
|
425
|
+
value = typeof rule.default === 'function' ? await rule.default() : rule.default;
|
|
426
|
+
} catch {
|
|
427
|
+
addError(errors, field, 'default', 'Could not create the default value.');
|
|
428
|
+
return { present: false };
|
|
429
|
+
}
|
|
430
|
+
}
|
|
431
|
+
|
|
432
|
+
// Handle undefined (missing) values.
|
|
433
|
+
if (value === undefined) {
|
|
434
|
+
if (rule.required) {
|
|
435
|
+
addError(errors, field, 'required', errorMessage(rule, 'This field is required.'));
|
|
436
|
+
}
|
|
437
|
+
return { present: false };
|
|
438
|
+
}
|
|
439
|
+
|
|
440
|
+
// Handle null values.
|
|
441
|
+
if (value === null) {
|
|
442
|
+
if (rule.nullable) return { present: true, value: null };
|
|
443
|
+
if (rule.required) {
|
|
444
|
+
addError(errors, field, 'required', errorMessage(rule, 'This field is required.'));
|
|
445
|
+
} else {
|
|
446
|
+
addError(errors, field, 'nullable', errorMessage(rule, 'This field cannot be null.'));
|
|
447
|
+
}
|
|
448
|
+
return { present: false };
|
|
449
|
+
}
|
|
450
|
+
|
|
451
|
+
// Sanitize string values.
|
|
452
|
+
value = sanitizeString(value, rule);
|
|
453
|
+
|
|
454
|
+
// Coerce string values to the target type.
|
|
455
|
+
if (rule.coerce) value = coerceValue(value, rule.type);
|
|
456
|
+
|
|
457
|
+
// Apply custom transform.
|
|
458
|
+
if (rule.transform) {
|
|
459
|
+
try {
|
|
460
|
+
value = await rule.transform(value);
|
|
461
|
+
} catch {
|
|
462
|
+
addError(errors, field, 'transform', 'Transformation failed.');
|
|
463
|
+
return { present: false };
|
|
464
|
+
}
|
|
465
|
+
}
|
|
466
|
+
|
|
467
|
+
// Handle empty strings. Must come after sanitization/transform so that
|
|
468
|
+
// trimming can produce an empty string.
|
|
469
|
+
if (value === '' && rule.rejectEmpty) {
|
|
470
|
+
addError(errors, field, 'empty', errorMessage(rule, 'Must not be empty.'));
|
|
471
|
+
return { present: false };
|
|
472
|
+
}
|
|
473
|
+
|
|
474
|
+
// Type check.
|
|
475
|
+
if (rule.type && !matchesType(value, rule.type)) {
|
|
476
|
+
addError(errors, field, 'type', errorMessage(rule, `Expected type ${rule.type}.`));
|
|
477
|
+
return { present: false };
|
|
478
|
+
}
|
|
479
|
+
|
|
480
|
+
// Process nested objects. If a rule has `properties`, it implies type object.
|
|
481
|
+
if (rule.properties && isPlainObject(value)) {
|
|
482
|
+
value = await processObject(value, rule.properties, options, field, errors, depth + 1);
|
|
483
|
+
} else if (rule.type === 'object' && !rule.properties) {
|
|
484
|
+
// Object type without properties: clone to prevent input mutation.
|
|
485
|
+
value = cloneInput(value, depth + 1, options.maxDepth);
|
|
486
|
+
}
|
|
487
|
+
|
|
488
|
+
// Process arrays.
|
|
489
|
+
if (rule.type === 'array') {
|
|
490
|
+
value = await processArray(value, rule, options, field, errors, depth);
|
|
491
|
+
}
|
|
492
|
+
|
|
493
|
+
// Clone Date to prevent input mutation via the returned reference.
|
|
494
|
+
if (value instanceof Date) {
|
|
495
|
+
value = new Date(value.getTime());
|
|
496
|
+
}
|
|
497
|
+
|
|
498
|
+
// Validate value-level rules (string checks, number checks, enum, etc.).
|
|
499
|
+
validateValueRules(value, rule, field, errors);
|
|
500
|
+
await runCustom(value, rule, field, errors);
|
|
501
|
+
|
|
502
|
+
// Determine whether the field should appear in the output.
|
|
503
|
+
// - Empty strings are excluded unless `allowEmpty` or `required` is set.
|
|
504
|
+
// - Transform returning undefined makes the field absent.
|
|
505
|
+
if (value === undefined) {
|
|
506
|
+
return { present: false };
|
|
507
|
+
}
|
|
508
|
+
const present = value !== '' || rule.allowEmpty === true || rule.required === true;
|
|
509
|
+
|
|
510
|
+
return { present, value };
|
|
511
|
+
}
|
|
512
|
+
|
|
513
|
+
async function processObject(input, schema, options, basePath, errors, depth) {
|
|
514
|
+
if (!isPlainObject(input)) {
|
|
515
|
+
addError(errors, basePath, 'type', 'Expected an object.');
|
|
516
|
+
return Object.create(null);
|
|
517
|
+
}
|
|
518
|
+
if (depth > options.maxDepth) {
|
|
519
|
+
addError(errors, basePath, 'maxDepth', 'Maximum object depth exceeded.');
|
|
520
|
+
return Object.create(null);
|
|
521
|
+
}
|
|
522
|
+
|
|
523
|
+
const inputKeys = Object.keys(input);
|
|
524
|
+
if (inputKeys.length > options.maxObjectKeys) {
|
|
525
|
+
addError(errors, basePath, 'maxObjectKeys', 'Too many object properties.');
|
|
526
|
+
return Object.create(null);
|
|
527
|
+
}
|
|
528
|
+
|
|
529
|
+
const output = Object.create(null);
|
|
530
|
+
if (options.unknown === 'strict') {
|
|
531
|
+
for (const key of inputKeys) {
|
|
532
|
+
if (!own(schema, key)) {
|
|
533
|
+
addError(errors, pathFor(basePath, key), 'unknown', 'Unknown field.');
|
|
534
|
+
}
|
|
535
|
+
}
|
|
536
|
+
}
|
|
537
|
+
|
|
538
|
+
for (const key of Object.keys(schema)) {
|
|
539
|
+
if (DANGEROUS_KEYS.has(key)) continue;
|
|
540
|
+
const fieldPath = pathFor(basePath, key);
|
|
541
|
+
const result = await processField(input[key], schema[key], options, fieldPath, errors, depth);
|
|
542
|
+
if (result.present) output[key] = result.value;
|
|
543
|
+
if (options.abortEarly && errors.length > 0) break;
|
|
544
|
+
}
|
|
545
|
+
|
|
546
|
+
if (options.unknown === 'passthrough') {
|
|
547
|
+
for (const key of inputKeys) {
|
|
548
|
+
if (!own(schema, key) && !DANGEROUS_KEYS.has(key)) {
|
|
549
|
+
output[key] = cloneInput(input[key], depth + 1, options.maxDepth);
|
|
550
|
+
}
|
|
551
|
+
}
|
|
552
|
+
}
|
|
553
|
+
|
|
554
|
+
return output;
|
|
555
|
+
}
|
|
556
|
+
|
|
557
|
+
/**
|
|
558
|
+
* Validate data against a schema. This is the Express-independent core API.
|
|
559
|
+
*
|
|
560
|
+
* @param {*} input - The data to validate.
|
|
561
|
+
* @param {Object} schema - The validation schema.
|
|
562
|
+
* @param {Object} [options] - Validation options.
|
|
563
|
+
* @returns {Promise<Object>} The validated and cleaned output.
|
|
564
|
+
* @throws {ValidationError} When validation fails.
|
|
565
|
+
* @throws {TypeError} When the schema or options are malformed.
|
|
566
|
+
*/
|
|
567
|
+
async function validateData(input, schema, options = {}) {
|
|
568
|
+
const normalizedOptions = validateOptions(options);
|
|
569
|
+
if (!isPlainObject(schema)) {
|
|
570
|
+
throw new TypeError('Schema must be a plain object.');
|
|
571
|
+
}
|
|
572
|
+
|
|
573
|
+
const source = input === undefined || input === null ? Object.create(null) : input;
|
|
574
|
+
const errors = [];
|
|
575
|
+
const output = await processObject(source, schema, normalizedOptions, '', errors, 0);
|
|
576
|
+
if (errors.length > 0) throw new ValidationError(errors);
|
|
577
|
+
return output;
|
|
578
|
+
}
|
|
579
|
+
|
|
580
|
+
/**
|
|
581
|
+
* Express middleware factory. Returns an async middleware function that
|
|
582
|
+
* validates request data against the given schema.
|
|
583
|
+
*
|
|
584
|
+
* @param {Object} schema - The validation schema.
|
|
585
|
+
* @param {Object} [options] - Validation options.
|
|
586
|
+
* @returns {Function} Express middleware function.
|
|
587
|
+
*/
|
|
588
|
+
function validate(schema, options = {}) {
|
|
589
|
+
// Validate options eagerly at middleware creation time, not per-request.
|
|
590
|
+
// This catches configuration errors early during app startup.
|
|
591
|
+
const normalizedOptions = validateOptions(options);
|
|
592
|
+
|
|
593
|
+
return async function valireqMiddleware(req, res, next) {
|
|
594
|
+
try {
|
|
595
|
+
const result = await validateData(req[normalizedOptions.source], schema, normalizedOptions);
|
|
596
|
+
|
|
597
|
+
if (normalizedOptions.output === 'bySource') {
|
|
598
|
+
req.validated = req.validated || {};
|
|
599
|
+
req.validated[normalizedOptions.source] = result;
|
|
600
|
+
} else {
|
|
601
|
+
req.validated = result;
|
|
602
|
+
}
|
|
603
|
+
return next();
|
|
604
|
+
} catch (error) {
|
|
605
|
+
if (!(error instanceof ValidationError)) return next(error);
|
|
606
|
+
if (typeof normalizedOptions.onError === 'function') {
|
|
607
|
+
return normalizedOptions.onError(error, req, res, next);
|
|
608
|
+
}
|
|
609
|
+
return res.status(error.status).json(error.toJSON());
|
|
610
|
+
}
|
|
611
|
+
};
|
|
612
|
+
}
|
|
613
|
+
|
|
614
|
+
module.exports = {
|
|
615
|
+
validate,
|
|
616
|
+
validateData,
|
|
617
|
+
ValidationError,
|
|
618
|
+
};
|