@seip/bluebird-js 0.0.1 → 0.1.1
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/.env_example +53 -53
- package/AGENTS.md +426 -403
- package/LICENSE +1 -1
- package/README.md +292 -285
- package/app/routes/api.js +50 -50
- package/app/routes/web.js +55 -53
- package/app/views/about.js +63 -0
- package/app/views/dashboard.js +147 -0
- package/app/views/index.js +80 -0
- package/app/views/layouts/main/view.js +81 -0
- package/app/views/legal/terms.html +19 -0
- package/app/views/login.js +80 -0
- package/core/app.d.ts +18 -18
- package/core/app.js +684 -644
- package/core/auth.d.ts +13 -13
- package/core/auth.js +326 -326
- package/core/cache.d.ts +17 -17
- package/core/cache.js +475 -475
- package/core/cli/doctor.js +287 -287
- package/core/cli/ecosystem.js +162 -162
- package/core/cli/init.js +779 -779
- package/core/cli/migrate.js +541 -541
- package/core/cli/model.js +66 -66
- package/core/cli/nginx.js +199 -199
- package/core/cli/route.js +120 -120
- package/core/cli/view.js +55 -36
- package/core/config.d.ts +3 -3
- package/core/config.js +111 -111
- package/core/csrf.d.ts +3 -3
- package/core/csrf.js +114 -114
- package/core/database.d.ts +15 -15
- package/core/database.js +636 -636
- package/core/debug.d.ts +3 -3
- package/core/debug.js +249 -249
- package/core/hash.d.ts +3 -3
- package/core/hash.js +194 -194
- package/core/html.d.ts +42 -0
- package/core/html.js +217 -0
- package/core/index.d.ts +1176 -1071
- package/core/logger.d.ts +3 -3
- package/core/logger.js +127 -124
- package/core/middleware.d.ts +3 -3
- package/core/middleware.js +28 -28
- package/core/model.d.ts +19 -19
- package/core/model.js +600 -600
- package/core/queue.d.ts +13 -13
- package/core/queue.js +172 -172
- package/core/ratelimit.d.ts +3 -3
- package/core/ratelimit.js +145 -145
- package/core/redis.d.ts +21 -21
- package/core/redis.js +230 -230
- package/core/render-cache.js +212 -0
- package/core/render.d.ts +3 -3
- package/core/render.js +199 -555
- package/core/router.d.ts +3 -3
- package/core/router.js +171 -171
- package/core/seo.d.ts +3 -3
- package/core/seo.js +106 -106
- package/core/swagger.d.ts +3 -3
- package/core/swagger.js +60 -60
- package/core/upload.d.ts +13 -13
- package/core/upload.js +102 -102
- package/core/util/colors.js +82 -82
- package/core/validate.d.ts +15 -15
- package/core/validate.js +364 -364
- package/core/view-loader.js +162 -0
- package/core/vite.d.ts +3 -3
- package/core/vite.js +145 -145
- package/core/ws.d.ts +13 -13
- package/core/ws.js +245 -245
- package/index.js +18 -18
- package/jsconfig.json +15 -15
- package/package.json +85 -86
- package/production.md +273 -273
- package/public/css/bluebird.min.css +1 -1
- package/public/js/bluebird-client.js +1780 -1662
- package/public/js/bluebird.min.js +1072 -1072
- package/app/views/about.html +0 -161
- package/app/views/dashboard.html +0 -140
- package/app/views/index.html +0 -150
- package/app/views/login.html +0 -144
package/core/validate.js
CHANGED
|
@@ -1,364 +1,364 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Escapes HTML special characters to prevent XSS in string field values.
|
|
3
|
-
* @param {string} value
|
|
4
|
-
* @returns {string}
|
|
5
|
-
*/
|
|
6
|
-
function escapeXss(value) {
|
|
7
|
-
return String(value)
|
|
8
|
-
.replace(/&/g, "&")
|
|
9
|
-
.replace(/</g, "<")
|
|
10
|
-
.replace(/>/g, ">")
|
|
11
|
-
.replace(/"/g, """)
|
|
12
|
-
.replace(/'/g, "'")
|
|
13
|
-
.replace(/\//g, "/");
|
|
14
|
-
}
|
|
15
|
-
|
|
16
|
-
const messages_default = {
|
|
17
|
-
es: {
|
|
18
|
-
required: (f) => `El campo ${f} es obligatorio`,
|
|
19
|
-
min: (f, n) => `El campo ${f} debe tener al menos ${n} caracteres`,
|
|
20
|
-
max: (f, n) => `El campo ${f} no puede tener más de ${n} caracteres`,
|
|
21
|
-
email: (f) => `El campo ${f} debe ser un email válido`,
|
|
22
|
-
number: (f) => `El campo ${f} debe ser numérico`,
|
|
23
|
-
alpha: (f) => `El campo ${f} solo puede contener letras`,
|
|
24
|
-
alphanumeric: (f) => `El campo ${f} solo puede contener letras y números`,
|
|
25
|
-
boolean: (f) => `El campo ${f} debe ser verdadero o falso`,
|
|
26
|
-
date: (f) => `El campo ${f} debe ser una fecha válida`,
|
|
27
|
-
url: (f) => `El campo ${f} debe ser una URL válida`,
|
|
28
|
-
in: (f, v) => `El campo ${f} debe ser uno de: ${v.join(", ")}`,
|
|
29
|
-
equals: (f, v) => `El campo ${f} debe ser igual a ${v}`,
|
|
30
|
-
password: () => `La contraseña debe tener mayúsculas, minúsculas y números`,
|
|
31
|
-
pattern: (f) => `El campo ${f} no cumple el patrón requerido`,
|
|
32
|
-
},
|
|
33
|
-
en: {
|
|
34
|
-
required: (f) => `${f} is required`,
|
|
35
|
-
min: (f, n) => `${f} must be at least ${n} characters`,
|
|
36
|
-
max: (f, n) => `${f} must be at most ${n} characters`,
|
|
37
|
-
email: (f) => `${f} must be a valid email`,
|
|
38
|
-
number: (f) => `${f} must be numeric`,
|
|
39
|
-
alpha: (f) => `${f} must contain only letters`,
|
|
40
|
-
alphanumeric: (f) => `${f} must contain only letters and numbers`,
|
|
41
|
-
boolean: (f) => `${f} must be true or false`,
|
|
42
|
-
date: (f) => `${f} must be a valid date`,
|
|
43
|
-
url: (f) => `${f} must be a valid URL`,
|
|
44
|
-
in: (f, v) => `${f} must be one of: ${v.join(", ")}`,
|
|
45
|
-
equals: (f, v) => `${f} must equal ${v}`,
|
|
46
|
-
password: () => `Password must contain uppercase, lowercase and numbers`,
|
|
47
|
-
pattern: (f) => `${f} does not match the required pattern`,
|
|
48
|
-
},
|
|
49
|
-
pt: {
|
|
50
|
-
required: (f) => `O campo ${f} é obrigatório`,
|
|
51
|
-
min: (f, n) => `O campo ${f} deve ter pelo menos ${n} caracteres`,
|
|
52
|
-
max: (f, n) => `O campo ${f} não pode ter mais de ${n} caracteres`,
|
|
53
|
-
email: (f) => `O campo ${f} deve ser um email válido`,
|
|
54
|
-
number: (f) => `O campo ${f} deve ser numérico`,
|
|
55
|
-
alpha: (f) => `O campo ${f} só pode conter letras`,
|
|
56
|
-
alphanumeric: (f) => `O campo ${f} só pode conter letras e números`,
|
|
57
|
-
boolean: (f) => `O campo ${f} deve ser verdadeiro ou falso`,
|
|
58
|
-
date: (f) => `O campo ${f} deve ser uma data válida`,
|
|
59
|
-
url: (f) => `O campo ${f} deve ser uma URL válida`,
|
|
60
|
-
in: (f, v) => `O campo ${f} deve ser um de: ${v.join(", ")}`,
|
|
61
|
-
equals: (f, v) => `O campo ${f} deve ser igual a ${v}`,
|
|
62
|
-
password: () => `A senha deve conter maiúsculas, minúsculas e números`,
|
|
63
|
-
pattern: (f) => `O campo ${f} não corresponde ao padrão exigido`,
|
|
64
|
-
},
|
|
65
|
-
br: {
|
|
66
|
-
required: (f) => `O campo ${f} é obrigatório`,
|
|
67
|
-
min: (f, n) => `O campo ${f} deve ter pelo menos ${n} caracteres`,
|
|
68
|
-
max: (f, n) => `O campo ${f} não pode ter mais de ${n} caracteres`,
|
|
69
|
-
email: (f) => `O campo ${f} deve ser um email válido`,
|
|
70
|
-
number: (f) => `O campo ${f} deve ser numérico`,
|
|
71
|
-
alpha: (f) => `O campo ${f} só pode conter letras`,
|
|
72
|
-
alphanumeric: (f) => `O campo ${f} só pode conter letras e números`,
|
|
73
|
-
boolean: (f) => `O campo ${f} deve ser verdadeiro ou falso`,
|
|
74
|
-
date: (f) => `O campo ${f} deve ser uma data válida`,
|
|
75
|
-
url: (f) => `O campo ${f} deve ser uma URL válida`,
|
|
76
|
-
in: (f, v) => `O campo ${f} deve ser um de: ${v.join(", ")}`,
|
|
77
|
-
equals: (f, v) => `O campo ${f} deve ser igual a ${v}`,
|
|
78
|
-
password: () => `A senha deve conter maiúsculas, minúsculas e números`,
|
|
79
|
-
pattern: (f) => `O campo ${f} não corresponde ao padrão exigido`,
|
|
80
|
-
},
|
|
81
|
-
fr: {
|
|
82
|
-
required: (f) => `Le champ ${f} est obligatoire`,
|
|
83
|
-
min: (f, n) => `Le champ ${f} doit contenir au moins ${n} caractères`,
|
|
84
|
-
max: (f, n) => `Le champ ${f} ne peut pas contenir plus de ${n} caractères`,
|
|
85
|
-
email: (f) => `Le champ ${f} doit être un email valide`,
|
|
86
|
-
number: (f) => `Le champ ${f} doit être numérique`,
|
|
87
|
-
alpha: (f) => `Le champ ${f} ne peut contenir que des lettres`,
|
|
88
|
-
alphanumeric: (f) =>
|
|
89
|
-
`Le champ ${f} ne peut contenir que des lettres et des chiffres`,
|
|
90
|
-
boolean: (f) => `Le champ ${f} doit être vrai ou faux`,
|
|
91
|
-
date: (f) => `Le champ ${f} doit être une date valide`,
|
|
92
|
-
url: (f) => `Le champ ${f} doit être une URL valide`,
|
|
93
|
-
in: (f, v) => `Le champ ${f} doit être l'un de: ${v.join(", ")}`,
|
|
94
|
-
equals: (f, v) => `Le champ ${f} doit être égal à ${v}`,
|
|
95
|
-
password: () =>
|
|
96
|
-
`Le mot de passe doit contenir des majuscules, des minuscules et des chiffres`,
|
|
97
|
-
pattern: (f) => `Le champ ${f} ne correspond pas au modèle requis`,
|
|
98
|
-
},
|
|
99
|
-
};
|
|
100
|
-
|
|
101
|
-
const validators = {
|
|
102
|
-
isEmpty: (value) => value === undefined || value === null || value === "",
|
|
103
|
-
isEmail: (value) => /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(value),
|
|
104
|
-
isNumeric: (value) => !isNaN(value) && !isNaN(parseFloat(value)),
|
|
105
|
-
isAlpha: (value) => /^[a-zA-Z]+$/.test(value),
|
|
106
|
-
isAlphanumeric: (value) => /^[a-zA-Z0-9]+$/.test(value),
|
|
107
|
-
isBoolean: (value) =>
|
|
108
|
-
value === true || value === false || value === "true" || value === "false",
|
|
109
|
-
isISO8601: (value) => !isNaN(Date.parse(value)),
|
|
110
|
-
isURL: (value) => {
|
|
111
|
-
try {
|
|
112
|
-
new URL(value);
|
|
113
|
-
return true;
|
|
114
|
-
} catch {
|
|
115
|
-
return false;
|
|
116
|
-
}
|
|
117
|
-
},
|
|
118
|
-
isLength: (value, { min, max }) => {
|
|
119
|
-
const len = String(value).length;
|
|
120
|
-
if (min !== undefined && len < min) return false;
|
|
121
|
-
if (max !== undefined && len > max) return false;
|
|
122
|
-
return true;
|
|
123
|
-
},
|
|
124
|
-
isIn: (value, values) => values.includes(value),
|
|
125
|
-
equals: (value, comparison) => value === comparison,
|
|
126
|
-
matches: (value, pattern) => {
|
|
127
|
-
if (pattern instanceof RegExp) {
|
|
128
|
-
pattern.lastIndex = 0;
|
|
129
|
-
return pattern.test(String(value));
|
|
130
|
-
}
|
|
131
|
-
return new RegExp(pattern).test(String(value));
|
|
132
|
-
},
|
|
133
|
-
};
|
|
134
|
-
|
|
135
|
-
/**
|
|
136
|
-
* Comprehensive Validator class for handling multi-language data validation.
|
|
137
|
-
*/
|
|
138
|
-
class Validator {
|
|
139
|
-
/**
|
|
140
|
-
* Initializes the Validator instance with a schema and optional language settings.
|
|
141
|
-
* @param {Object} schema - Validation rules for each field (e.g., { email: { required: true, email: true } }).
|
|
142
|
-
* @param {string} [lang_default=null] - Default language for error messages (e.g., "en", "es").
|
|
143
|
-
* @param {Object} [messages=null] - Custom message overrides for validation rules.
|
|
144
|
-
* @example
|
|
145
|
-
* const loginSchema = {
|
|
146
|
-
* email: { required: true, email: true },
|
|
147
|
-
* password: { required: true, min: 6 }
|
|
148
|
-
* };
|
|
149
|
-
* const loginValidator = new Validator(loginSchema, 'en');
|
|
150
|
-
*/
|
|
151
|
-
constructor(schema, lang_default = null, messages = null) {
|
|
152
|
-
this.schema = schema || {};
|
|
153
|
-
this.lang_default = lang_default;
|
|
154
|
-
this.messages = messages ? messages : messages_default;
|
|
155
|
-
}
|
|
156
|
-
|
|
157
|
-
/**
|
|
158
|
-
* Validates the request body or plain data object against the defined schema.
|
|
159
|
-
* @param {import('express').Request|Object} req - Express request object or plain data dictionary.
|
|
160
|
-
* @returns {Promise<{success: boolean, error: boolean, errors: Array<{field: string, message: string}>, message: Array<string>, html: Array<string>}>}
|
|
161
|
-
*/
|
|
162
|
-
async validate(req) {
|
|
163
|
-
const isExpressReq = req && typeof req === "object" && ("body" in req || "headers" in req || "query" in req);
|
|
164
|
-
let lang = this.lang_default;
|
|
165
|
-
if (!lang && isExpressReq) {
|
|
166
|
-
lang =
|
|
167
|
-
req.query?.lang ||
|
|
168
|
-
req.body?.lang ||
|
|
169
|
-
req.params?.lang ||
|
|
170
|
-
req.cookies?.lang ||
|
|
171
|
-
req.headers?.["accept-language"]?.split(",")[0]?.split("-")[0] ||
|
|
172
|
-
req.session?.lang;
|
|
173
|
-
}
|
|
174
|
-
lang = lang || "en";
|
|
175
|
-
|
|
176
|
-
const msg = this.messages[lang] || this.messages.en || this.messages.es;
|
|
177
|
-
const errors = [];
|
|
178
|
-
const messages = [];
|
|
179
|
-
const body = isExpressReq ? (req.body || {}) : (req || {});
|
|
180
|
-
|
|
181
|
-
for (const [field, config] of Object.entries(this.schema)) {
|
|
182
|
-
let value = body[field];
|
|
183
|
-
|
|
184
|
-
if (config.xss === true && typeof value === "string") {
|
|
185
|
-
body[field] = escapeXss(value);
|
|
186
|
-
value = body[field];
|
|
187
|
-
}
|
|
188
|
-
|
|
189
|
-
if (config.required && validators.isEmpty(value)) {
|
|
190
|
-
const errorMsg = config.messages?.required || msg.required(field);
|
|
191
|
-
messages.push(errorMsg);
|
|
192
|
-
errors.push({ field, message: errorMsg });
|
|
193
|
-
continue;
|
|
194
|
-
}
|
|
195
|
-
|
|
196
|
-
if (!validators.isEmpty(value)) {
|
|
197
|
-
if (
|
|
198
|
-
config.min !== undefined &&
|
|
199
|
-
!validators.isLength(value, { min: config.min })
|
|
200
|
-
) {
|
|
201
|
-
const errorMsg = config.messages?.min || msg.min(field, config.min);
|
|
202
|
-
messages.push(errorMsg);
|
|
203
|
-
errors.push({ field, message: errorMsg });
|
|
204
|
-
}
|
|
205
|
-
if (
|
|
206
|
-
config.max !== undefined &&
|
|
207
|
-
!validators.isLength(value, { max: config.max })
|
|
208
|
-
) {
|
|
209
|
-
const errorMsg = config.messages?.max || msg.max(field, config.max);
|
|
210
|
-
messages.push(errorMsg);
|
|
211
|
-
errors.push({ field, message: errorMsg });
|
|
212
|
-
}
|
|
213
|
-
if (config.email && !validators.isEmail(value)) {
|
|
214
|
-
const errorMsg = config.messages?.email || msg.email(field);
|
|
215
|
-
messages.push(errorMsg);
|
|
216
|
-
errors.push({ field, message: errorMsg });
|
|
217
|
-
}
|
|
218
|
-
if (config.number && !validators.isNumeric(value)) {
|
|
219
|
-
const errorMsg = config.messages?.number || msg.number(field);
|
|
220
|
-
messages.push(errorMsg);
|
|
221
|
-
errors.push({ field, message: errorMsg });
|
|
222
|
-
}
|
|
223
|
-
if (config.alpha && !validators.isAlpha(value)) {
|
|
224
|
-
const errorMsg = config.messages?.alpha || msg.alpha(field);
|
|
225
|
-
messages.push(errorMsg);
|
|
226
|
-
errors.push({ field, message: errorMsg });
|
|
227
|
-
}
|
|
228
|
-
if (config.alphanumeric && !validators.isAlphanumeric(value)) {
|
|
229
|
-
const errorMsg = config.messages?.alphanumeric || msg.alphanumeric(field);
|
|
230
|
-
messages.push(errorMsg);
|
|
231
|
-
errors.push({ field, message: errorMsg });
|
|
232
|
-
}
|
|
233
|
-
if (config.boolean && !validators.isBoolean(value)) {
|
|
234
|
-
const errorMsg = config.messages?.boolean || msg.boolean(field);
|
|
235
|
-
messages.push(errorMsg);
|
|
236
|
-
errors.push({ field, message: errorMsg });
|
|
237
|
-
}
|
|
238
|
-
if (config.date && !validators.isISO8601(value)) {
|
|
239
|
-
const errorMsg = config.messages?.date || msg.date(field);
|
|
240
|
-
messages.push(errorMsg);
|
|
241
|
-
errors.push({ field, message: errorMsg });
|
|
242
|
-
}
|
|
243
|
-
if (config.url && !validators.isURL(value)) {
|
|
244
|
-
const errorMsg = config.messages?.url || msg.url(field);
|
|
245
|
-
messages.push(errorMsg);
|
|
246
|
-
errors.push({ field, message: errorMsg });
|
|
247
|
-
}
|
|
248
|
-
if (config.in && !validators.isIn(value, config.in)) {
|
|
249
|
-
const errorMsg = config.messages?.in || msg.in(field, config.in);
|
|
250
|
-
messages.push(errorMsg);
|
|
251
|
-
errors.push({ field, message: errorMsg });
|
|
252
|
-
}
|
|
253
|
-
if (
|
|
254
|
-
config.equals !== undefined &&
|
|
255
|
-
!validators.equals(value, config.equals)
|
|
256
|
-
) {
|
|
257
|
-
const errorMsg = config.messages?.equals || msg.equals(field, config.equals);
|
|
258
|
-
messages.push(errorMsg);
|
|
259
|
-
errors.push({ field, message: errorMsg });
|
|
260
|
-
}
|
|
261
|
-
if (
|
|
262
|
-
config.password &&
|
|
263
|
-
!validators.matches(value, /^(?=.*[A-Z])(?=.*[a-z])(?=.*\d).{6,}$/)
|
|
264
|
-
) {
|
|
265
|
-
const errorMsg = config.messages?.password || msg.password(field);
|
|
266
|
-
messages.push(errorMsg);
|
|
267
|
-
errors.push({ field, message: errorMsg });
|
|
268
|
-
}
|
|
269
|
-
if (config.pattern && !validators.matches(value, config.pattern)) {
|
|
270
|
-
const errorMsg = config.messages?.pattern || msg.pattern(field);
|
|
271
|
-
messages.push(errorMsg);
|
|
272
|
-
errors.push({ field, message: errorMsg });
|
|
273
|
-
}
|
|
274
|
-
}
|
|
275
|
-
}
|
|
276
|
-
|
|
277
|
-
if (errors.length > 0) {
|
|
278
|
-
return {
|
|
279
|
-
success: false,
|
|
280
|
-
error: true,
|
|
281
|
-
errors: errors,
|
|
282
|
-
message: messages,
|
|
283
|
-
html: [],
|
|
284
|
-
};
|
|
285
|
-
}
|
|
286
|
-
|
|
287
|
-
return { success: true, error: false, errors: [], message: [], html: [] };
|
|
288
|
-
}
|
|
289
|
-
|
|
290
|
-
/**
|
|
291
|
-
* Express middleware for automated validation of the request body.
|
|
292
|
-
* Returns a 400 Bad Request response with validation results if errors occur.
|
|
293
|
-
* @returns {Function} Express middleware function (req, res, next).
|
|
294
|
-
*/
|
|
295
|
-
middleware() {
|
|
296
|
-
return async (req, res, next) => {
|
|
297
|
-
const result = await this.validate(req);
|
|
298
|
-
if (!result.success) {
|
|
299
|
-
return res.status(400).json(result);
|
|
300
|
-
}
|
|
301
|
-
next();
|
|
302
|
-
};
|
|
303
|
-
}
|
|
304
|
-
|
|
305
|
-
/**
|
|
306
|
-
* Express middleware for explicitly sanitizing request data against XSS.
|
|
307
|
-
* Can be used on specific routes where HTML input is not expected.
|
|
308
|
-
* @returns {Function} Express middleware function.
|
|
309
|
-
*/
|
|
310
|
-
static xssMiddleware() {
|
|
311
|
-
return (req, res, next) => {
|
|
312
|
-
if (req.body && typeof req.body === "object") {
|
|
313
|
-
Validator.mutateSanitized(req.body);
|
|
314
|
-
}
|
|
315
|
-
if (req.query && typeof req.query === "object") {
|
|
316
|
-
Validator.mutateSanitized(req.query);
|
|
317
|
-
}
|
|
318
|
-
if (req.params && typeof req.params === "object") {
|
|
319
|
-
Validator.mutateSanitized(req.params);
|
|
320
|
-
}
|
|
321
|
-
next();
|
|
322
|
-
};
|
|
323
|
-
}
|
|
324
|
-
|
|
325
|
-
/**
|
|
326
|
-
* Recursively escapes string properties on an object in-place.
|
|
327
|
-
* @param {Object} obj
|
|
328
|
-
*/
|
|
329
|
-
static mutateSanitized(obj) {
|
|
330
|
-
for (const key in obj) {
|
|
331
|
-
if (typeof obj[key] === "string") {
|
|
332
|
-
obj[key] = escapeXss(obj[key]);
|
|
333
|
-
} else if (typeof obj[key] === "object" && obj[key] !== null) {
|
|
334
|
-
Validator.mutateSanitized(obj[key]);
|
|
335
|
-
}
|
|
336
|
-
}
|
|
337
|
-
}
|
|
338
|
-
|
|
339
|
-
/**
|
|
340
|
-
* Recursively creates a sanitized copy of a string, array, or object.
|
|
341
|
-
* @param {*} obj
|
|
342
|
-
* @returns {*}
|
|
343
|
-
*/
|
|
344
|
-
static sanitizeObject(obj) {
|
|
345
|
-
if (typeof obj === "string") return escapeXss(obj);
|
|
346
|
-
|
|
347
|
-
if (Array.isArray(obj)) {
|
|
348
|
-
return obj.map((item) => Validator.sanitizeObject(item));
|
|
349
|
-
}
|
|
350
|
-
|
|
351
|
-
if (typeof obj === "object" && obj !== null) {
|
|
352
|
-
const sanitized = {};
|
|
353
|
-
for (const key in obj) {
|
|
354
|
-
sanitized[key] = Validator.sanitizeObject(obj[key]);
|
|
355
|
-
}
|
|
356
|
-
return sanitized;
|
|
357
|
-
}
|
|
358
|
-
|
|
359
|
-
return obj;
|
|
360
|
-
}
|
|
361
|
-
}
|
|
362
|
-
|
|
363
|
-
export { Validator };
|
|
364
|
-
export default Validator;
|
|
1
|
+
/**
|
|
2
|
+
* Escapes HTML special characters to prevent XSS in string field values.
|
|
3
|
+
* @param {string} value
|
|
4
|
+
* @returns {string}
|
|
5
|
+
*/
|
|
6
|
+
function escapeXss(value) {
|
|
7
|
+
return String(value)
|
|
8
|
+
.replace(/&/g, "&")
|
|
9
|
+
.replace(/</g, "<")
|
|
10
|
+
.replace(/>/g, ">")
|
|
11
|
+
.replace(/"/g, """)
|
|
12
|
+
.replace(/'/g, "'")
|
|
13
|
+
.replace(/\//g, "/");
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
const messages_default = {
|
|
17
|
+
es: {
|
|
18
|
+
required: (f) => `El campo ${f} es obligatorio`,
|
|
19
|
+
min: (f, n) => `El campo ${f} debe tener al menos ${n} caracteres`,
|
|
20
|
+
max: (f, n) => `El campo ${f} no puede tener más de ${n} caracteres`,
|
|
21
|
+
email: (f) => `El campo ${f} debe ser un email válido`,
|
|
22
|
+
number: (f) => `El campo ${f} debe ser numérico`,
|
|
23
|
+
alpha: (f) => `El campo ${f} solo puede contener letras`,
|
|
24
|
+
alphanumeric: (f) => `El campo ${f} solo puede contener letras y números`,
|
|
25
|
+
boolean: (f) => `El campo ${f} debe ser verdadero o falso`,
|
|
26
|
+
date: (f) => `El campo ${f} debe ser una fecha válida`,
|
|
27
|
+
url: (f) => `El campo ${f} debe ser una URL válida`,
|
|
28
|
+
in: (f, v) => `El campo ${f} debe ser uno de: ${v.join(", ")}`,
|
|
29
|
+
equals: (f, v) => `El campo ${f} debe ser igual a ${v}`,
|
|
30
|
+
password: () => `La contraseña debe tener mayúsculas, minúsculas y números`,
|
|
31
|
+
pattern: (f) => `El campo ${f} no cumple el patrón requerido`,
|
|
32
|
+
},
|
|
33
|
+
en: {
|
|
34
|
+
required: (f) => `${f} is required`,
|
|
35
|
+
min: (f, n) => `${f} must be at least ${n} characters`,
|
|
36
|
+
max: (f, n) => `${f} must be at most ${n} characters`,
|
|
37
|
+
email: (f) => `${f} must be a valid email`,
|
|
38
|
+
number: (f) => `${f} must be numeric`,
|
|
39
|
+
alpha: (f) => `${f} must contain only letters`,
|
|
40
|
+
alphanumeric: (f) => `${f} must contain only letters and numbers`,
|
|
41
|
+
boolean: (f) => `${f} must be true or false`,
|
|
42
|
+
date: (f) => `${f} must be a valid date`,
|
|
43
|
+
url: (f) => `${f} must be a valid URL`,
|
|
44
|
+
in: (f, v) => `${f} must be one of: ${v.join(", ")}`,
|
|
45
|
+
equals: (f, v) => `${f} must equal ${v}`,
|
|
46
|
+
password: () => `Password must contain uppercase, lowercase and numbers`,
|
|
47
|
+
pattern: (f) => `${f} does not match the required pattern`,
|
|
48
|
+
},
|
|
49
|
+
pt: {
|
|
50
|
+
required: (f) => `O campo ${f} é obrigatório`,
|
|
51
|
+
min: (f, n) => `O campo ${f} deve ter pelo menos ${n} caracteres`,
|
|
52
|
+
max: (f, n) => `O campo ${f} não pode ter mais de ${n} caracteres`,
|
|
53
|
+
email: (f) => `O campo ${f} deve ser um email válido`,
|
|
54
|
+
number: (f) => `O campo ${f} deve ser numérico`,
|
|
55
|
+
alpha: (f) => `O campo ${f} só pode conter letras`,
|
|
56
|
+
alphanumeric: (f) => `O campo ${f} só pode conter letras e números`,
|
|
57
|
+
boolean: (f) => `O campo ${f} deve ser verdadeiro ou falso`,
|
|
58
|
+
date: (f) => `O campo ${f} deve ser uma data válida`,
|
|
59
|
+
url: (f) => `O campo ${f} deve ser uma URL válida`,
|
|
60
|
+
in: (f, v) => `O campo ${f} deve ser um de: ${v.join(", ")}`,
|
|
61
|
+
equals: (f, v) => `O campo ${f} deve ser igual a ${v}`,
|
|
62
|
+
password: () => `A senha deve conter maiúsculas, minúsculas e números`,
|
|
63
|
+
pattern: (f) => `O campo ${f} não corresponde ao padrão exigido`,
|
|
64
|
+
},
|
|
65
|
+
br: {
|
|
66
|
+
required: (f) => `O campo ${f} é obrigatório`,
|
|
67
|
+
min: (f, n) => `O campo ${f} deve ter pelo menos ${n} caracteres`,
|
|
68
|
+
max: (f, n) => `O campo ${f} não pode ter mais de ${n} caracteres`,
|
|
69
|
+
email: (f) => `O campo ${f} deve ser um email válido`,
|
|
70
|
+
number: (f) => `O campo ${f} deve ser numérico`,
|
|
71
|
+
alpha: (f) => `O campo ${f} só pode conter letras`,
|
|
72
|
+
alphanumeric: (f) => `O campo ${f} só pode conter letras e números`,
|
|
73
|
+
boolean: (f) => `O campo ${f} deve ser verdadeiro ou falso`,
|
|
74
|
+
date: (f) => `O campo ${f} deve ser uma data válida`,
|
|
75
|
+
url: (f) => `O campo ${f} deve ser uma URL válida`,
|
|
76
|
+
in: (f, v) => `O campo ${f} deve ser um de: ${v.join(", ")}`,
|
|
77
|
+
equals: (f, v) => `O campo ${f} deve ser igual a ${v}`,
|
|
78
|
+
password: () => `A senha deve conter maiúsculas, minúsculas e números`,
|
|
79
|
+
pattern: (f) => `O campo ${f} não corresponde ao padrão exigido`,
|
|
80
|
+
},
|
|
81
|
+
fr: {
|
|
82
|
+
required: (f) => `Le champ ${f} est obligatoire`,
|
|
83
|
+
min: (f, n) => `Le champ ${f} doit contenir au moins ${n} caractères`,
|
|
84
|
+
max: (f, n) => `Le champ ${f} ne peut pas contenir plus de ${n} caractères`,
|
|
85
|
+
email: (f) => `Le champ ${f} doit être un email valide`,
|
|
86
|
+
number: (f) => `Le champ ${f} doit être numérique`,
|
|
87
|
+
alpha: (f) => `Le champ ${f} ne peut contenir que des lettres`,
|
|
88
|
+
alphanumeric: (f) =>
|
|
89
|
+
`Le champ ${f} ne peut contenir que des lettres et des chiffres`,
|
|
90
|
+
boolean: (f) => `Le champ ${f} doit être vrai ou faux`,
|
|
91
|
+
date: (f) => `Le champ ${f} doit être une date valide`,
|
|
92
|
+
url: (f) => `Le champ ${f} doit être une URL valide`,
|
|
93
|
+
in: (f, v) => `Le champ ${f} doit être l'un de: ${v.join(", ")}`,
|
|
94
|
+
equals: (f, v) => `Le champ ${f} doit être égal à ${v}`,
|
|
95
|
+
password: () =>
|
|
96
|
+
`Le mot de passe doit contenir des majuscules, des minuscules et des chiffres`,
|
|
97
|
+
pattern: (f) => `Le champ ${f} ne correspond pas au modèle requis`,
|
|
98
|
+
},
|
|
99
|
+
};
|
|
100
|
+
|
|
101
|
+
const validators = {
|
|
102
|
+
isEmpty: (value) => value === undefined || value === null || value === "",
|
|
103
|
+
isEmail: (value) => /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(value),
|
|
104
|
+
isNumeric: (value) => !isNaN(value) && !isNaN(parseFloat(value)),
|
|
105
|
+
isAlpha: (value) => /^[a-zA-Z]+$/.test(value),
|
|
106
|
+
isAlphanumeric: (value) => /^[a-zA-Z0-9]+$/.test(value),
|
|
107
|
+
isBoolean: (value) =>
|
|
108
|
+
value === true || value === false || value === "true" || value === "false",
|
|
109
|
+
isISO8601: (value) => !isNaN(Date.parse(value)),
|
|
110
|
+
isURL: (value) => {
|
|
111
|
+
try {
|
|
112
|
+
new URL(value);
|
|
113
|
+
return true;
|
|
114
|
+
} catch {
|
|
115
|
+
return false;
|
|
116
|
+
}
|
|
117
|
+
},
|
|
118
|
+
isLength: (value, { min, max }) => {
|
|
119
|
+
const len = String(value).length;
|
|
120
|
+
if (min !== undefined && len < min) return false;
|
|
121
|
+
if (max !== undefined && len > max) return false;
|
|
122
|
+
return true;
|
|
123
|
+
},
|
|
124
|
+
isIn: (value, values) => values.includes(value),
|
|
125
|
+
equals: (value, comparison) => value === comparison,
|
|
126
|
+
matches: (value, pattern) => {
|
|
127
|
+
if (pattern instanceof RegExp) {
|
|
128
|
+
pattern.lastIndex = 0;
|
|
129
|
+
return pattern.test(String(value));
|
|
130
|
+
}
|
|
131
|
+
return new RegExp(pattern).test(String(value));
|
|
132
|
+
},
|
|
133
|
+
};
|
|
134
|
+
|
|
135
|
+
/**
|
|
136
|
+
* Comprehensive Validator class for handling multi-language data validation.
|
|
137
|
+
*/
|
|
138
|
+
class Validator {
|
|
139
|
+
/**
|
|
140
|
+
* Initializes the Validator instance with a schema and optional language settings.
|
|
141
|
+
* @param {Object} schema - Validation rules for each field (e.g., { email: { required: true, email: true } }).
|
|
142
|
+
* @param {string} [lang_default=null] - Default language for error messages (e.g., "en", "es").
|
|
143
|
+
* @param {Object} [messages=null] - Custom message overrides for validation rules.
|
|
144
|
+
* @example
|
|
145
|
+
* const loginSchema = {
|
|
146
|
+
* email: { required: true, email: true },
|
|
147
|
+
* password: { required: true, min: 6 }
|
|
148
|
+
* };
|
|
149
|
+
* const loginValidator = new Validator(loginSchema, 'en');
|
|
150
|
+
*/
|
|
151
|
+
constructor(schema, lang_default = null, messages = null) {
|
|
152
|
+
this.schema = schema || {};
|
|
153
|
+
this.lang_default = lang_default;
|
|
154
|
+
this.messages = messages ? messages : messages_default;
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
/**
|
|
158
|
+
* Validates the request body or plain data object against the defined schema.
|
|
159
|
+
* @param {import('express').Request|Object} req - Express request object or plain data dictionary.
|
|
160
|
+
* @returns {Promise<{success: boolean, error: boolean, errors: Array<{field: string, message: string}>, message: Array<string>, html: Array<string>}>}
|
|
161
|
+
*/
|
|
162
|
+
async validate(req) {
|
|
163
|
+
const isExpressReq = req && typeof req === "object" && ("body" in req || "headers" in req || "query" in req);
|
|
164
|
+
let lang = this.lang_default;
|
|
165
|
+
if (!lang && isExpressReq) {
|
|
166
|
+
lang =
|
|
167
|
+
req.query?.lang ||
|
|
168
|
+
req.body?.lang ||
|
|
169
|
+
req.params?.lang ||
|
|
170
|
+
req.cookies?.lang ||
|
|
171
|
+
req.headers?.["accept-language"]?.split(",")[0]?.split("-")[0] ||
|
|
172
|
+
req.session?.lang;
|
|
173
|
+
}
|
|
174
|
+
lang = lang || "en";
|
|
175
|
+
|
|
176
|
+
const msg = this.messages[lang] || this.messages.en || this.messages.es;
|
|
177
|
+
const errors = [];
|
|
178
|
+
const messages = [];
|
|
179
|
+
const body = isExpressReq ? (req.body || {}) : (req || {});
|
|
180
|
+
|
|
181
|
+
for (const [field, config] of Object.entries(this.schema)) {
|
|
182
|
+
let value = body[field];
|
|
183
|
+
|
|
184
|
+
if (config.xss === true && typeof value === "string") {
|
|
185
|
+
body[field] = escapeXss(value);
|
|
186
|
+
value = body[field];
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
if (config.required && validators.isEmpty(value)) {
|
|
190
|
+
const errorMsg = config.messages?.required || msg.required(field);
|
|
191
|
+
messages.push(errorMsg);
|
|
192
|
+
errors.push({ field, message: errorMsg });
|
|
193
|
+
continue;
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
if (!validators.isEmpty(value)) {
|
|
197
|
+
if (
|
|
198
|
+
config.min !== undefined &&
|
|
199
|
+
!validators.isLength(value, { min: config.min })
|
|
200
|
+
) {
|
|
201
|
+
const errorMsg = config.messages?.min || msg.min(field, config.min);
|
|
202
|
+
messages.push(errorMsg);
|
|
203
|
+
errors.push({ field, message: errorMsg });
|
|
204
|
+
}
|
|
205
|
+
if (
|
|
206
|
+
config.max !== undefined &&
|
|
207
|
+
!validators.isLength(value, { max: config.max })
|
|
208
|
+
) {
|
|
209
|
+
const errorMsg = config.messages?.max || msg.max(field, config.max);
|
|
210
|
+
messages.push(errorMsg);
|
|
211
|
+
errors.push({ field, message: errorMsg });
|
|
212
|
+
}
|
|
213
|
+
if (config.email && !validators.isEmail(value)) {
|
|
214
|
+
const errorMsg = config.messages?.email || msg.email(field);
|
|
215
|
+
messages.push(errorMsg);
|
|
216
|
+
errors.push({ field, message: errorMsg });
|
|
217
|
+
}
|
|
218
|
+
if (config.number && !validators.isNumeric(value)) {
|
|
219
|
+
const errorMsg = config.messages?.number || msg.number(field);
|
|
220
|
+
messages.push(errorMsg);
|
|
221
|
+
errors.push({ field, message: errorMsg });
|
|
222
|
+
}
|
|
223
|
+
if (config.alpha && !validators.isAlpha(value)) {
|
|
224
|
+
const errorMsg = config.messages?.alpha || msg.alpha(field);
|
|
225
|
+
messages.push(errorMsg);
|
|
226
|
+
errors.push({ field, message: errorMsg });
|
|
227
|
+
}
|
|
228
|
+
if (config.alphanumeric && !validators.isAlphanumeric(value)) {
|
|
229
|
+
const errorMsg = config.messages?.alphanumeric || msg.alphanumeric(field);
|
|
230
|
+
messages.push(errorMsg);
|
|
231
|
+
errors.push({ field, message: errorMsg });
|
|
232
|
+
}
|
|
233
|
+
if (config.boolean && !validators.isBoolean(value)) {
|
|
234
|
+
const errorMsg = config.messages?.boolean || msg.boolean(field);
|
|
235
|
+
messages.push(errorMsg);
|
|
236
|
+
errors.push({ field, message: errorMsg });
|
|
237
|
+
}
|
|
238
|
+
if (config.date && !validators.isISO8601(value)) {
|
|
239
|
+
const errorMsg = config.messages?.date || msg.date(field);
|
|
240
|
+
messages.push(errorMsg);
|
|
241
|
+
errors.push({ field, message: errorMsg });
|
|
242
|
+
}
|
|
243
|
+
if (config.url && !validators.isURL(value)) {
|
|
244
|
+
const errorMsg = config.messages?.url || msg.url(field);
|
|
245
|
+
messages.push(errorMsg);
|
|
246
|
+
errors.push({ field, message: errorMsg });
|
|
247
|
+
}
|
|
248
|
+
if (config.in && !validators.isIn(value, config.in)) {
|
|
249
|
+
const errorMsg = config.messages?.in || msg.in(field, config.in);
|
|
250
|
+
messages.push(errorMsg);
|
|
251
|
+
errors.push({ field, message: errorMsg });
|
|
252
|
+
}
|
|
253
|
+
if (
|
|
254
|
+
config.equals !== undefined &&
|
|
255
|
+
!validators.equals(value, config.equals)
|
|
256
|
+
) {
|
|
257
|
+
const errorMsg = config.messages?.equals || msg.equals(field, config.equals);
|
|
258
|
+
messages.push(errorMsg);
|
|
259
|
+
errors.push({ field, message: errorMsg });
|
|
260
|
+
}
|
|
261
|
+
if (
|
|
262
|
+
config.password &&
|
|
263
|
+
!validators.matches(value, /^(?=.*[A-Z])(?=.*[a-z])(?=.*\d).{6,}$/)
|
|
264
|
+
) {
|
|
265
|
+
const errorMsg = config.messages?.password || msg.password(field);
|
|
266
|
+
messages.push(errorMsg);
|
|
267
|
+
errors.push({ field, message: errorMsg });
|
|
268
|
+
}
|
|
269
|
+
if (config.pattern && !validators.matches(value, config.pattern)) {
|
|
270
|
+
const errorMsg = config.messages?.pattern || msg.pattern(field);
|
|
271
|
+
messages.push(errorMsg);
|
|
272
|
+
errors.push({ field, message: errorMsg });
|
|
273
|
+
}
|
|
274
|
+
}
|
|
275
|
+
}
|
|
276
|
+
|
|
277
|
+
if (errors.length > 0) {
|
|
278
|
+
return {
|
|
279
|
+
success: false,
|
|
280
|
+
error: true,
|
|
281
|
+
errors: errors,
|
|
282
|
+
message: messages,
|
|
283
|
+
html: [],
|
|
284
|
+
};
|
|
285
|
+
}
|
|
286
|
+
|
|
287
|
+
return { success: true, error: false, errors: [], message: [], html: [] };
|
|
288
|
+
}
|
|
289
|
+
|
|
290
|
+
/**
|
|
291
|
+
* Express middleware for automated validation of the request body.
|
|
292
|
+
* Returns a 400 Bad Request response with validation results if errors occur.
|
|
293
|
+
* @returns {Function} Express middleware function (req, res, next).
|
|
294
|
+
*/
|
|
295
|
+
middleware() {
|
|
296
|
+
return async (req, res, next) => {
|
|
297
|
+
const result = await this.validate(req);
|
|
298
|
+
if (!result.success) {
|
|
299
|
+
return res.status(400).json(result);
|
|
300
|
+
}
|
|
301
|
+
next();
|
|
302
|
+
};
|
|
303
|
+
}
|
|
304
|
+
|
|
305
|
+
/**
|
|
306
|
+
* Express middleware for explicitly sanitizing request data against XSS.
|
|
307
|
+
* Can be used on specific routes where HTML input is not expected.
|
|
308
|
+
* @returns {Function} Express middleware function.
|
|
309
|
+
*/
|
|
310
|
+
static xssMiddleware() {
|
|
311
|
+
return (req, res, next) => {
|
|
312
|
+
if (req.body && typeof req.body === "object") {
|
|
313
|
+
Validator.mutateSanitized(req.body);
|
|
314
|
+
}
|
|
315
|
+
if (req.query && typeof req.query === "object") {
|
|
316
|
+
Validator.mutateSanitized(req.query);
|
|
317
|
+
}
|
|
318
|
+
if (req.params && typeof req.params === "object") {
|
|
319
|
+
Validator.mutateSanitized(req.params);
|
|
320
|
+
}
|
|
321
|
+
next();
|
|
322
|
+
};
|
|
323
|
+
}
|
|
324
|
+
|
|
325
|
+
/**
|
|
326
|
+
* Recursively escapes string properties on an object in-place.
|
|
327
|
+
* @param {Object} obj
|
|
328
|
+
*/
|
|
329
|
+
static mutateSanitized(obj) {
|
|
330
|
+
for (const key in obj) {
|
|
331
|
+
if (typeof obj[key] === "string") {
|
|
332
|
+
obj[key] = escapeXss(obj[key]);
|
|
333
|
+
} else if (typeof obj[key] === "object" && obj[key] !== null) {
|
|
334
|
+
Validator.mutateSanitized(obj[key]);
|
|
335
|
+
}
|
|
336
|
+
}
|
|
337
|
+
}
|
|
338
|
+
|
|
339
|
+
/**
|
|
340
|
+
* Recursively creates a sanitized copy of a string, array, or object.
|
|
341
|
+
* @param {*} obj
|
|
342
|
+
* @returns {*}
|
|
343
|
+
*/
|
|
344
|
+
static sanitizeObject(obj) {
|
|
345
|
+
if (typeof obj === "string") return escapeXss(obj);
|
|
346
|
+
|
|
347
|
+
if (Array.isArray(obj)) {
|
|
348
|
+
return obj.map((item) => Validator.sanitizeObject(item));
|
|
349
|
+
}
|
|
350
|
+
|
|
351
|
+
if (typeof obj === "object" && obj !== null) {
|
|
352
|
+
const sanitized = {};
|
|
353
|
+
for (const key in obj) {
|
|
354
|
+
sanitized[key] = Validator.sanitizeObject(obj[key]);
|
|
355
|
+
}
|
|
356
|
+
return sanitized;
|
|
357
|
+
}
|
|
358
|
+
|
|
359
|
+
return obj;
|
|
360
|
+
}
|
|
361
|
+
}
|
|
362
|
+
|
|
363
|
+
export { Validator };
|
|
364
|
+
export default Validator;
|