-
Notifications
You must be signed in to change notification settings - Fork 3.7k
Expand file tree
/
Copy pathinput-validation.ts
More file actions
1041 lines (950 loc) · 27.1 KB
/
Copy pathinput-validation.ts
File metadata and controls
1041 lines (950 loc) · 27.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import { createLogger } from '@sim/logger'
import * as ipaddr from 'ipaddr.js'
const logger = createLogger('InputValidation')
export interface ValidationResult {
isValid: boolean
error?: string
sanitized?: string
}
export interface PathSegmentOptions {
/** Name of the parameter for error messages */
paramName?: string
/** Maximum length allowed (default: 255) */
maxLength?: number
/** Allow hyphens (default: true) */
allowHyphens?: boolean
/** Allow underscores (default: true) */
allowUnderscores?: boolean
/** Allow dots (default: false, to prevent directory traversal) */
allowDots?: boolean
/** Custom regex pattern to match */
customPattern?: RegExp
}
/**
* Validates a path segment to prevent path traversal and SSRF attacks
*
* This function ensures that user-provided input used in URL paths or file paths
* cannot be used for directory traversal attacks or SSRF.
*
* Default behavior:
* - Allows: letters (a-z, A-Z), numbers (0-9), hyphens (-), underscores (_)
* - Blocks: dots (.), slashes (/, \), null bytes, URL encoding, and special characters
*
* @param value - The path segment to validate
* @param options - Validation options
* @returns ValidationResult with isValid flag and optional error message
*
* @example
* ```typescript
* const result = validatePathSegment(itemId, { paramName: 'itemId' })
* if (!result.isValid) {
* return NextResponse.json({ error: result.error }, { status: 400 })
* }
* ```
*/
export function validatePathSegment(
value: string | null | undefined,
options: PathSegmentOptions = {}
): ValidationResult {
const {
paramName = 'path segment',
maxLength = 255,
allowHyphens = true,
allowUnderscores = true,
allowDots = false,
customPattern,
} = options
if (value === null || value === undefined || value === '') {
return {
isValid: false,
error: `${paramName} is required`,
}
}
if (value.length > maxLength) {
logger.warn('Path segment exceeds maximum length', {
paramName,
length: value.length,
maxLength,
})
return {
isValid: false,
error: `${paramName} exceeds maximum length of ${maxLength} characters`,
}
}
if (value.includes('\0') || value.includes('%00')) {
logger.warn('Path segment contains null bytes', { paramName })
return {
isValid: false,
error: `${paramName} contains invalid characters`,
}
}
const pathTraversalPatterns = [
'..',
'./',
'.\\.',
'%2e%2e',
'%252e%252e',
'..%2f',
'..%5c',
'%2e%2e%2f',
'%2e%2e/',
'..%252f',
]
const lowerValue = value.toLowerCase()
for (const pattern of pathTraversalPatterns) {
if (lowerValue.includes(pattern.toLowerCase())) {
logger.warn('Path traversal attempt detected', {
paramName,
pattern,
value: value.substring(0, 100),
})
return {
isValid: false,
error: `${paramName} contains invalid path traversal sequences`,
}
}
}
if (value.includes('/') || value.includes('\\')) {
logger.warn('Path segment contains directory separators', { paramName })
return {
isValid: false,
error: `${paramName} cannot contain directory separators`,
}
}
if (customPattern) {
if (!customPattern.test(value)) {
logger.warn('Path segment failed custom pattern validation', {
paramName,
pattern: customPattern.toString(),
})
return {
isValid: false,
error: `${paramName} format is invalid`,
}
}
return { isValid: true, sanitized: value }
}
let pattern = '^[a-zA-Z0-9'
if (allowHyphens) pattern += '\\-'
if (allowUnderscores) pattern += '_'
if (allowDots) pattern += '\\.'
pattern += ']+$'
const regex = new RegExp(pattern)
if (!regex.test(value)) {
logger.warn('Path segment contains disallowed characters', {
paramName,
value: value.substring(0, 100),
})
return {
isValid: false,
error: `${paramName} can only contain alphanumeric characters${allowHyphens ? ', hyphens' : ''}${allowUnderscores ? ', underscores' : ''}${allowDots ? ', dots' : ''}`,
}
}
return { isValid: true, sanitized: value }
}
/**
* Validates an alphanumeric ID (letters, numbers, hyphens, underscores only)
*
* @param value - The ID to validate
* @param paramName - Name of the parameter for error messages
* @param maxLength - Maximum length (default: 100)
* @returns ValidationResult
*
* @example
* ```typescript
* const result = validateAlphanumericId(userId, 'userId')
* if (!result.isValid) {
* return NextResponse.json({ error: result.error }, { status: 400 })
* }
* ```
*/
export function validateAlphanumericId(
value: string | null | undefined,
paramName = 'ID',
maxLength = 100
): ValidationResult {
return validatePathSegment(value, {
paramName,
maxLength,
allowHyphens: true,
allowUnderscores: true,
allowDots: false,
})
}
/**
* Validates a numeric ID
*
* @param value - The ID to validate
* @param paramName - Name of the parameter for error messages
* @param options - Additional options (min, max)
* @returns ValidationResult with sanitized number as string
*
* @example
* ```typescript
* const result = validateNumericId(pageNumber, 'pageNumber', { min: 1, max: 1000 })
* if (!result.isValid) {
* return NextResponse.json({ error: result.error }, { status: 400 })
* }
* ```
*/
export function validateNumericId(
value: string | number | null | undefined,
paramName = 'ID',
options: { min?: number; max?: number } = {}
): ValidationResult {
if (value === null || value === undefined || value === '') {
return {
isValid: false,
error: `${paramName} is required`,
}
}
const num = typeof value === 'number' ? value : Number(value)
if (Number.isNaN(num) || !Number.isFinite(num)) {
logger.warn('Invalid numeric ID', { paramName, value })
return {
isValid: false,
error: `${paramName} must be a valid number`,
}
}
if (options.min !== undefined && num < options.min) {
return {
isValid: false,
error: `${paramName} must be at least ${options.min}`,
}
}
if (options.max !== undefined && num > options.max) {
return {
isValid: false,
error: `${paramName} must be at most ${options.max}`,
}
}
return { isValid: true, sanitized: num.toString() }
}
/**
* Validates an integer value (from JSON body or other sources)
*
* This is stricter than validateNumericId - it requires:
* - Value must already be a number type (not string)
* - Must be an integer (no decimals)
* - Must be finite (not NaN or Infinity)
*
* @param value - The value to validate
* @param paramName - Name of the parameter for error messages
* @param options - Additional options (min, max)
* @returns ValidationResult
*
* @example
* ```typescript
* const result = validateInteger(failedCount, 'failedCount', { min: 0 })
* if (!result.isValid) {
* return NextResponse.json({ error: result.error }, { status: 400 })
* }
* ```
*/
export function validateInteger(
value: unknown,
paramName = 'value',
options: { min?: number; max?: number } = {}
): ValidationResult {
if (value === null || value === undefined) {
return {
isValid: false,
error: `${paramName} is required`,
}
}
if (typeof value !== 'number') {
logger.warn('Value is not a number', { paramName, valueType: typeof value })
return {
isValid: false,
error: `${paramName} must be a number`,
}
}
if (Number.isNaN(value) || !Number.isFinite(value)) {
logger.warn('Invalid number value', { paramName, value })
return {
isValid: false,
error: `${paramName} must be a valid number`,
}
}
if (!Number.isInteger(value)) {
logger.warn('Value is not an integer', { paramName, value })
return {
isValid: false,
error: `${paramName} must be an integer`,
}
}
if (options.min !== undefined && value < options.min) {
return {
isValid: false,
error: `${paramName} must be at least ${options.min}`,
}
}
if (options.max !== undefined && value > options.max) {
return {
isValid: false,
error: `${paramName} must be at most ${options.max}`,
}
}
return { isValid: true }
}
/**
* Validates that a value is in an allowed list (enum validation)
*
* @param value - The value to validate
* @param allowedValues - Array of allowed values
* @param paramName - Name of the parameter for error messages
* @returns ValidationResult
*
* @example
* ```typescript
* const result = validateEnum(type, ['note', 'contact', 'task'], 'type')
* if (!result.isValid) {
* return NextResponse.json({ error: result.error }, { status: 400 })
* }
* ```
*/
export function validateEnum<T extends string>(
value: string | null | undefined,
allowedValues: readonly T[],
paramName = 'value'
): ValidationResult {
if (value === null || value === undefined || value === '') {
return {
isValid: false,
error: `${paramName} is required`,
}
}
if (!allowedValues.includes(value as T)) {
logger.warn('Value not in allowed list', {
paramName,
value,
allowedValues,
})
return {
isValid: false,
error: `${paramName} must be one of: ${allowedValues.join(', ')}`,
}
}
return { isValid: true, sanitized: value }
}
/**
* Validates a hostname to prevent SSRF attacks
*
* This function checks that a hostname is not a private IP, localhost, or other reserved address.
* It complements the validateProxyUrl function by providing hostname-specific validation.
*
* @param hostname - The hostname to validate
* @param paramName - Name of the parameter for error messages
* @returns ValidationResult
*
* @example
* ```typescript
* const result = validateHostname(webhookDomain, 'webhook domain')
* if (!result.isValid) {
* return NextResponse.json({ error: result.error }, { status: 400 })
* }
* ```
*/
export function validateHostname(
hostname: string | null | undefined,
paramName = 'hostname'
): ValidationResult {
if (hostname === null || hostname === undefined || hostname === '') {
return {
isValid: false,
error: `${paramName} is required`,
}
}
const lowerHostname = hostname.toLowerCase()
if (lowerHostname === 'localhost') {
logger.warn('Hostname is localhost', { paramName })
return {
isValid: false,
error: `${paramName} cannot be a private IP address or localhost`,
}
}
if (ipaddr.isValid(lowerHostname)) {
if (isPrivateOrReservedIP(lowerHostname)) {
logger.warn('Hostname matches blocked IP range', {
paramName,
hostname: hostname.substring(0, 100),
})
return {
isValid: false,
error: `${paramName} cannot be a private IP address or localhost`,
}
}
}
const hostnamePattern =
/^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?(\.[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?)*$/i
if (!hostnamePattern.test(hostname)) {
logger.warn('Invalid hostname format', {
paramName,
hostname: hostname.substring(0, 100),
})
return {
isValid: false,
error: `${paramName} is not a valid hostname`,
}
}
return { isValid: true, sanitized: hostname }
}
/**
* Validates a file extension
*
* @param extension - The file extension (with or without leading dot)
* @param allowedExtensions - Array of allowed extensions (without dots)
* @param paramName - Name of the parameter for error messages
* @returns ValidationResult
*
* @example
* ```typescript
* const result = validateFileExtension(ext, ['jpg', 'png', 'gif'], 'file extension')
* if (!result.isValid) {
* return NextResponse.json({ error: result.error }, { status: 400 })
* }
* ```
*/
export function validateFileExtension(
extension: string | null | undefined,
allowedExtensions: readonly string[],
paramName = 'file extension'
): ValidationResult {
if (extension === null || extension === undefined || extension === '') {
return {
isValid: false,
error: `${paramName} is required`,
}
}
const ext = extension.startsWith('.') ? extension.slice(1) : extension
const normalizedExt = ext.toLowerCase()
if (!allowedExtensions.map((e) => e.toLowerCase()).includes(normalizedExt)) {
logger.warn('File extension not in allowed list', {
paramName,
extension: ext,
allowedExtensions,
})
return {
isValid: false,
error: `${paramName} must be one of: ${allowedExtensions.join(', ')}`,
}
}
return { isValid: true, sanitized: normalizedExt }
}
/**
* Validates Microsoft Graph API resource IDs
*
* Microsoft Graph IDs can be complex - for example, SharePoint site IDs can include:
* - "root" (literal string)
* - GUIDs
* - Hostnames with colons and slashes (e.g., "hostname:/sites/sitename")
* - Group paths (e.g., "groups/{guid}/sites/root")
*
* This function allows these legitimate patterns while blocking path traversal.
*
* @param value - The Microsoft Graph ID to validate
* @param paramName - Name of the parameter for error messages
* @returns ValidationResult
*
* @example
* ```typescript
* const result = validateMicrosoftGraphId(siteId, 'siteId')
* if (!result.isValid) {
* return NextResponse.json({ error: result.error }, { status: 400 })
* }
* ```
*/
export function validateMicrosoftGraphId(
value: string | null | undefined,
paramName = 'ID'
): ValidationResult {
if (value === null || value === undefined || value === '') {
return {
isValid: false,
error: `${paramName} is required`,
}
}
const pathTraversalPatterns = [
'../',
'..\\',
'%2e%2e%2f',
'%2e%2e/',
'..%2f',
'%2e%2e%5c',
'%2e%2e\\',
'..%5c',
'%252e%252e%252f',
]
const lowerValue = value.toLowerCase()
for (const pattern of pathTraversalPatterns) {
if (lowerValue.includes(pattern)) {
logger.warn('Path traversal attempt in Microsoft Graph ID', {
paramName,
value: value.substring(0, 100),
})
return {
isValid: false,
error: `${paramName} contains invalid path traversal sequence`,
}
}
}
if (/[\x00-\x1f\x7f]/.test(value) || value.includes('%00')) {
logger.warn('Control characters in Microsoft Graph ID', { paramName })
return {
isValid: false,
error: `${paramName} contains invalid control characters`,
}
}
if (value.includes('\n') || value.includes('\r')) {
return {
isValid: false,
error: `${paramName} contains invalid newline characters`,
}
}
return { isValid: true, sanitized: value }
}
/**
* Validates Jira Cloud IDs (typically UUID format)
*
* @param value - The Jira Cloud ID to validate
* @param paramName - Name of the parameter for error messages
* @returns ValidationResult
*
* @example
* ```typescript
* const result = validateJiraCloudId(cloudId, 'cloudId')
* if (!result.isValid) {
* return NextResponse.json({ error: result.error }, { status: 400 })
* }
* ```
*/
export function validateJiraCloudId(
value: string | null | undefined,
paramName = 'cloudId'
): ValidationResult {
return validatePathSegment(value, {
paramName,
allowHyphens: true,
allowUnderscores: false,
allowDots: false,
maxLength: 100,
})
}
/**
* Validates Jira issue keys (format: PROJECT-123 or PROJECT-KEY-123)
*
* @param value - The Jira issue key to validate
* @param paramName - Name of the parameter for error messages
* @returns ValidationResult
*
* @example
* ```typescript
* const result = validateJiraIssueKey(issueKey, 'issueKey')
* if (!result.isValid) {
* return NextResponse.json({ error: result.error }, { status: 400 })
* }
* ```
*/
export function validateJiraIssueKey(
value: string | null | undefined,
paramName = 'issueKey'
): ValidationResult {
return validatePathSegment(value, {
paramName,
allowHyphens: true,
allowUnderscores: false,
allowDots: false,
maxLength: 255,
})
}
/**
* Validates a URL to prevent SSRF attacks
*
* This function checks that URLs:
* - Use https:// protocol only
* - Do not point to private IP ranges or localhost
* - Do not use suspicious ports
*
* @param url - The URL to validate
* @param paramName - Name of the parameter for error messages
* @returns ValidationResult
*
* @example
* ```typescript
* const result = validateExternalUrl(url, 'fileUrl')
* if (!result.isValid) {
* return NextResponse.json({ error: result.error }, { status: 400 })
* }
* ```
*/
export function validateExternalUrl(
url: string | null | undefined,
paramName = 'url'
): ValidationResult {
if (!url || typeof url !== 'string') {
return {
isValid: false,
error: `${paramName} is required and must be a string`,
}
}
let parsedUrl: URL
try {
parsedUrl = new URL(url)
} catch {
return {
isValid: false,
error: `${paramName} must be a valid URL`,
}
}
const protocol = parsedUrl.protocol
const hostname = parsedUrl.hostname.toLowerCase()
const cleanHostname =
hostname.startsWith('[') && hostname.endsWith(']') ? hostname.slice(1, -1) : hostname
let isLocalhost = cleanHostname === 'localhost'
if (ipaddr.isValid(cleanHostname)) {
const processedIP = ipaddr.process(cleanHostname).toString()
if (processedIP === '127.0.0.1' || processedIP === '::1') {
isLocalhost = true
}
}
if (protocol !== 'https:' && !(protocol === 'http:' && isLocalhost)) {
return {
isValid: false,
error: `${paramName} must use https:// protocol`,
}
}
if (!isLocalhost && ipaddr.isValid(cleanHostname)) {
if (isPrivateOrReservedIP(cleanHostname)) {
return {
isValid: false,
error: `${paramName} cannot point to private IP addresses`,
}
}
}
// Block suspicious ports commonly used for internal services
const port = parsedUrl.port
const blockedPorts = [
'22', // SSH
'23', // Telnet
'25', // SMTP
'3306', // MySQL
'5432', // PostgreSQL
'6379', // Redis
'27017', // MongoDB
'9200', // Elasticsearch
]
if (port && blockedPorts.includes(port)) {
return {
isValid: false,
error: `${paramName} uses a blocked port`,
}
}
return { isValid: true }
}
/**
* Validates an image URL to prevent SSRF attacks
* Alias for validateExternalUrl for backward compatibility
*/
export function validateImageUrl(
url: string | null | undefined,
paramName = 'imageUrl'
): ValidationResult {
return validateExternalUrl(url, paramName)
}
/**
* Validates a proxy URL to prevent SSRF attacks
* Alias for validateExternalUrl for backward compatibility
*/
export function validateProxyUrl(
url: string | null | undefined,
paramName = 'proxyUrl'
): ValidationResult {
return validateExternalUrl(url, paramName)
}
/**
* Checks if an IP address is private or reserved (not routable on the public internet)
* Uses ipaddr.js for robust handling of all IP formats including:
* - Octal notation (0177.0.0.1)
* - Hex notation (0x7f000001)
* - IPv4-mapped IPv6 (::ffff:127.0.0.1)
* - Various edge cases that regex patterns miss
*/
function isPrivateOrReservedIP(ip: string): boolean {
try {
if (!ipaddr.isValid(ip)) {
return true
}
const addr = ipaddr.process(ip)
const range = addr.range()
return range !== 'unicast'
} catch {
return true
}
}
/**
* Validates an Airtable ID (base, table, or webhook ID)
*
* Airtable IDs have specific prefixes:
* - Base IDs: "app" + 14 alphanumeric characters (e.g., appXXXXXXXXXXXXXX)
* - Table IDs: "tbl" + 14 alphanumeric characters
* - Webhook IDs: "ach" + 14 alphanumeric characters
*
* @param value - The ID to validate
* @param expectedPrefix - The expected prefix ('app', 'tbl', or 'ach')
* @param paramName - Name of the parameter for error messages
* @returns ValidationResult
*
* @example
* ```typescript
* const result = validateAirtableId(baseId, 'app', 'baseId')
* if (!result.isValid) {
* throw new Error(result.error)
* }
* ```
*/
export function validateAirtableId(
value: string | null | undefined,
expectedPrefix: 'app' | 'tbl' | 'ach',
paramName = 'ID'
): ValidationResult {
if (value === null || value === undefined || value === '') {
return {
isValid: false,
error: `${paramName} is required`,
}
}
// Airtable IDs: prefix (3 chars) + 14 alphanumeric characters = 17 chars total
const airtableIdPattern = new RegExp(`^${expectedPrefix}[a-zA-Z0-9]{14}$`)
if (!airtableIdPattern.test(value)) {
logger.warn('Invalid Airtable ID format', {
paramName,
expectedPrefix,
value: value.substring(0, 20),
})
return {
isValid: false,
error: `${paramName} must be a valid Airtable ID starting with "${expectedPrefix}"`,
}
}
return { isValid: true, sanitized: value }
}
/**
* Validates an AWS region identifier
*
* Supported region formats:
* - Standard: us-east-1, eu-west-2, ap-southeast-1, sa-east-1, af-south-1
* - GovCloud: us-gov-east-1, us-gov-west-1
* - China: cn-north-1, cn-northwest-1
* - Israel: il-central-1
* - ISO partitions: us-iso-east-1, us-isob-east-1
*
* @param value - The AWS region to validate
* @param paramName - Name of the parameter for error messages
* @returns ValidationResult
*
* @example
* ```typescript
* const result = validateAwsRegion(region, 'region')
* if (!result.isValid) {
* return NextResponse.json({ error: result.error }, { status: 400 })
* }
* ```
*/
export function validateAwsRegion(
value: string | null | undefined,
paramName = 'region'
): ValidationResult {
if (value === null || value === undefined || value === '') {
return {
isValid: false,
error: `${paramName} is required`,
}
}
// AWS region patterns:
// - Standard: af|ap|ca|eu|me|sa|us|il followed by direction and number
// - GovCloud: us-gov-east-1, us-gov-west-1
// - China: cn-north-1, cn-northwest-1
// - ISO: us-iso-east-1, us-iso-west-1, us-isob-east-1
const awsRegionPattern =
/^(af|ap|ca|cn|eu|il|me|sa|us|us-gov|us-iso|us-isob)-(central|north|northeast|northwest|south|southeast|southwest|east|west)-\d{1,2}$/
if (!awsRegionPattern.test(value)) {
logger.warn('Invalid AWS region format', {
paramName,
value: value.substring(0, 50),
})
return {
isValid: false,
error: `${paramName} must be a valid AWS region (e.g., us-east-1, eu-west-2, us-gov-west-1)`,
}
}
return { isValid: true, sanitized: value }
}
/**
* Validates an S3 bucket name according to AWS naming rules
*
* S3 bucket names must:
* - Be 3-63 characters long
* - Start and end with a letter or number
* - Contain only lowercase letters, numbers, and hyphens
* - Not contain consecutive periods
* - Not be formatted as an IP address
*
* @param value - The S3 bucket name to validate
* @param paramName - Name of the parameter for error messages
* @returns ValidationResult
*
* @example
* ```typescript
* const result = validateS3BucketName(bucket, 'bucket')
* if (!result.isValid) {
* return NextResponse.json({ error: result.error }, { status: 400 })
* }
* ```
*/
export function validateS3BucketName(
value: string | null | undefined,
paramName = 'bucket'
): ValidationResult {
if (value === null || value === undefined || value === '') {
return {
isValid: false,
error: `${paramName} is required`,
}
}
if (value.length < 3 || value.length > 63) {
logger.warn('S3 bucket name length invalid', {
paramName,
length: value.length,
})
return {
isValid: false,
error: `${paramName} must be between 3 and 63 characters`,
}
}
const bucketNamePattern = /^[a-z0-9][a-z0-9.-]*[a-z0-9]$|^[a-z0-9]$/
if (!bucketNamePattern.test(value)) {
logger.warn('Invalid S3 bucket name format', {
paramName,
value: value.substring(0, 63),
})
return {
isValid: false,
error: `${paramName} must start and end with a letter or number, and contain only lowercase letters, numbers, hyphens, and periods`,
}
}
if (value.includes('..')) {
logger.warn('S3 bucket name contains consecutive periods', { paramName })
return {
isValid: false,
error: `${paramName} cannot contain consecutive periods`,
}
}
const ipPattern = /^(\d{1,3}\.){3}\d{1,3}$/
if (ipPattern.test(value)) {
logger.warn('S3 bucket name formatted as IP address', { paramName })
return {
isValid: false,
error: `${paramName} cannot be formatted as an IP address`,
}
}
return { isValid: true, sanitized: value }
}
/**
* Validates a Google Calendar ID
*
* Google Calendar IDs can be:
* - "primary" (literal string for the user's primary calendar)
* - Email addresses (for user calendars)
* - Alphanumeric strings with hyphens, underscores, and dots (for other calendars)
*
* This validator allows these legitimate formats while blocking path traversal and injection attempts.
*
* @param value - The calendar ID to validate
* @param paramName - Name of the parameter for error messages
* @returns ValidationResult
*
* @example
* ```typescript
* const result = validateGoogleCalendarId(calendarId, 'calendarId')
* if (!result.isValid) {
* return NextResponse.json({ error: result.error }, { status: 400 })
* }
* ```
*/
export function validateGoogleCalendarId(
value: string | null | undefined,
paramName = 'calendarId'
): ValidationResult {
if (value === null || value === undefined || value === '') {
return {
isValid: false,
error: `${paramName} is required`,
}
}
if (value === 'primary') {
return { isValid: true, sanitized: value }
}
const pathTraversalPatterns = [
'../',
'..\\',
'%2e%2e%2f',
'%2e%2e/',
'..%2f',
'%2e%2e%5c',
'%2e%2e\\',
'..%5c',
'%252e%252e%252f',
]
const lowerValue = value.toLowerCase()
for (const pattern of pathTraversalPatterns) {
if (lowerValue.includes(pattern)) {
logger.warn('Path traversal attempt in Google Calendar ID', {
paramName,
value: value.substring(0, 100),
})
return {
isValid: false,
error: `${paramName} contains invalid path traversal sequence`,
}
}
}
if (/[\x00-\x1f\x7f]/.test(value) || value.includes('%00')) {
logger.warn('Control characters in Google Calendar ID', { paramName })
return {
isValid: false,