(
value: string | null | undefined,
options: PathSegmentOptions = {}
)
| 48 | * ``` |
| 49 | */ |
| 50 | export function validatePathSegment( |
| 51 | value: string | null | undefined, |
| 52 | options: PathSegmentOptions = {} |
| 53 | ): ValidationResult { |
| 54 | const { |
| 55 | paramName = 'path segment', |
| 56 | maxLength = 255, |
| 57 | allowHyphens = true, |
| 58 | allowUnderscores = true, |
| 59 | allowDots = false, |
| 60 | customPattern, |
| 61 | } = options |
| 62 | |
| 63 | if (value === null || value === undefined || value === '') { |
| 64 | return { |
| 65 | isValid: false, |
| 66 | error: `${paramName} is required`, |
| 67 | } |
| 68 | } |
| 69 | |
| 70 | if (value.length > maxLength) { |
| 71 | logger.warn('Path segment exceeds maximum length', { |
| 72 | paramName, |
| 73 | length: value.length, |
| 74 | maxLength, |
| 75 | }) |
| 76 | return { |
| 77 | isValid: false, |
| 78 | error: `${paramName} exceeds maximum length of ${maxLength} characters`, |
| 79 | } |
| 80 | } |
| 81 | |
| 82 | if (value.includes('\0') || value.includes('%00')) { |
| 83 | logger.warn('Path segment contains null bytes', { paramName }) |
| 84 | return { |
| 85 | isValid: false, |
| 86 | error: `${paramName} contains invalid characters`, |
| 87 | } |
| 88 | } |
| 89 | |
| 90 | const pathTraversalPatterns = [ |
| 91 | '..', |
| 92 | './', |
| 93 | '.\\.', |
| 94 | '%2e%2e', |
| 95 | '%252e%252e', |
| 96 | '..%2f', |
| 97 | '..%5c', |
| 98 | '%2e%2e%2f', |
| 99 | '%2e%2e/', |
| 100 | '..%252f', |
| 101 | ] |
| 102 | |
| 103 | const lowerValue = value.toLowerCase() |
| 104 | for (const pattern of pathTraversalPatterns) { |
| 105 | if (lowerValue.includes(pattern.toLowerCase())) { |
| 106 | logger.warn('Path traversal attempt detected', { |
| 107 | paramName, |
no test coverage detected