(hostname: string)
| 37 | * Checks all A and AAAA records to prevent multi-record bypass attacks. |
| 38 | */ |
| 39 | export async function validateHostResolution(hostname: string): Promise<void> { |
| 40 | if (isPrivateHostname(hostname)) { |
| 41 | throw new Error('URLs pointing to private or internal networks are not allowed'); |
| 42 | } |
| 43 | |
| 44 | // If already an IP literal, the string check above is sufficient |
| 45 | if (isIP(hostname)) return; |
| 46 | |
| 47 | // Resolve all DNS records and check every address |
| 48 | const [ipv4Result, ipv6Result] = await Promise.allSettled([ |
| 49 | dns.resolve4(hostname), |
| 50 | dns.resolve6(hostname), |
| 51 | ]); |
| 52 | |
| 53 | const allAddresses = [ |
| 54 | ...(ipv4Result.status === 'fulfilled' ? ipv4Result.value : []), |
| 55 | ...(ipv6Result.status === 'fulfilled' ? ipv6Result.value : []), |
| 56 | ]; |
| 57 | |
| 58 | if (allAddresses.length === 0) { |
| 59 | throw new Error('Could not resolve hostname'); |
| 60 | } |
| 61 | |
| 62 | for (const address of allAddresses) { |
| 63 | if (isPrivateHostname(address)) { |
| 64 | throw new Error('URL resolved to a private or internal IP address'); |
| 65 | } |
| 66 | } |
| 67 | } |
| 68 | |
| 69 | /** |
| 70 | * Validate a URL for safe server-side fetching. |
no test coverage detected