// src/host-check.js - host/port validation and SSRF/private-address blocking. import net from 'node:net'; import dns from 'node:dns/promises'; function isPrivateIpv4(ip) { const parts = ip.split('.').map((n) => Number(n)); if (parts.length !== 4 || parts.some((n) => !Number.isInteger(n) || n < 0 || n > 255)) return true; const [a, b] = parts; if (a === 0 || a === 10 || a === 127) return true; if (a === 169 && b === 254) return true; if (a === 172 && b >= 16 && b <= 31) return true; if (a === 192 && b === 168) return true; if (a === 100 && b >= 64 && b <= 127) return true; // CGNAT if (a === 192 && b === 0 && parts[2] === 0) return true; if (a === 192 && b === 0 && parts[2] === 2) return true; if (a === 198 && (b === 18 || b === 19)) return true; if (a === 198 && b === 51 && parts[2] === 100) return true; if (a === 203 && b === 0 && parts[2] === 113) return true; if (a >= 224) return true; // multicast/reserved return false; } function isPrivateIpv6(ip) { const v = ip.toLowerCase().split('%')[0]; if (v === '::1' || v === '::') return true; if (v.startsWith('fe8') || v.startsWith('fe9') || v.startsWith('fea') || v.startsWith('feb')) return true; // fe80::/10 if (v.startsWith('fc') || v.startsWith('fd')) return true; // fc00::/7 // IPv4-mapped ::ffff:x.x.x.x or ::ffff:7f00:1 const mapped = v.match(/^::ffff:(\d+\.\d+\.\d+\.\d+)$/i); if (mapped) return isPrivateIpv4(mapped[1]); const hexMapped = v.match(/^::ffff:([0-9a-f]{1,4}):([0-9a-f]{1,4})$/i); if (hexMapped) { const hi = parseInt(hexMapped[1], 16); const lo = parseInt(hexMapped[2], 16); return isPrivateIpv4(`${(hi >> 8) & 255}.${hi & 255}.${(lo >> 8) & 255}.${lo & 255}`); } return false; } function isPrivateIp(ip) { const kind = net.isIP(ip); if (kind === 4) return isPrivateIpv4(ip); if (kind === 6) return isPrivateIpv6(ip); return true; } export async function isDisallowedHost(host) { const h = String(host || '').trim().toLowerCase().replace(/\.+$/, ''); if (!h) return true; if (h === 'localhost' || h.endsWith('.localhost') || h.endsWith('.local') || h.endsWith('.internal')) return true; if (net.isIP(h)) return isPrivateIp(h); try { const results = await dns.lookup(h, { all: true, verbatim: true }); if (!results.length) return true; return results.some((r) => isPrivateIp(r.address)); } catch { // If DNS resolution fails, do not allow unresolved host to be used for SSRF checks bypass; // let normal connection fail later? Better be safe: block. return true; } } export function cleanHost(v) { const s = String(v || '').trim().slice(0, 255); if (!s) return ''; if (!/^[a-zA-Z0-9._:-]+$/.test(s)) return ''; return s; } export function cleanPort(v, fallback) { const n = Number(v); if (!Number.isInteger(n) || n < 1 || n > 65535) return fallback; return n; } export function isAllowedPort(port, base, delta = 5) { const p = Number(port); const b = Number(base); if (!Number.isInteger(p) || !Number.isInteger(b)) return false; return Math.abs(p - b) <= delta; }