nextjs-secure 0.2.0 → 0.5.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.
@@ -0,0 +1,1964 @@
1
+ // src/middleware/validation/utils.ts
2
+ function isZodSchema(schema) {
3
+ return typeof schema === "object" && schema !== null && "safeParse" in schema && typeof schema.safeParse === "function";
4
+ }
5
+ function isCustomSchema(schema) {
6
+ if (typeof schema !== "object" || schema === null) return false;
7
+ if ("safeParse" in schema) return false;
8
+ const entries = Object.entries(schema);
9
+ if (entries.length === 0) return false;
10
+ return entries.every(([_, rule]) => {
11
+ return typeof rule === "object" && rule !== null && "type" in rule;
12
+ });
13
+ }
14
+ var EMAIL_PATTERN = /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/;
15
+ var URL_PATTERN = /^https?:\/\/(?:(?:www\.)?[-a-zA-Z0-9@:%._+~#=]{1,256}\.[a-zA-Z0-9()]{1,6}|localhost|(?:\d{1,3}\.){3}\d{1,3})(?::\d{1,5})?(?:[-a-zA-Z0-9()@:%_+.~#?&/=]*)$/;
16
+ var UUID_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
17
+ var DATE_PATTERN = /^\d{4}-\d{2}-\d{2}(?:T\d{2}:\d{2}:\d{2}(?:\.\d{3})?(?:Z|[+-]\d{2}:?\d{2})?)?$/;
18
+ function validateField(value, rule, fieldName) {
19
+ if (value === void 0 || value === null || value === "") {
20
+ if (rule.required) {
21
+ return {
22
+ field: fieldName,
23
+ code: "required",
24
+ message: rule.message || `${fieldName} is required`,
25
+ received: value
26
+ };
27
+ }
28
+ return null;
29
+ }
30
+ switch (rule.type) {
31
+ case "string":
32
+ if (typeof value !== "string") {
33
+ return {
34
+ field: fieldName,
35
+ code: "invalid_type",
36
+ message: rule.message || `${fieldName} must be a string`,
37
+ expected: "string",
38
+ received: typeof value
39
+ };
40
+ }
41
+ if (rule.minLength !== void 0 && value.length < rule.minLength) {
42
+ return {
43
+ field: fieldName,
44
+ code: "too_short",
45
+ message: rule.message || `${fieldName} must be at least ${rule.minLength} characters`,
46
+ received: value.length
47
+ };
48
+ }
49
+ if (rule.maxLength !== void 0 && value.length > rule.maxLength) {
50
+ return {
51
+ field: fieldName,
52
+ code: "too_long",
53
+ message: rule.message || `${fieldName} must be at most ${rule.maxLength} characters`,
54
+ received: value.length
55
+ };
56
+ }
57
+ if (rule.pattern && !rule.pattern.test(value)) {
58
+ return {
59
+ field: fieldName,
60
+ code: "invalid_pattern",
61
+ message: rule.message || `${fieldName} has invalid format`,
62
+ received: value
63
+ };
64
+ }
65
+ break;
66
+ case "number":
67
+ const num = typeof value === "number" ? value : Number(value);
68
+ if (isNaN(num)) {
69
+ return {
70
+ field: fieldName,
71
+ code: "invalid_type",
72
+ message: rule.message || `${fieldName} must be a number`,
73
+ expected: "number",
74
+ received: typeof value
75
+ };
76
+ }
77
+ if (rule.integer && !Number.isInteger(num)) {
78
+ return {
79
+ field: fieldName,
80
+ code: "invalid_integer",
81
+ message: rule.message || `${fieldName} must be an integer`,
82
+ received: num
83
+ };
84
+ }
85
+ if (rule.min !== void 0 && num < rule.min) {
86
+ return {
87
+ field: fieldName,
88
+ code: "too_small",
89
+ message: rule.message || `${fieldName} must be at least ${rule.min}`,
90
+ received: num
91
+ };
92
+ }
93
+ if (rule.max !== void 0 && num > rule.max) {
94
+ return {
95
+ field: fieldName,
96
+ code: "too_large",
97
+ message: rule.message || `${fieldName} must be at most ${rule.max}`,
98
+ received: num
99
+ };
100
+ }
101
+ break;
102
+ case "boolean":
103
+ if (typeof value !== "boolean" && value !== "true" && value !== "false") {
104
+ return {
105
+ field: fieldName,
106
+ code: "invalid_type",
107
+ message: rule.message || `${fieldName} must be a boolean`,
108
+ expected: "boolean",
109
+ received: typeof value
110
+ };
111
+ }
112
+ break;
113
+ case "email":
114
+ if (typeof value !== "string" || !EMAIL_PATTERN.test(value)) {
115
+ return {
116
+ field: fieldName,
117
+ code: "invalid_email",
118
+ message: rule.message || `${fieldName} must be a valid email address`,
119
+ received: value
120
+ };
121
+ }
122
+ break;
123
+ case "url":
124
+ if (typeof value !== "string" || !URL_PATTERN.test(value)) {
125
+ return {
126
+ field: fieldName,
127
+ code: "invalid_url",
128
+ message: rule.message || `${fieldName} must be a valid URL`,
129
+ received: value
130
+ };
131
+ }
132
+ break;
133
+ case "uuid":
134
+ if (typeof value !== "string" || !UUID_PATTERN.test(value)) {
135
+ return {
136
+ field: fieldName,
137
+ code: "invalid_uuid",
138
+ message: rule.message || `${fieldName} must be a valid UUID`,
139
+ received: value
140
+ };
141
+ }
142
+ break;
143
+ case "date":
144
+ if (typeof value !== "string" || !DATE_PATTERN.test(value)) {
145
+ const parsed = new Date(value);
146
+ if (isNaN(parsed.getTime())) {
147
+ return {
148
+ field: fieldName,
149
+ code: "invalid_date",
150
+ message: rule.message || `${fieldName} must be a valid date`,
151
+ received: value
152
+ };
153
+ }
154
+ }
155
+ break;
156
+ case "array":
157
+ if (!Array.isArray(value)) {
158
+ return {
159
+ field: fieldName,
160
+ code: "invalid_type",
161
+ message: rule.message || `${fieldName} must be an array`,
162
+ expected: "array",
163
+ received: typeof value
164
+ };
165
+ }
166
+ if (rule.minItems !== void 0 && value.length < rule.minItems) {
167
+ return {
168
+ field: fieldName,
169
+ code: "too_few_items",
170
+ message: rule.message || `${fieldName} must have at least ${rule.minItems} items`,
171
+ received: value.length
172
+ };
173
+ }
174
+ if (rule.maxItems !== void 0 && value.length > rule.maxItems) {
175
+ return {
176
+ field: fieldName,
177
+ code: "too_many_items",
178
+ message: rule.message || `${fieldName} must have at most ${rule.maxItems} items`,
179
+ received: value.length
180
+ };
181
+ }
182
+ if (rule.items) {
183
+ for (let i = 0; i < value.length; i++) {
184
+ const itemError = validateField(value[i], rule.items, `${fieldName}[${i}]`);
185
+ if (itemError) return itemError;
186
+ }
187
+ }
188
+ break;
189
+ case "object":
190
+ if (typeof value !== "object" || value === null || Array.isArray(value)) {
191
+ return {
192
+ field: fieldName,
193
+ code: "invalid_type",
194
+ message: rule.message || `${fieldName} must be an object`,
195
+ expected: "object",
196
+ received: Array.isArray(value) ? "array" : typeof value
197
+ };
198
+ }
199
+ break;
200
+ }
201
+ if (rule.custom) {
202
+ const result = rule.custom(value);
203
+ if (result !== true) {
204
+ return {
205
+ field: fieldName,
206
+ code: "custom_validation",
207
+ message: typeof result === "string" ? result : rule.message || `${fieldName} failed validation`,
208
+ received: value
209
+ };
210
+ }
211
+ }
212
+ return null;
213
+ }
214
+ function validateCustomSchema(data, schema) {
215
+ if (typeof data !== "object" || data === null) {
216
+ return {
217
+ success: false,
218
+ errors: [{
219
+ field: "_root",
220
+ code: "invalid_type",
221
+ message: "Expected an object",
222
+ received: data
223
+ }]
224
+ };
225
+ }
226
+ const errors = [];
227
+ const record = data;
228
+ for (const [fieldName, rule] of Object.entries(schema)) {
229
+ const error = validateField(record[fieldName], rule, fieldName);
230
+ if (error) {
231
+ errors.push(error);
232
+ }
233
+ }
234
+ if (errors.length > 0) {
235
+ return { success: false, errors };
236
+ }
237
+ return { success: true, data };
238
+ }
239
+ function validateZodSchema(data, schema) {
240
+ const result = schema.safeParse(data);
241
+ if (result.success) {
242
+ return { success: true, data: result.data };
243
+ }
244
+ const errors = result.error.issues.map((issue) => ({
245
+ field: issue.path.join(".") || "_root",
246
+ code: issue.code,
247
+ message: issue.message,
248
+ path: issue.path.map(String)
249
+ }));
250
+ return { success: false, errors };
251
+ }
252
+ function getByPath(obj, path) {
253
+ if (typeof obj !== "object" || obj === null) return void 0;
254
+ const parts = path.split(".");
255
+ let current = obj;
256
+ for (const part of parts) {
257
+ if (typeof current !== "object" || current === null) return void 0;
258
+ current = current[part];
259
+ }
260
+ return current;
261
+ }
262
+ function setByPath(obj, path, value) {
263
+ const parts = path.split(".");
264
+ let current = obj;
265
+ for (let i = 0; i < parts.length - 1; i++) {
266
+ const part = parts[i];
267
+ if (!(part in current) || typeof current[part] !== "object") {
268
+ current[part] = {};
269
+ }
270
+ current = current[part];
271
+ }
272
+ current[parts[parts.length - 1]] = value;
273
+ }
274
+ function walkObject(obj, fn, path = "") {
275
+ if (typeof obj === "string") {
276
+ return fn(obj, path);
277
+ }
278
+ if (Array.isArray(obj)) {
279
+ return obj.map((item, i) => walkObject(item, fn, `${path}[${i}]`));
280
+ }
281
+ if (typeof obj === "object" && obj !== null) {
282
+ const result = {};
283
+ for (const [key, value] of Object.entries(obj)) {
284
+ const newPath = path ? `${path}.${key}` : key;
285
+ result[key] = walkObject(value, fn, newPath);
286
+ }
287
+ return result;
288
+ }
289
+ return obj;
290
+ }
291
+ function parseQueryString(url) {
292
+ const result = {};
293
+ try {
294
+ const urlObj = new URL(url);
295
+ for (const [key, value] of urlObj.searchParams.entries()) {
296
+ if (key in result) {
297
+ const existing = result[key];
298
+ if (Array.isArray(existing)) {
299
+ existing.push(value);
300
+ } else {
301
+ result[key] = [existing, value];
302
+ }
303
+ } else {
304
+ result[key] = value;
305
+ }
306
+ }
307
+ } catch {
308
+ }
309
+ return result;
310
+ }
311
+
312
+ // src/middleware/validation/validators/schema.ts
313
+ function validate(data, schema) {
314
+ if (isZodSchema(schema)) {
315
+ return validateZodSchema(data, schema);
316
+ }
317
+ if (isCustomSchema(schema)) {
318
+ return validateCustomSchema(data, schema);
319
+ }
320
+ return {
321
+ success: false,
322
+ errors: [{
323
+ field: "_schema",
324
+ code: "invalid_schema",
325
+ message: "Invalid schema provided"
326
+ }]
327
+ };
328
+ }
329
+ async function validateBody(request, schema) {
330
+ let body;
331
+ try {
332
+ const contentType = request.headers.get("content-type") || "";
333
+ if (contentType.includes("application/json")) {
334
+ body = await request.json();
335
+ } else if (contentType.includes("application/x-www-form-urlencoded")) {
336
+ const text = await request.text();
337
+ body = Object.fromEntries(new URLSearchParams(text));
338
+ } else if (contentType.includes("multipart/form-data")) {
339
+ const formData = await request.formData();
340
+ const obj = {};
341
+ formData.forEach((value, key) => {
342
+ if (typeof value === "string") {
343
+ obj[key] = value;
344
+ }
345
+ });
346
+ body = obj;
347
+ } else {
348
+ try {
349
+ body = await request.json();
350
+ } catch {
351
+ body = {};
352
+ }
353
+ }
354
+ } catch (error) {
355
+ return {
356
+ success: false,
357
+ errors: [{
358
+ field: "_body",
359
+ code: "parse_error",
360
+ message: "Failed to parse request body"
361
+ }]
362
+ };
363
+ }
364
+ return validate(body, schema);
365
+ }
366
+ function validateQuery(request, schema) {
367
+ const query = parseQueryString(request.url);
368
+ return validate(query, schema);
369
+ }
370
+ function validateParams(params, schema) {
371
+ return validate(params, schema);
372
+ }
373
+ async function validateRequest(request, config) {
374
+ const allErrors = [];
375
+ const data = {};
376
+ if (config.body) {
377
+ const bodyResult = await validateBody(request, config.body);
378
+ if (!bodyResult.success) {
379
+ allErrors.push(...(bodyResult.errors || []).map((e) => ({
380
+ ...e,
381
+ field: `body.${e.field}`.replace("body._root", "body")
382
+ })));
383
+ } else {
384
+ data.body = bodyResult.data;
385
+ }
386
+ } else {
387
+ data.body = {};
388
+ }
389
+ if (config.query) {
390
+ const queryResult = validateQuery(request, config.query);
391
+ if (!queryResult.success) {
392
+ allErrors.push(...(queryResult.errors || []).map((e) => ({
393
+ ...e,
394
+ field: `query.${e.field}`.replace("query._root", "query")
395
+ })));
396
+ } else {
397
+ data.query = queryResult.data;
398
+ }
399
+ } else {
400
+ data.query = {};
401
+ }
402
+ if (config.params && config.routeParams) {
403
+ const paramsResult = validateParams(config.routeParams, config.params);
404
+ if (!paramsResult.success) {
405
+ allErrors.push(...(paramsResult.errors || []).map((e) => ({
406
+ ...e,
407
+ field: `params.${e.field}`.replace("params._root", "params")
408
+ })));
409
+ } else {
410
+ data.params = paramsResult.data;
411
+ }
412
+ } else {
413
+ data.params = {};
414
+ }
415
+ if (allErrors.length > 0) {
416
+ return { success: false, errors: allErrors };
417
+ }
418
+ return {
419
+ success: true,
420
+ data
421
+ };
422
+ }
423
+ function defaultValidationErrorResponse(errors) {
424
+ return new Response(
425
+ JSON.stringify({
426
+ error: "validation_error",
427
+ message: "Request validation failed",
428
+ details: errors.map((e) => ({
429
+ field: e.field,
430
+ code: e.code,
431
+ message: e.message
432
+ }))
433
+ }),
434
+ {
435
+ status: 400,
436
+ headers: { "Content-Type": "application/json" }
437
+ }
438
+ );
439
+ }
440
+ function createValidator(schema) {
441
+ return (data) => validate(data, schema);
442
+ }
443
+ function allValid(...results) {
444
+ return results.every((r) => r.success);
445
+ }
446
+ function mergeErrors(...results) {
447
+ const errors = [];
448
+ for (const result of results) {
449
+ if (result.errors) {
450
+ errors.push(...result.errors);
451
+ }
452
+ }
453
+ return errors;
454
+ }
455
+
456
+ // src/middleware/validation/validators/content-type.ts
457
+ var MIME_TYPES = {
458
+ // Text
459
+ TEXT_PLAIN: "text/plain",
460
+ TEXT_HTML: "text/html",
461
+ TEXT_CSS: "text/css",
462
+ TEXT_JAVASCRIPT: "text/javascript",
463
+ // Application
464
+ JSON: "application/json",
465
+ FORM_URLENCODED: "application/x-www-form-urlencoded",
466
+ MULTIPART_FORM: "multipart/form-data",
467
+ XML: "application/xml",
468
+ PDF: "application/pdf",
469
+ ZIP: "application/zip",
470
+ GZIP: "application/gzip",
471
+ OCTET_STREAM: "application/octet-stream",
472
+ // Image
473
+ IMAGE_PNG: "image/png",
474
+ IMAGE_JPEG: "image/jpeg",
475
+ IMAGE_GIF: "image/gif",
476
+ IMAGE_WEBP: "image/webp",
477
+ IMAGE_SVG: "image/svg+xml",
478
+ // Audio
479
+ AUDIO_MP3: "audio/mpeg",
480
+ AUDIO_WAV: "audio/wav",
481
+ AUDIO_OGG: "audio/ogg",
482
+ // Video
483
+ VIDEO_MP4: "video/mp4",
484
+ VIDEO_WEBM: "video/webm"
485
+ };
486
+ function parseContentType(header) {
487
+ if (!header) {
488
+ return {
489
+ type: "",
490
+ subtype: "",
491
+ mediaType: "",
492
+ parameters: {}
493
+ };
494
+ }
495
+ const parts = header.split(";").map((p) => p.trim());
496
+ const mediaType = parts[0].toLowerCase();
497
+ const [type = "", subtype = ""] = mediaType.split("/");
498
+ const parameters = {};
499
+ for (let i = 1; i < parts.length; i++) {
500
+ const [key, value] = parts[i].split("=").map((p) => p.trim());
501
+ if (key && value) {
502
+ parameters[key.toLowerCase()] = value.replace(/^["']|["']$/g, "");
503
+ }
504
+ }
505
+ return {
506
+ type,
507
+ subtype,
508
+ mediaType,
509
+ charset: parameters["charset"],
510
+ boundary: parameters["boundary"],
511
+ parameters
512
+ };
513
+ }
514
+ function isAllowedContentType(contentType, allowedTypes, strict = false) {
515
+ if (!contentType) {
516
+ return !strict;
517
+ }
518
+ const { mediaType } = parseContentType(contentType);
519
+ return allowedTypes.some((allowed) => {
520
+ const normalizedAllowed = allowed.toLowerCase().trim();
521
+ if (mediaType === normalizedAllowed) {
522
+ return true;
523
+ }
524
+ if (normalizedAllowed.endsWith("/*")) {
525
+ const prefix = normalizedAllowed.slice(0, -2);
526
+ return mediaType.startsWith(prefix + "/");
527
+ }
528
+ if (!normalizedAllowed.includes("/")) {
529
+ const { type } = parseContentType(contentType);
530
+ return type === normalizedAllowed;
531
+ }
532
+ return false;
533
+ });
534
+ }
535
+ function validateContentType(request, config) {
536
+ const contentType = request.headers.get("content-type");
537
+ const { allowed, strict = false, charset } = config;
538
+ if (strict && !contentType) {
539
+ return {
540
+ valid: false,
541
+ contentType: null,
542
+ reason: "Content-Type header is required"
543
+ };
544
+ }
545
+ if (contentType && !isAllowedContentType(contentType, allowed, strict)) {
546
+ return {
547
+ valid: false,
548
+ contentType,
549
+ reason: `Content-Type '${contentType}' is not allowed`
550
+ };
551
+ }
552
+ if (charset && contentType) {
553
+ const parsed = parseContentType(contentType);
554
+ if (parsed.charset && parsed.charset.toLowerCase() !== charset.toLowerCase()) {
555
+ return {
556
+ valid: false,
557
+ contentType,
558
+ reason: `Charset '${parsed.charset}' is not allowed, expected '${charset}'`
559
+ };
560
+ }
561
+ }
562
+ return { valid: true, contentType };
563
+ }
564
+ function defaultContentTypeErrorResponse(contentType, reason) {
565
+ return new Response(
566
+ JSON.stringify({
567
+ error: "invalid_content_type",
568
+ message: reason,
569
+ received: contentType
570
+ }),
571
+ {
572
+ status: 415,
573
+ // Unsupported Media Type
574
+ headers: { "Content-Type": "application/json" }
575
+ }
576
+ );
577
+ }
578
+ function isJsonRequest(request) {
579
+ return isAllowedContentType(
580
+ request.headers.get("content-type"),
581
+ [MIME_TYPES.JSON]
582
+ );
583
+ }
584
+ function isFormRequest(request) {
585
+ return isAllowedContentType(
586
+ request.headers.get("content-type"),
587
+ [MIME_TYPES.FORM_URLENCODED, MIME_TYPES.MULTIPART_FORM]
588
+ );
589
+ }
590
+ function isMultipartRequest(request) {
591
+ return isAllowedContentType(
592
+ request.headers.get("content-type"),
593
+ [MIME_TYPES.MULTIPART_FORM]
594
+ );
595
+ }
596
+ function getMultipartBoundary(request) {
597
+ const contentType = request.headers.get("content-type");
598
+ if (!contentType) return null;
599
+ const { boundary } = parseContentType(contentType);
600
+ return boundary || null;
601
+ }
602
+
603
+ // src/middleware/validation/sanitizers/path.ts
604
+ var DANGEROUS_PATTERNS = [
605
+ // Unix path traversal
606
+ /\.\.\//g,
607
+ /\.\./g,
608
+ // Windows path traversal
609
+ /\.\.\\/g,
610
+ // Null byte (can truncate paths in some systems)
611
+ /%00/g,
612
+ /\0/g,
613
+ // URL encoded traversal
614
+ /%2e%2e%2f/gi,
615
+ // ../
616
+ /%2e%2e\//gi,
617
+ // ../
618
+ /%2e%2e%5c/gi,
619
+ // ..\
620
+ /%2e%2e\\/gi,
621
+ // ..\
622
+ // Double URL encoding
623
+ /%252e%252e%252f/gi,
624
+ /%252e%252e%255c/gi,
625
+ // Unicode encoding
626
+ /\.%u002e\//gi,
627
+ /%u002e%u002e%u002f/gi,
628
+ // Overlong UTF-8 encoding
629
+ /%c0%ae%c0%ae%c0%af/gi,
630
+ /%c1%9c/gi
631
+ // Backslash variant
632
+ ];
633
+ var DEFAULT_BLOCKED_EXTENSIONS = [
634
+ ".exe",
635
+ ".dll",
636
+ ".so",
637
+ ".dylib",
638
+ // Executables
639
+ ".sh",
640
+ ".bash",
641
+ ".bat",
642
+ ".cmd",
643
+ ".ps1",
644
+ // Scripts
645
+ ".php",
646
+ ".asp",
647
+ ".aspx",
648
+ ".jsp",
649
+ ".cgi",
650
+ // Server scripts
651
+ ".htaccess",
652
+ ".htpasswd",
653
+ // Apache config
654
+ ".env",
655
+ ".git",
656
+ ".svn"
657
+ // Config/VCS
658
+ ];
659
+ function normalizePathSeparators(path) {
660
+ return path.replace(/\\/g, "/");
661
+ }
662
+ function decodePathComponent(path) {
663
+ let result = path;
664
+ let previous = "";
665
+ while (result !== previous) {
666
+ previous = result;
667
+ try {
668
+ result = decodeURIComponent(result);
669
+ } catch {
670
+ break;
671
+ }
672
+ }
673
+ return result;
674
+ }
675
+ function hasPathTraversal(path) {
676
+ if (!path || typeof path !== "string") return false;
677
+ const normalized = normalizePathSeparators(decodePathComponent(path));
678
+ for (const pattern of DANGEROUS_PATTERNS) {
679
+ pattern.lastIndex = 0;
680
+ if (pattern.test(normalized)) {
681
+ return true;
682
+ }
683
+ }
684
+ if (normalized.includes("..")) {
685
+ return true;
686
+ }
687
+ return false;
688
+ }
689
+ function validatePath(path, config = {}) {
690
+ if (!path || typeof path !== "string") {
691
+ return { valid: false, reason: "Path is empty or not a string" };
692
+ }
693
+ const {
694
+ allowAbsolute = false,
695
+ allowedPrefixes = [],
696
+ allowedExtensions,
697
+ blockedExtensions = DEFAULT_BLOCKED_EXTENSIONS,
698
+ maxDepth = 10,
699
+ maxLength = 255,
700
+ normalize = true
701
+ } = config;
702
+ if (path.length > maxLength) {
703
+ return { valid: false, reason: `Path exceeds maximum length of ${maxLength}` };
704
+ }
705
+ let normalized = decodePathComponent(path);
706
+ if (normalize) {
707
+ normalized = normalizePathSeparators(normalized);
708
+ }
709
+ if (normalized.includes("\0") || path.includes("%00")) {
710
+ return { valid: false, reason: "Path contains null bytes" };
711
+ }
712
+ if (hasPathTraversal(path)) {
713
+ return { valid: false, reason: "Path contains traversal sequences" };
714
+ }
715
+ const isAbsolute = normalized.startsWith("/") || /^[a-zA-Z]:/.test(normalized) || // Windows drive letter
716
+ normalized.startsWith("\\\\");
717
+ if (isAbsolute && !allowAbsolute) {
718
+ return { valid: false, reason: "Absolute paths are not allowed" };
719
+ }
720
+ if (allowedPrefixes.length > 0) {
721
+ const hasValidPrefix = allowedPrefixes.some((prefix) => {
722
+ const normalizedPrefix = normalizePathSeparators(prefix);
723
+ return normalized.startsWith(normalizedPrefix);
724
+ });
725
+ if (!hasValidPrefix) {
726
+ return { valid: false, reason: "Path does not start with an allowed prefix" };
727
+ }
728
+ }
729
+ const segments = normalized.split("/").filter((s) => s && s !== ".");
730
+ if (segments.length > maxDepth) {
731
+ return { valid: false, reason: `Path depth exceeds maximum of ${maxDepth}` };
732
+ }
733
+ const lastSegment = segments[segments.length - 1] || "";
734
+ const dotIndex = lastSegment.lastIndexOf(".");
735
+ const extension = dotIndex > 0 ? lastSegment.slice(dotIndex).toLowerCase() : "";
736
+ if (extension && blockedExtensions.length > 0) {
737
+ if (blockedExtensions.map((e) => e.toLowerCase()).includes(extension)) {
738
+ return { valid: false, reason: `Extension ${extension} is not allowed` };
739
+ }
740
+ }
741
+ if (extension && allowedExtensions && allowedExtensions.length > 0) {
742
+ if (!allowedExtensions.map((e) => e.toLowerCase()).includes(extension)) {
743
+ return { valid: false, reason: `Extension ${extension} is not in allowed list` };
744
+ }
745
+ }
746
+ const sanitized = normalized.replace(/\/+/g, "/");
747
+ return { valid: true, sanitized };
748
+ }
749
+ function sanitizePath(path, config = {}) {
750
+ if (!path || typeof path !== "string") return "";
751
+ const { normalize = true, maxLength = 255 } = config;
752
+ let result = decodePathComponent(path);
753
+ if (normalize) {
754
+ result = normalizePathSeparators(result);
755
+ }
756
+ result = result.replace(/\0/g, "").replace(/%00/g, "");
757
+ result = result.replace(/\.\.\//g, "").replace(/\.\.\\/g, "");
758
+ if (!config.allowAbsolute) {
759
+ result = result.replace(/^\/+/, "");
760
+ result = result.replace(/^[a-zA-Z]:/, "");
761
+ result = result.replace(/^\\\\/, "");
762
+ }
763
+ result = result.replace(/\/+/g, "/");
764
+ result = result.replace(/\/+$/, "");
765
+ if (result.length > maxLength) {
766
+ result = result.slice(0, maxLength);
767
+ }
768
+ return result;
769
+ }
770
+ function isPathContained(path, baseDir) {
771
+ if (!path || !baseDir) return false;
772
+ const normalizedPath = normalizePathSeparators(decodePathComponent(path));
773
+ const normalizedBase = normalizePathSeparators(baseDir);
774
+ const resolvedPath = resolvePath(normalizedPath, normalizedBase);
775
+ return resolvedPath.startsWith(normalizedBase.replace(/\/$/, "") + "/");
776
+ }
777
+ function resolvePath(path, base) {
778
+ let combined;
779
+ if (path.startsWith("/")) {
780
+ combined = path;
781
+ } else {
782
+ combined = `${base.replace(/\/$/, "")}/${path}`;
783
+ }
784
+ const segments = [];
785
+ for (const segment of combined.split("/")) {
786
+ if (segment === "" || segment === ".") {
787
+ continue;
788
+ }
789
+ if (segment === "..") {
790
+ segments.pop();
791
+ } else {
792
+ segments.push(segment);
793
+ }
794
+ }
795
+ return "/" + segments.join("/");
796
+ }
797
+ function getExtension(path) {
798
+ if (!path || typeof path !== "string") return "";
799
+ const normalized = normalizePathSeparators(path);
800
+ const segments = normalized.split("/");
801
+ const filename = segments[segments.length - 1] || "";
802
+ const dotIndex = filename.lastIndexOf(".");
803
+ if (dotIndex <= 0) return "";
804
+ return filename.slice(dotIndex).toLowerCase();
805
+ }
806
+ function getFilename(path) {
807
+ if (!path || typeof path !== "string") return "";
808
+ const normalized = normalizePathSeparators(path);
809
+ const segments = normalized.split("/");
810
+ return segments[segments.length - 1] || "";
811
+ }
812
+ function sanitizeFilename(filename) {
813
+ if (typeof filename !== "string") return "file";
814
+ if (!filename) return "file";
815
+ let result = filename;
816
+ result = result.replace(/[/\\]/g, "");
817
+ result = result.replace(/\0/g, "");
818
+ result = result.replace(/[\x00-\x1f\x7f]/g, "");
819
+ result = result.replace(/[<>:"|?*]/g, "");
820
+ result = result.replace(/^[.\s]+|[.\s]+$/g, "");
821
+ if (result.length > 255) {
822
+ const ext = getExtension(result);
823
+ const name = result.slice(0, 255 - ext.length);
824
+ result = name + ext;
825
+ }
826
+ return result || "file";
827
+ }
828
+ function isHiddenPath(path) {
829
+ if (!path) return false;
830
+ const normalized = normalizePathSeparators(path);
831
+ const segments = normalized.split("/").filter(Boolean);
832
+ return segments.some((segment) => segment.startsWith("."));
833
+ }
834
+
835
+ // src/middleware/validation/validators/file.ts
836
+ var MAGIC_NUMBERS = [
837
+ // Images
838
+ { type: "image/jpeg", extension: ".jpg", signature: [255, 216, 255] },
839
+ { type: "image/png", extension: ".png", signature: [137, 80, 78, 71, 13, 10, 26, 10] },
840
+ { type: "image/gif", extension: ".gif", signature: [71, 73, 70, 56] },
841
+ // GIF87a or GIF89a
842
+ { type: "image/webp", extension: ".webp", signature: [82, 73, 70, 70], offset: 0 },
843
+ // RIFF
844
+ { type: "image/bmp", extension: ".bmp", signature: [66, 77] },
845
+ { type: "image/tiff", extension: ".tiff", signature: [73, 73, 42, 0] },
846
+ // Little endian
847
+ { type: "image/tiff", extension: ".tiff", signature: [77, 77, 0, 42] },
848
+ // Big endian
849
+ { type: "image/x-icon", extension: ".ico", signature: [0, 0, 1, 0] },
850
+ { type: "image/svg+xml", extension: ".svg", signature: [60, 63, 120, 109, 108] },
851
+ // <?xml
852
+ // Documents
853
+ { type: "application/pdf", extension: ".pdf", signature: [37, 80, 68, 70] },
854
+ // %PDF
855
+ { type: "application/zip", extension: ".zip", signature: [80, 75, 3, 4] },
856
+ // PK
857
+ { type: "application/gzip", extension: ".gz", signature: [31, 139] },
858
+ { type: "application/x-rar-compressed", extension: ".rar", signature: [82, 97, 114, 33] },
859
+ { type: "application/x-7z-compressed", extension: ".7z", signature: [55, 122, 188, 175, 39, 28] },
860
+ // Microsoft Office (new format - zip based)
861
+ { type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", extension: ".xlsx", signature: [80, 75, 3, 4] },
862
+ { type: "application/vnd.openxmlformats-officedocument.wordprocessingml.document", extension: ".docx", signature: [80, 75, 3, 4] },
863
+ { type: "application/vnd.openxmlformats-officedocument.presentationml.presentation", extension: ".pptx", signature: [80, 75, 3, 4] },
864
+ // Microsoft Office (old format)
865
+ { type: "application/msword", extension: ".doc", signature: [208, 207, 17, 224, 161, 177, 26, 225] },
866
+ { type: "application/vnd.ms-excel", extension: ".xls", signature: [208, 207, 17, 224, 161, 177, 26, 225] },
867
+ // Audio
868
+ { type: "audio/mpeg", extension: ".mp3", signature: [255, 251] },
869
+ // MP3 frame sync
870
+ { type: "audio/mpeg", extension: ".mp3", signature: [73, 68, 51] },
871
+ // ID3
872
+ { type: "audio/wav", extension: ".wav", signature: [82, 73, 70, 70] },
873
+ // RIFF
874
+ { type: "audio/ogg", extension: ".ogg", signature: [79, 103, 103, 83] },
875
+ { type: "audio/flac", extension: ".flac", signature: [102, 76, 97, 67] },
876
+ // Video
877
+ { type: "video/mp4", extension: ".mp4", signature: [0, 0, 0], offset: 0 },
878
+ // Partial match
879
+ { type: "video/webm", extension: ".webm", signature: [26, 69, 223, 163] },
880
+ { type: "video/avi", extension: ".avi", signature: [82, 73, 70, 70] },
881
+ // RIFF
882
+ { type: "video/quicktime", extension: ".mov", signature: [0, 0, 0, 20, 102, 116, 121, 112] },
883
+ // Web
884
+ { type: "application/wasm", extension: ".wasm", signature: [0, 97, 115, 109] },
885
+ // \0asm
886
+ // Fonts
887
+ { type: "font/woff", extension: ".woff", signature: [119, 79, 70, 70] },
888
+ { type: "font/woff2", extension: ".woff2", signature: [119, 79, 70, 50] }
889
+ ];
890
+ var DEFAULT_MAX_FILE_SIZE = 10 * 1024 * 1024;
891
+ var DEFAULT_MAX_FILES = 10;
892
+ var DANGEROUS_EXTENSIONS = [
893
+ ".exe",
894
+ ".dll",
895
+ ".so",
896
+ ".dylib",
897
+ ".bin",
898
+ ".sh",
899
+ ".bash",
900
+ ".bat",
901
+ ".cmd",
902
+ ".ps1",
903
+ ".vbs",
904
+ ".php",
905
+ ".asp",
906
+ ".aspx",
907
+ ".jsp",
908
+ ".cgi",
909
+ ".pl",
910
+ ".py",
911
+ ".rb",
912
+ ".jar",
913
+ ".class",
914
+ ".msi",
915
+ ".dmg",
916
+ ".pkg",
917
+ ".deb",
918
+ ".rpm",
919
+ ".scr",
920
+ ".pif",
921
+ ".com",
922
+ ".hta"
923
+ ];
924
+ function checkMagicNumber(bytes, magicNumber) {
925
+ const offset = magicNumber.offset || 0;
926
+ const signature = magicNumber.signature;
927
+ if (bytes.length < offset + signature.length) {
928
+ return false;
929
+ }
930
+ for (let i = 0; i < signature.length; i++) {
931
+ if (bytes[offset + i] !== signature[i]) {
932
+ return false;
933
+ }
934
+ }
935
+ return true;
936
+ }
937
+ function detectFileType(bytes) {
938
+ for (const magic of MAGIC_NUMBERS) {
939
+ if (checkMagicNumber(bytes, magic)) {
940
+ return { type: magic.type, extension: magic.extension };
941
+ }
942
+ }
943
+ return null;
944
+ }
945
+ async function validateFile(file, config = {}) {
946
+ const {
947
+ maxSize = DEFAULT_MAX_FILE_SIZE,
948
+ minSize = 0,
949
+ allowedTypes = [],
950
+ blockedTypes = [],
951
+ allowedExtensions = [],
952
+ blockedExtensions = DANGEROUS_EXTENSIONS,
953
+ validateMagicNumbers = true,
954
+ sanitizeFilename: doSanitize = true
955
+ } = config;
956
+ const errors = [];
957
+ const extension = getExtension(file.name);
958
+ const info = {
959
+ filename: doSanitize ? sanitizeFilename(file.name) : file.name,
960
+ size: file.size,
961
+ type: file.type,
962
+ extension
963
+ };
964
+ if (file.size > maxSize) {
965
+ errors.push({
966
+ filename: file.name,
967
+ code: "size_exceeded",
968
+ message: `File size (${formatBytes(file.size)}) exceeds maximum allowed (${formatBytes(maxSize)})`,
969
+ details: { size: file.size, maxSize }
970
+ });
971
+ }
972
+ if (file.size < minSize) {
973
+ errors.push({
974
+ filename: file.name,
975
+ code: "size_too_small",
976
+ message: `File size (${formatBytes(file.size)}) is below minimum required (${formatBytes(minSize)})`,
977
+ details: { size: file.size, minSize }
978
+ });
979
+ }
980
+ if (blockedExtensions.length > 0 && extension) {
981
+ if (blockedExtensions.map((e) => e.toLowerCase()).includes(extension.toLowerCase())) {
982
+ errors.push({
983
+ filename: file.name,
984
+ code: "extension_not_allowed",
985
+ message: `File extension '${extension}' is not allowed`,
986
+ details: { extension, blockedExtensions }
987
+ });
988
+ }
989
+ }
990
+ if (allowedExtensions.length > 0 && extension) {
991
+ if (!allowedExtensions.map((e) => e.toLowerCase()).includes(extension.toLowerCase())) {
992
+ errors.push({
993
+ filename: file.name,
994
+ code: "extension_not_allowed",
995
+ message: `File extension '${extension}' is not in allowed list`,
996
+ details: { extension, allowedExtensions }
997
+ });
998
+ }
999
+ }
1000
+ if (blockedTypes.length > 0 && file.type) {
1001
+ if (blockedTypes.includes(file.type)) {
1002
+ errors.push({
1003
+ filename: file.name,
1004
+ code: "type_not_allowed",
1005
+ message: `File type '${file.type}' is not allowed`,
1006
+ details: { type: file.type, blockedTypes }
1007
+ });
1008
+ }
1009
+ }
1010
+ if (allowedTypes.length > 0) {
1011
+ if (!allowedTypes.includes(file.type)) {
1012
+ errors.push({
1013
+ filename: file.name,
1014
+ code: "type_not_allowed",
1015
+ message: `File type '${file.type}' is not in allowed list`,
1016
+ details: { type: file.type, allowedTypes }
1017
+ });
1018
+ }
1019
+ }
1020
+ if (validateMagicNumbers && errors.length === 0) {
1021
+ try {
1022
+ const buffer = await file.arrayBuffer();
1023
+ const bytes = new Uint8Array(buffer.slice(0, 32));
1024
+ const detected = detectFileType(bytes);
1025
+ if (detected) {
1026
+ if (file.type && detected.type !== file.type) {
1027
+ const isSimilar = detected.type.startsWith("image/") && file.type.startsWith("image/") || detected.type.startsWith("audio/") && file.type.startsWith("audio/") || detected.type.startsWith("video/") && file.type.startsWith("video/");
1028
+ if (!isSimilar) {
1029
+ errors.push({
1030
+ filename: file.name,
1031
+ code: "invalid_content",
1032
+ message: `File content doesn't match declared type (claimed: ${file.type}, detected: ${detected.type})`,
1033
+ details: { claimed: file.type, detected: detected.type }
1034
+ });
1035
+ }
1036
+ }
1037
+ }
1038
+ } catch {
1039
+ }
1040
+ }
1041
+ return {
1042
+ valid: errors.length === 0,
1043
+ info,
1044
+ errors
1045
+ };
1046
+ }
1047
+ async function validateFiles(files, config = {}) {
1048
+ const { maxFiles = DEFAULT_MAX_FILES } = config;
1049
+ const allErrors = [];
1050
+ const infos = [];
1051
+ if (files.length > maxFiles) {
1052
+ allErrors.push({
1053
+ filename: "",
1054
+ code: "too_many_files",
1055
+ message: `Too many files (${files.length}), maximum allowed is ${maxFiles}`,
1056
+ details: { count: files.length, maxFiles }
1057
+ });
1058
+ }
1059
+ for (const file of files) {
1060
+ const result = await validateFile(file, config);
1061
+ infos.push(result.info);
1062
+ allErrors.push(...result.errors);
1063
+ }
1064
+ return {
1065
+ valid: allErrors.length === 0,
1066
+ infos,
1067
+ errors: allErrors
1068
+ };
1069
+ }
1070
+ function extractFilesFromFormData(formData) {
1071
+ const files = /* @__PURE__ */ new Map();
1072
+ formData.forEach((value, key) => {
1073
+ if (value instanceof File) {
1074
+ const existing = files.get(key) || [];
1075
+ existing.push(value);
1076
+ files.set(key, existing);
1077
+ }
1078
+ });
1079
+ return files;
1080
+ }
1081
+ async function validateFilesFromRequest(request, config = {}) {
1082
+ const contentType = request.headers.get("content-type") || "";
1083
+ if (!contentType.includes("multipart/form-data")) {
1084
+ return { valid: true, files: /* @__PURE__ */ new Map(), errors: [] };
1085
+ }
1086
+ try {
1087
+ const formData = await request.formData();
1088
+ const fileMap = extractFilesFromFormData(formData);
1089
+ const allInfos = /* @__PURE__ */ new Map();
1090
+ const allErrors = [];
1091
+ let totalFileCount = 0;
1092
+ for (const [field, files] of fileMap.entries()) {
1093
+ totalFileCount += files.length;
1094
+ const result = await validateFiles(files, { ...config, maxFiles: Infinity });
1095
+ allInfos.set(field, result.infos);
1096
+ allErrors.push(...result.errors.map((e) => ({ ...e, field })));
1097
+ }
1098
+ const maxFiles = config.maxFiles ?? DEFAULT_MAX_FILES;
1099
+ if (totalFileCount > maxFiles) {
1100
+ allErrors.push({
1101
+ filename: "",
1102
+ code: "too_many_files",
1103
+ message: `Total file count (${totalFileCount}) exceeds maximum (${maxFiles})`,
1104
+ details: { count: totalFileCount, maxFiles }
1105
+ });
1106
+ }
1107
+ return {
1108
+ valid: allErrors.length === 0,
1109
+ files: allInfos,
1110
+ errors: allErrors
1111
+ };
1112
+ } catch {
1113
+ return {
1114
+ valid: false,
1115
+ files: /* @__PURE__ */ new Map(),
1116
+ errors: [{
1117
+ filename: "",
1118
+ code: "invalid_content",
1119
+ message: "Failed to parse multipart form data"
1120
+ }]
1121
+ };
1122
+ }
1123
+ }
1124
+ function defaultFileErrorResponse(errors) {
1125
+ return new Response(
1126
+ JSON.stringify({
1127
+ error: "file_validation_error",
1128
+ message: "File validation failed",
1129
+ details: errors.map((e) => ({
1130
+ filename: e.filename,
1131
+ field: e.field,
1132
+ code: e.code,
1133
+ message: e.message
1134
+ }))
1135
+ }),
1136
+ {
1137
+ status: 400,
1138
+ headers: { "Content-Type": "application/json" }
1139
+ }
1140
+ );
1141
+ }
1142
+ function formatBytes(bytes) {
1143
+ if (bytes === 0) return "0 B";
1144
+ const units = ["B", "KB", "MB", "GB"];
1145
+ const k = 1024;
1146
+ const i = Math.floor(Math.log(bytes) / Math.log(k));
1147
+ return `${parseFloat((bytes / Math.pow(k, i)).toFixed(2))} ${units[i]}`;
1148
+ }
1149
+
1150
+ // src/middleware/validation/sanitizers/xss.ts
1151
+ var DEFAULT_ALLOWED_TAGS = [
1152
+ "a",
1153
+ "abbr",
1154
+ "b",
1155
+ "blockquote",
1156
+ "br",
1157
+ "code",
1158
+ "del",
1159
+ "em",
1160
+ "h1",
1161
+ "h2",
1162
+ "h3",
1163
+ "h4",
1164
+ "h5",
1165
+ "h6",
1166
+ "hr",
1167
+ "i",
1168
+ "ins",
1169
+ "li",
1170
+ "mark",
1171
+ "ol",
1172
+ "p",
1173
+ "pre",
1174
+ "q",
1175
+ "s",
1176
+ "small",
1177
+ "span",
1178
+ "strong",
1179
+ "sub",
1180
+ "sup",
1181
+ "u",
1182
+ "ul"
1183
+ ];
1184
+ var DEFAULT_ALLOWED_ATTRIBUTES = {
1185
+ a: ["href", "title", "target", "rel"],
1186
+ img: ["src", "alt", "title", "width", "height"],
1187
+ abbr: ["title"],
1188
+ q: ["cite"],
1189
+ blockquote: ["cite"]
1190
+ };
1191
+ var DEFAULT_SAFE_PROTOCOLS = ["http:", "https:", "mailto:", "tel:"];
1192
+ var DANGEROUS_PATTERNS2 = [
1193
+ // Event handlers
1194
+ /\bon\w+\s*=/gi,
1195
+ // JavaScript protocol
1196
+ /javascript\s*:/gi,
1197
+ // VBScript protocol
1198
+ /vbscript\s*:/gi,
1199
+ // Data URI with scripts
1200
+ /data\s*:[^,]*(?:text\/html|application\/javascript|text\/javascript)/gi,
1201
+ // Expression in CSS
1202
+ /expression\s*\(/gi,
1203
+ // Binding in CSS (Firefox)
1204
+ /-moz-binding\s*:/gi,
1205
+ // Behavior in CSS (IE)
1206
+ /behavior\s*:/gi,
1207
+ // Import in CSS
1208
+ /@import/gi,
1209
+ // Script tags
1210
+ /<\s*script/gi,
1211
+ // Style tags with expressions
1212
+ /<\s*style[^>]*>[^<]*expression/gi,
1213
+ // SVG with scripts
1214
+ /<\s*svg[^>]*onload/gi,
1215
+ // Object/embed/applet tags
1216
+ /<\s*(object|embed|applet)/gi,
1217
+ // Base tag (can redirect resources)
1218
+ /<\s*base/gi,
1219
+ // Meta refresh
1220
+ /<\s*meta[^>]*http-equiv\s*=\s*["']?refresh/gi,
1221
+ // Form action hijacking
1222
+ /<\s*form[^>]*action\s*=\s*["']?javascript/gi,
1223
+ // Link tag with import
1224
+ /<\s*link[^>]*rel\s*=\s*["']?import/gi
1225
+ ];
1226
+ var HTML_ENTITIES = {
1227
+ "&": "&amp;",
1228
+ "<": "&lt;",
1229
+ ">": "&gt;",
1230
+ '"': "&quot;",
1231
+ "'": "&#x27;",
1232
+ "/": "&#x2F;",
1233
+ "`": "&#x60;",
1234
+ "=": "&#x3D;"
1235
+ };
1236
+ function escapeHtml(str) {
1237
+ return str.replace(/[&<>"'`=/]/g, (char) => HTML_ENTITIES[char] || char);
1238
+ }
1239
+ function unescapeHtml(str) {
1240
+ const entityMap = {
1241
+ "&amp;": "&",
1242
+ "&lt;": "<",
1243
+ "&gt;": ">",
1244
+ "&quot;": '"',
1245
+ "&#x27;": "'",
1246
+ "&#x2F;": "/",
1247
+ "&#x60;": "`",
1248
+ "&#x3D;": "=",
1249
+ "&#39;": "'",
1250
+ "&#47;": "/"
1251
+ };
1252
+ return str.replace(/&(?:amp|lt|gt|quot|#x27|#x2F|#x60|#x3D|#39|#47);/gi, (entity) => {
1253
+ return entityMap[entity.toLowerCase()] || entity;
1254
+ });
1255
+ }
1256
+ function stripHtml(str) {
1257
+ let result = str.replace(/<script[^>]*>[\s\S]*?<\/script>/gi, "");
1258
+ result = result.replace(/<style[^>]*>[\s\S]*?<\/style>/gi, "");
1259
+ result = result.replace(/<[^>]*>/g, "");
1260
+ result = unescapeHtml(result);
1261
+ result = result.replace(/\0/g, "");
1262
+ return result.trim();
1263
+ }
1264
+ function isSafeUrl(url, allowedProtocols = DEFAULT_SAFE_PROTOCOLS) {
1265
+ if (!url) return true;
1266
+ const trimmed = url.trim().toLowerCase();
1267
+ if (trimmed.startsWith("javascript:")) return false;
1268
+ if (trimmed.startsWith("vbscript:")) return false;
1269
+ if (trimmed.startsWith("data:image/")) return true;
1270
+ if (trimmed.startsWith("data:")) return false;
1271
+ try {
1272
+ const parsed = new URL(url, "https://example.com");
1273
+ if (parsed.protocol && !allowedProtocols.includes(parsed.protocol)) {
1274
+ if (!url.includes(":")) return true;
1275
+ return false;
1276
+ }
1277
+ } catch {
1278
+ return true;
1279
+ }
1280
+ return true;
1281
+ }
1282
+ function sanitizeHtml(str, allowedTags = DEFAULT_ALLOWED_TAGS, allowedAttributes = DEFAULT_ALLOWED_ATTRIBUTES, allowedProtocols = DEFAULT_SAFE_PROTOCOLS) {
1283
+ let result = str.replace(/\0/g, "");
1284
+ result = result.replace(/<script[^>]*>[\s\S]*?<\/script>/gi, "");
1285
+ result = result.replace(/<style[^>]*>[\s\S]*?<\/style>/gi, "");
1286
+ result = result.replace(/<!--[\s\S]*?-->/g, "");
1287
+ result = result.replace(/<\/?([a-z][a-z0-9]*)\b([^>]*)>/gi, (match, tagName, attributes) => {
1288
+ const lowerTag = tagName.toLowerCase();
1289
+ const isClosing = match.startsWith("</");
1290
+ if (!allowedTags.includes(lowerTag)) {
1291
+ return "";
1292
+ }
1293
+ if (isClosing) {
1294
+ return `</${lowerTag}>`;
1295
+ }
1296
+ const allowedAttrs = allowedAttributes[lowerTag] || [];
1297
+ const safeAttrs = [];
1298
+ const attrRegex = /([a-z][a-z0-9-]*)\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s>]*))/gi;
1299
+ let attrMatch;
1300
+ while ((attrMatch = attrRegex.exec(attributes)) !== null) {
1301
+ const attrName = attrMatch[1].toLowerCase();
1302
+ const attrValue = attrMatch[2] || attrMatch[3] || attrMatch[4] || "";
1303
+ if (!allowedAttrs.includes(attrName)) continue;
1304
+ if (DANGEROUS_PATTERNS2.some((pattern) => pattern.test(attrValue))) continue;
1305
+ if (["href", "src", "action", "formaction"].includes(attrName)) {
1306
+ if (!isSafeUrl(attrValue, allowedProtocols)) continue;
1307
+ }
1308
+ const safeValue = escapeHtml(attrValue);
1309
+ safeAttrs.push(`${attrName}="${safeValue}"`);
1310
+ }
1311
+ const attrStr = safeAttrs.length > 0 ? " " + safeAttrs.join(" ") : "";
1312
+ return `<${lowerTag}${attrStr}>`;
1313
+ });
1314
+ for (const pattern of DANGEROUS_PATTERNS2) {
1315
+ result = result.replace(pattern, "");
1316
+ }
1317
+ return result;
1318
+ }
1319
+ function detectXSS(str) {
1320
+ if (!str || typeof str !== "string") return false;
1321
+ const normalized = str.replace(/\\x([0-9a-f]{2})/gi, (_, hex) => String.fromCharCode(parseInt(hex, 16))).replace(/\\u([0-9a-f]{4})/gi, (_, hex) => String.fromCharCode(parseInt(hex, 16))).replace(/&#x([0-9a-f]+);?/gi, (_, hex) => String.fromCharCode(parseInt(hex, 16))).replace(/&#(\d+);?/gi, (_, dec) => String.fromCharCode(parseInt(dec, 10)));
1322
+ for (const pattern of DANGEROUS_PATTERNS2) {
1323
+ pattern.lastIndex = 0;
1324
+ if (pattern.test(normalized)) {
1325
+ return true;
1326
+ }
1327
+ }
1328
+ return false;
1329
+ }
1330
+ function sanitize(input, config = {}) {
1331
+ if (!input || typeof input !== "string") return "";
1332
+ const {
1333
+ mode = "escape",
1334
+ allowedTags = DEFAULT_ALLOWED_TAGS,
1335
+ allowedAttributes = DEFAULT_ALLOWED_ATTRIBUTES,
1336
+ allowedProtocols = DEFAULT_SAFE_PROTOCOLS,
1337
+ maxLength,
1338
+ stripNull = true
1339
+ } = config;
1340
+ let result = input;
1341
+ if (stripNull) {
1342
+ result = result.replace(/\0/g, "");
1343
+ }
1344
+ switch (mode) {
1345
+ case "escape":
1346
+ result = escapeHtml(result);
1347
+ break;
1348
+ case "strip":
1349
+ result = stripHtml(result);
1350
+ break;
1351
+ case "allow-safe":
1352
+ result = sanitizeHtml(result, allowedTags, allowedAttributes, allowedProtocols);
1353
+ break;
1354
+ }
1355
+ if (maxLength !== void 0 && result.length > maxLength) {
1356
+ result = result.slice(0, maxLength);
1357
+ }
1358
+ return result;
1359
+ }
1360
+ function sanitizeObject(obj, config = {}) {
1361
+ if (typeof obj === "string") {
1362
+ return sanitize(obj, config);
1363
+ }
1364
+ if (Array.isArray(obj)) {
1365
+ return obj.map((item) => sanitizeObject(item, config));
1366
+ }
1367
+ if (typeof obj === "object" && obj !== null) {
1368
+ const result = {};
1369
+ for (const [key, value] of Object.entries(obj)) {
1370
+ result[key] = sanitizeObject(value, config);
1371
+ }
1372
+ return result;
1373
+ }
1374
+ return obj;
1375
+ }
1376
+ function sanitizeFields(obj, fields, config = {}) {
1377
+ const result = { ...obj };
1378
+ for (const field of fields) {
1379
+ if (field in result && typeof result[field] === "string") {
1380
+ result[field] = sanitize(result[field], config);
1381
+ }
1382
+ }
1383
+ return result;
1384
+ }
1385
+
1386
+ // src/middleware/validation/sanitizers/sql.ts
1387
+ var SQL_PATTERNS = [
1388
+ // High severity - Definite attacks
1389
+ {
1390
+ pattern: /'\s*OR\s+'?\d+'?\s*=\s*'?\d+'?/gi,
1391
+ name: "OR '1'='1' attack",
1392
+ severity: "high"
1393
+ },
1394
+ {
1395
+ pattern: /'\s*OR\s+'[^']*'\s*=\s*'[^']*'/gi,
1396
+ name: "OR 'x'='x' attack",
1397
+ severity: "high"
1398
+ },
1399
+ {
1400
+ pattern: /;\s*DROP\s+(TABLE|DATABASE|INDEX|VIEW)/gi,
1401
+ name: "DROP statement",
1402
+ severity: "high"
1403
+ },
1404
+ {
1405
+ pattern: /;\s*DELETE\s+FROM/gi,
1406
+ name: "DELETE statement",
1407
+ severity: "high"
1408
+ },
1409
+ {
1410
+ pattern: /;\s*TRUNCATE\s+/gi,
1411
+ name: "TRUNCATE statement",
1412
+ severity: "high"
1413
+ },
1414
+ {
1415
+ pattern: /;\s*INSERT\s+INTO/gi,
1416
+ name: "INSERT statement",
1417
+ severity: "high"
1418
+ },
1419
+ {
1420
+ pattern: /;\s*UPDATE\s+\w+\s+SET/gi,
1421
+ name: "UPDATE statement",
1422
+ severity: "high"
1423
+ },
1424
+ {
1425
+ pattern: /UNION\s+(ALL\s+)?SELECT/gi,
1426
+ name: "UNION SELECT attack",
1427
+ severity: "high"
1428
+ },
1429
+ {
1430
+ pattern: /EXEC(\s+|\()+(sp_|xp_)/gi,
1431
+ name: "SQL Server stored procedure",
1432
+ severity: "high"
1433
+ },
1434
+ {
1435
+ pattern: /EXECUTE\s+IMMEDIATE/gi,
1436
+ name: "Oracle EXECUTE IMMEDIATE",
1437
+ severity: "high"
1438
+ },
1439
+ {
1440
+ pattern: /INTO\s+(OUT|DUMP)FILE/gi,
1441
+ name: "MySQL file write",
1442
+ severity: "high"
1443
+ },
1444
+ {
1445
+ pattern: /LOAD_FILE\s*\(/gi,
1446
+ name: "MySQL file read",
1447
+ severity: "high"
1448
+ },
1449
+ {
1450
+ pattern: /BENCHMARK\s*\(\s*\d+\s*,/gi,
1451
+ name: "MySQL BENCHMARK DoS",
1452
+ severity: "high"
1453
+ },
1454
+ {
1455
+ pattern: /SLEEP\s*\(\s*\d+\s*\)/gi,
1456
+ name: "SQL SLEEP time-based attack",
1457
+ severity: "high"
1458
+ },
1459
+ {
1460
+ pattern: /WAITFOR\s+DELAY/gi,
1461
+ name: "SQL Server WAITFOR DELAY",
1462
+ severity: "high"
1463
+ },
1464
+ {
1465
+ pattern: /PG_SLEEP\s*\(/gi,
1466
+ name: "PostgreSQL pg_sleep",
1467
+ severity: "high"
1468
+ },
1469
+ // Medium severity - Likely attacks
1470
+ {
1471
+ pattern: /'\s*--/g,
1472
+ name: "SQL comment injection",
1473
+ severity: "medium"
1474
+ },
1475
+ {
1476
+ pattern: /'\s*#/g,
1477
+ name: "MySQL comment injection",
1478
+ severity: "medium"
1479
+ },
1480
+ {
1481
+ pattern: /\/\*[\s\S]*?\*\//g,
1482
+ name: "Block comment",
1483
+ severity: "medium"
1484
+ },
1485
+ {
1486
+ pattern: /'\s*;\s*$/g,
1487
+ name: "Statement terminator",
1488
+ severity: "medium"
1489
+ },
1490
+ {
1491
+ pattern: /HAVING\s+\d+\s*=\s*\d+/gi,
1492
+ name: "HAVING clause injection",
1493
+ severity: "medium"
1494
+ },
1495
+ {
1496
+ pattern: /GROUP\s+BY\s+\d+/gi,
1497
+ name: "GROUP BY injection",
1498
+ severity: "medium"
1499
+ },
1500
+ {
1501
+ pattern: /ORDER\s+BY\s+\d+/gi,
1502
+ name: "ORDER BY injection",
1503
+ severity: "medium"
1504
+ },
1505
+ {
1506
+ pattern: /CONCAT\s*\(/gi,
1507
+ name: "CONCAT function",
1508
+ severity: "medium"
1509
+ },
1510
+ {
1511
+ pattern: /CHAR\s*\(\s*\d+\s*\)/gi,
1512
+ name: "CHAR function bypass",
1513
+ severity: "medium"
1514
+ },
1515
+ {
1516
+ pattern: /0x[0-9a-f]{2,}/gi,
1517
+ name: "Hex encoded value",
1518
+ severity: "medium"
1519
+ },
1520
+ {
1521
+ pattern: /CONVERT\s*\(/gi,
1522
+ name: "CONVERT function",
1523
+ severity: "medium"
1524
+ },
1525
+ {
1526
+ pattern: /CAST\s*\(/gi,
1527
+ name: "CAST function",
1528
+ severity: "medium"
1529
+ },
1530
+ // Low severity - Suspicious but may be false positives
1531
+ {
1532
+ pattern: /'\s*AND\s+'?\d+'?\s*=\s*'?\d+'?/gi,
1533
+ name: "AND '1'='1' pattern",
1534
+ severity: "low"
1535
+ },
1536
+ {
1537
+ pattern: /'\s*AND\s+'[^']*'\s*=\s*'[^']*'/gi,
1538
+ name: "AND 'x'='x' pattern",
1539
+ severity: "low"
1540
+ },
1541
+ {
1542
+ pattern: /SELECT\s+[\w\s,*]+\s+FROM/gi,
1543
+ name: "SELECT statement",
1544
+ severity: "low"
1545
+ },
1546
+ {
1547
+ pattern: /'\s*\+\s*'/g,
1548
+ name: "String concatenation",
1549
+ severity: "low"
1550
+ },
1551
+ {
1552
+ pattern: /'\s*\|\|\s*'/g,
1553
+ name: "Oracle string concatenation",
1554
+ severity: "low"
1555
+ }
1556
+ ];
1557
+ var ENCODED_PATTERNS = [
1558
+ {
1559
+ pattern: /%27\s*%4f%52\s*%27/gi,
1560
+ // URL encoded ' OR '
1561
+ name: "URL encoded OR injection",
1562
+ severity: "high"
1563
+ },
1564
+ {
1565
+ pattern: /%27\s*%2d%2d/gi,
1566
+ // URL encoded ' --
1567
+ name: "URL encoded comment injection",
1568
+ severity: "medium"
1569
+ },
1570
+ {
1571
+ pattern: /\0|%00/g,
1572
+ // Null byte (decoded or encoded)
1573
+ name: "Null byte injection",
1574
+ severity: "high"
1575
+ },
1576
+ {
1577
+ pattern: /\\x27/gi,
1578
+ // Hex escape
1579
+ name: "Hex escaped quote",
1580
+ severity: "medium"
1581
+ },
1582
+ {
1583
+ pattern: /\\u0027/gi,
1584
+ // Unicode escape
1585
+ name: "Unicode escaped quote",
1586
+ severity: "medium"
1587
+ }
1588
+ ];
1589
+ function normalizeInput(input) {
1590
+ let result = input;
1591
+ try {
1592
+ result = decodeURIComponent(result);
1593
+ } catch {
1594
+ }
1595
+ result = result.replace(/&#x([0-9a-f]+);?/gi, (_, hex) => String.fromCharCode(parseInt(hex, 16))).replace(/&#(\d+);?/gi, (_, dec) => String.fromCharCode(parseInt(dec, 10))).replace(/&quot;/gi, '"').replace(/&apos;/gi, "'").replace(/&lt;/gi, "<").replace(/&gt;/gi, ">").replace(/&amp;/gi, "&");
1596
+ result = result.replace(
1597
+ /\\x([0-9a-f]{2})/gi,
1598
+ (_, hex) => String.fromCharCode(parseInt(hex, 16))
1599
+ );
1600
+ result = result.replace(
1601
+ /\\u([0-9a-f]{4})/gi,
1602
+ (_, hex) => String.fromCharCode(parseInt(hex, 16))
1603
+ );
1604
+ return result;
1605
+ }
1606
+ function detectSQLInjection(input, options = {}) {
1607
+ if (!input || typeof input !== "string") return [];
1608
+ const {
1609
+ customPatterns = [],
1610
+ checkEncoded = true,
1611
+ minSeverity = "low"
1612
+ } = options;
1613
+ const severityOrder = { low: 0, medium: 1, high: 2 };
1614
+ const minSeverityLevel = severityOrder[minSeverity];
1615
+ const detections = [];
1616
+ const seenPatterns = /* @__PURE__ */ new Set();
1617
+ const normalizedInput = checkEncoded ? normalizeInput(input) : input;
1618
+ const allPatterns = [
1619
+ ...SQL_PATTERNS,
1620
+ ...checkEncoded ? ENCODED_PATTERNS : [],
1621
+ ...customPatterns.map((p) => ({ pattern: p, name: "Custom pattern", severity: "high" }))
1622
+ ];
1623
+ for (const { pattern, name, severity } of allPatterns) {
1624
+ if (severityOrder[severity] < minSeverityLevel) continue;
1625
+ pattern.lastIndex = 0;
1626
+ const testInput = checkEncoded ? normalizedInput : input;
1627
+ if (pattern.test(testInput)) {
1628
+ const key = `${name}:${severity}`;
1629
+ if (!seenPatterns.has(key)) {
1630
+ seenPatterns.add(key);
1631
+ detections.push({
1632
+ field: "",
1633
+ // Will be set by caller
1634
+ value: input,
1635
+ pattern: name,
1636
+ severity
1637
+ });
1638
+ }
1639
+ }
1640
+ }
1641
+ return detections;
1642
+ }
1643
+ function hasSQLInjection(input, minSeverity = "medium") {
1644
+ return detectSQLInjection(input, { minSeverity }).length > 0;
1645
+ }
1646
+ function sanitizeSQLInput(input) {
1647
+ if (!input || typeof input !== "string") return "";
1648
+ let result = input;
1649
+ result = result.replace(/\0/g, "");
1650
+ result = result.replace(/'/g, "''");
1651
+ result = result.replace(/;/g, "");
1652
+ result = result.replace(/--/g, "");
1653
+ result = result.replace(/\/\*/g, "");
1654
+ result = result.replace(/\*\//g, "");
1655
+ result = result.replace(/0x[0-9a-f]+/gi, "");
1656
+ return result;
1657
+ }
1658
+ function detectSQLInjectionInObject(obj, options = {}) {
1659
+ const { fields, deep = true, customPatterns, minSeverity } = options;
1660
+ const detections = [];
1661
+ function walk(value, path) {
1662
+ if (typeof value === "string") {
1663
+ if (fields && fields.length > 0) {
1664
+ const fieldName = path.split(".").pop() || path;
1665
+ if (!fields.includes(fieldName)) return;
1666
+ }
1667
+ const detected = detectSQLInjection(value, { customPatterns, minSeverity });
1668
+ for (const d of detected) {
1669
+ detections.push({ ...d, field: path });
1670
+ }
1671
+ } else if (deep && Array.isArray(value)) {
1672
+ value.forEach((item, i) => walk(item, `${path}[${i}]`));
1673
+ } else if (deep && typeof value === "object" && value !== null) {
1674
+ for (const [key, val] of Object.entries(value)) {
1675
+ walk(val, path ? `${path}.${key}` : key);
1676
+ }
1677
+ }
1678
+ }
1679
+ walk(obj, "");
1680
+ return detections;
1681
+ }
1682
+ function isAllowedValue(value, allowList) {
1683
+ if (!allowList || allowList.length === 0) return false;
1684
+ return allowList.includes(value);
1685
+ }
1686
+
1687
+ // src/middleware/validation/middleware.ts
1688
+ function withValidation(handler, config) {
1689
+ const onError = config.onError || ((_, errors) => defaultValidationErrorResponse(errors));
1690
+ return async (req) => {
1691
+ const result = await validateRequest(req, {
1692
+ body: config.body,
1693
+ query: config.query,
1694
+ params: config.params,
1695
+ routeParams: config.routeParams
1696
+ });
1697
+ if (!result.success) {
1698
+ return onError(req, result.errors || []);
1699
+ }
1700
+ return handler(req, { validated: result.data });
1701
+ };
1702
+ }
1703
+ function withSanitization(handler, config = {}) {
1704
+ const {
1705
+ fields,
1706
+ mode = "escape",
1707
+ allowedTags,
1708
+ skip,
1709
+ onSanitized
1710
+ } = config;
1711
+ return async (req) => {
1712
+ if (skip && await skip(req)) {
1713
+ return handler(req, { sanitized: null, changes: [] });
1714
+ }
1715
+ let body;
1716
+ try {
1717
+ body = await req.json();
1718
+ } catch {
1719
+ return handler(req, { sanitized: null, changes: [] });
1720
+ }
1721
+ const changes = [];
1722
+ const sanitized = walkObject(body, (value, path) => {
1723
+ if (fields && fields.length > 0) {
1724
+ const fieldName = path.split(".").pop() || path;
1725
+ if (!fields.includes(fieldName)) {
1726
+ return value;
1727
+ }
1728
+ }
1729
+ const cleaned = sanitize(value, { mode, allowedTags });
1730
+ if (cleaned !== value) {
1731
+ changes.push({
1732
+ field: path,
1733
+ original: value,
1734
+ sanitized: cleaned
1735
+ });
1736
+ }
1737
+ return cleaned;
1738
+ }, "");
1739
+ if (onSanitized && changes.length > 0) {
1740
+ onSanitized(req, changes);
1741
+ }
1742
+ return handler(req, { sanitized, changes });
1743
+ };
1744
+ }
1745
+ function withXSSProtection(handler, config = {}) {
1746
+ const { fields, onDetection, checkQuery = true } = config;
1747
+ return async (req) => {
1748
+ const detections = [];
1749
+ if (checkQuery) {
1750
+ const url = new URL(req.url);
1751
+ for (const [key, value] of url.searchParams.entries()) {
1752
+ if (detectXSS(value)) {
1753
+ detections.push({ field: `query.${key}`, value });
1754
+ }
1755
+ }
1756
+ }
1757
+ let body;
1758
+ try {
1759
+ body = await req.json();
1760
+ } catch {
1761
+ body = null;
1762
+ }
1763
+ if (body) {
1764
+ walkObject(body, (value, path) => {
1765
+ if (fields && fields.length > 0) {
1766
+ const fieldName = path.split(".").pop() || path;
1767
+ if (!fields.includes(fieldName)) {
1768
+ return value;
1769
+ }
1770
+ }
1771
+ if (detectXSS(value)) {
1772
+ detections.push({ field: path, value });
1773
+ }
1774
+ return value;
1775
+ }, "");
1776
+ }
1777
+ if (detections.length > 0) {
1778
+ if (onDetection) {
1779
+ for (const { field, value } of detections) {
1780
+ const result = await onDetection(req, field, value);
1781
+ if (result instanceof Response) {
1782
+ return result;
1783
+ }
1784
+ }
1785
+ }
1786
+ return new Response(
1787
+ JSON.stringify({
1788
+ error: "xss_detected",
1789
+ message: "Potentially malicious content detected",
1790
+ fields: detections.map((d) => d.field)
1791
+ }),
1792
+ {
1793
+ status: 400,
1794
+ headers: { "Content-Type": "application/json" }
1795
+ }
1796
+ );
1797
+ }
1798
+ return handler(req);
1799
+ };
1800
+ }
1801
+ function withSQLProtection(handler, config = {}) {
1802
+ const {
1803
+ fields,
1804
+ deep = true,
1805
+ mode = "block",
1806
+ customPatterns,
1807
+ allowList = [],
1808
+ onDetection
1809
+ } = config;
1810
+ return async (req) => {
1811
+ let body;
1812
+ try {
1813
+ body = await req.json();
1814
+ } catch {
1815
+ return handler(req);
1816
+ }
1817
+ const detections = detectSQLInjectionInObject(body, {
1818
+ fields,
1819
+ deep,
1820
+ customPatterns,
1821
+ minSeverity: mode === "detect" ? "low" : "medium"
1822
+ });
1823
+ const filtered = detections.filter((d) => !allowList.includes(d.value));
1824
+ if (filtered.length > 0) {
1825
+ if (onDetection) {
1826
+ const result = await onDetection(req, filtered);
1827
+ if (result instanceof Response) {
1828
+ return result;
1829
+ }
1830
+ }
1831
+ if (mode === "block") {
1832
+ return new Response(
1833
+ JSON.stringify({
1834
+ error: "sql_injection_detected",
1835
+ message: "Potentially malicious SQL detected",
1836
+ detections: filtered.map((d) => ({
1837
+ field: d.field,
1838
+ pattern: d.pattern,
1839
+ severity: d.severity
1840
+ }))
1841
+ }),
1842
+ {
1843
+ status: 400,
1844
+ headers: { "Content-Type": "application/json" }
1845
+ }
1846
+ );
1847
+ }
1848
+ }
1849
+ return handler(req);
1850
+ };
1851
+ }
1852
+ function withContentType(handler, config) {
1853
+ const onInvalid = config.onInvalid || ((_, contentType) => defaultContentTypeErrorResponse(contentType, `Content-Type '${contentType}' is not allowed`));
1854
+ return async (req) => {
1855
+ const result = validateContentType(req, config);
1856
+ if (!result.valid) {
1857
+ return onInvalid(req, result.contentType);
1858
+ }
1859
+ return handler(req);
1860
+ };
1861
+ }
1862
+ function withFileValidation(handler, config = {}) {
1863
+ const onInvalid = config.onInvalid || ((_, errors) => defaultFileErrorResponse(errors));
1864
+ return async (req) => {
1865
+ const result = await validateFilesFromRequest(req, config);
1866
+ if (!result.valid) {
1867
+ return onInvalid(req, result.errors);
1868
+ }
1869
+ return handler(req, { files: result.files });
1870
+ };
1871
+ }
1872
+ function withSecureValidation(handler, config) {
1873
+ return async (req) => {
1874
+ const allErrors = [];
1875
+ if (config.contentType) {
1876
+ const ctResult = validateContentType(req, config.contentType);
1877
+ if (!ctResult.valid) {
1878
+ allErrors.push({
1879
+ field: "Content-Type",
1880
+ code: "invalid_content_type",
1881
+ message: ctResult.reason || "Invalid Content-Type"
1882
+ });
1883
+ }
1884
+ }
1885
+ let files;
1886
+ if (config.files) {
1887
+ const fileResult = await validateFilesFromRequest(req, config.files);
1888
+ if (!fileResult.valid) {
1889
+ allErrors.push(...fileResult.errors.map((e) => ({
1890
+ field: e.field || e.filename,
1891
+ code: e.code,
1892
+ message: e.message
1893
+ })));
1894
+ } else {
1895
+ files = fileResult.files;
1896
+ }
1897
+ }
1898
+ if (allErrors.length > 0) {
1899
+ const onError = config.onError || ((_, errors) => defaultValidationErrorResponse(errors));
1900
+ return onError(req, allErrors);
1901
+ }
1902
+ let validated;
1903
+ if (config.schema) {
1904
+ const schemaResult = await validateRequest(req, {
1905
+ body: config.schema.body,
1906
+ query: config.schema.query,
1907
+ params: config.schema.params,
1908
+ routeParams: config.routeParams
1909
+ });
1910
+ if (!schemaResult.success) {
1911
+ allErrors.push(...schemaResult.errors || []);
1912
+ } else {
1913
+ validated = schemaResult.data;
1914
+ }
1915
+ } else {
1916
+ validated = {
1917
+ body: {},
1918
+ query: {},
1919
+ params: {}
1920
+ };
1921
+ }
1922
+ if (config.sql && validated?.body) {
1923
+ const sqlDetections = detectSQLInjectionInObject(validated.body, {
1924
+ fields: config.sql.fields,
1925
+ deep: config.sql.deep,
1926
+ customPatterns: config.sql.customPatterns
1927
+ });
1928
+ if (sqlDetections.length > 0 && config.sql.mode !== "detect") {
1929
+ allErrors.push(...sqlDetections.map((d) => ({
1930
+ field: d.field,
1931
+ code: "sql_injection",
1932
+ message: `Potential SQL injection detected: ${d.pattern}`
1933
+ })));
1934
+ }
1935
+ }
1936
+ if (config.xss?.enabled && validated?.body) {
1937
+ walkObject(validated.body, (value, path) => {
1938
+ if (config.xss?.fields && config.xss.fields.length > 0) {
1939
+ const fieldName = path.split(".").pop() || path;
1940
+ if (!config.xss.fields.includes(fieldName)) {
1941
+ return value;
1942
+ }
1943
+ }
1944
+ if (detectXSS(value)) {
1945
+ allErrors.push({
1946
+ field: path,
1947
+ code: "xss_detected",
1948
+ message: "Potentially malicious content detected"
1949
+ });
1950
+ }
1951
+ return value;
1952
+ }, "");
1953
+ }
1954
+ if (allErrors.length > 0) {
1955
+ const onError = config.onError || ((_, errors) => defaultValidationErrorResponse(errors));
1956
+ return onError(req, allErrors);
1957
+ }
1958
+ return handler(req, { validated, files });
1959
+ };
1960
+ }
1961
+
1962
+ export { DANGEROUS_EXTENSIONS, DEFAULT_MAX_FILES, DEFAULT_MAX_FILE_SIZE, MIME_TYPES, allValid, checkMagicNumber, createValidator, defaultContentTypeErrorResponse, defaultFileErrorResponse, defaultValidationErrorResponse, detectFileType, detectSQLInjection, detectSQLInjectionInObject, detectXSS, escapeHtml, extractFilesFromFormData, getByPath, getExtension, getFilename, getMultipartBoundary, hasPathTraversal, hasSQLInjection, isAllowedContentType, isAllowedValue, isCustomSchema, isFormRequest, isHiddenPath, isJsonRequest, isMultipartRequest, isPathContained, isSafeUrl, isZodSchema, mergeErrors, parseContentType, parseQueryString, sanitize, sanitizeFields, sanitizeFilename, sanitizeHtml, sanitizeObject, sanitizePath, sanitizeSQLInput, setByPath, stripHtml, unescapeHtml, validate, validateBody, validateContentType, validateCustomSchema, validateField, validateFile, validateFiles, validateFilesFromRequest, validateParams, validatePath, validateQuery, validateRequest, validateZodSchema, walkObject, withContentType, withFileValidation, withSQLProtection, withSanitization, withSecureValidation, withValidation, withXSSProtection };
1963
+ //# sourceMappingURL=validation.js.map
1964
+ //# sourceMappingURL=validation.js.map