( hostname: string | null | undefined, paramName = 'hostname' )
| 380 | * ``` |
| 381 | */ |
| 382 | export function validateHostname( |
| 383 | hostname: string | null | undefined, |
| 384 | paramName = 'hostname' |
| 385 | ): ValidationResult { |
| 386 | if (hostname === null || hostname === undefined || hostname === '') { |
| 387 | return { |
| 388 | isValid: false, |
| 389 | error: `${paramName} is required`, |
| 390 | } |
| 391 | } |
| 392 | |
| 393 | const lowerHostname = hostname.toLowerCase() |
| 394 | |
| 395 | if (lowerHostname === 'localhost') { |
| 396 | logger.warn('Hostname is localhost', { paramName }) |
| 397 | return { |
| 398 | isValid: false, |
| 399 | error: `${paramName} cannot be a private IP address or localhost`, |
| 400 | } |
| 401 | } |
| 402 | |
| 403 | if (ipaddr.isValid(lowerHostname)) { |
| 404 | if (isPrivateOrReservedIP(lowerHostname)) { |
| 405 | logger.warn('Hostname matches blocked IP range', { |
| 406 | paramName, |
| 407 | hostname: hostname.substring(0, 100), |
| 408 | }) |
| 409 | return { |
| 410 | isValid: false, |
| 411 | error: `${paramName} cannot be a private IP address or localhost`, |
| 412 | } |
| 413 | } |
| 414 | } |
| 415 | |
| 416 | const hostnamePattern = |
| 417 | /^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?(\.[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?)*$/i |
| 418 | |
| 419 | if (!hostnamePattern.test(hostname)) { |
| 420 | logger.warn('Invalid hostname format', { |
| 421 | paramName, |
| 422 | hostname: hostname.substring(0, 100), |
| 423 | }) |
| 424 | return { |
| 425 | isValid: false, |
| 426 | error: `${paramName} is not a valid hostname`, |
| 427 | } |
| 428 | } |
| 429 | |
| 430 | return { isValid: true, sanitized: hostname } |
| 431 | } |
| 432 | |
| 433 | /** |
| 434 | * Validates a file extension |
no test coverage detected