loopback-hostname.ts 771 B

123456789101112131415161718
  1. /**
  2. * Browser-safe, zero-dependency loopback classification shared by the `/api`
  3. * Host fence and the package's `ctx.connection` state. The predicate stays
  4. * package-internal; client plugins consume the derived state through Cordis.
  5. */
  6. /**
  7. * Whether a normalized URL hostname names the local loopback authority.
  8. * @param hostname - WHATWG URL hostname (IPv6 literals retain brackets).
  9. * @returns true for localhost, IPv6 loopback, or any IPv4 address in 127/8.
  10. */
  11. export function isLoopbackHostname(hostname: string): boolean {
  12. if (hostname === 'localhost' || hostname === '[::1]') return true
  13. const parts = hostname.split('.')
  14. return parts.length === 4
  15. && parts[0] === '127'
  16. && parts.every(part => /^\d{1,3}$/.test(part) && Number(part) <= 255)
  17. }