/**
 * Strict loopback-literal check — the single source of truth for both S-GATE-style guards:
 *   - `service/install.ts` isLoopbackBindHost (BIND_HOST S-GATE, FIX C-host-1, CRITICAL)
 *   - `config/agentConfig.ts` isLoopbackWsUrl   (localTargetUrl anti-SSRF)
 *
 * Both previously used `value.startsWith('127.')`, which treats an arbitrary suffixed HOSTNAME
 * such as `127.0.0.1.attacker.example.com` or `127.evil.net` as loopback. Because Node resolves
 * non-literal hosts via DNS before bind()/dial, that prefix match let a crafted value defeat the
 * exact invariant the guard exists to enforce. This module fails closed: it accepts a value ONLY
 * when it is an EXACT loopback literal — `localhost`, `::1`/`[::1]`, or a fully-parsed IPv4 address
 * in 127.0.0.0/8 with NO trailing characters. Anything else (a hostname, a partial IP, `0.0.0.0`,
 * `::`) is rejected.
 */
import { isIPv4 } from 'node:net'

/** Non-IPv4 loopback literals accepted verbatim (localhost + the IPv6 loopback, with/without brackets). */
const LOOPBACK_LITERALS: ReadonlySet<string> = new Set(['localhost', '::1', '[::1]'])

/**
 * True iff `host` is an EXACT loopback literal: `localhost`, `::1`, `[::1]`, or a well-formed IPv4
 * address in 127.0.0.0/8 (the whole string must parse as a dotted-quad — no trailing label). A
 * suffixed hostname like `127.0.0.1.attacker.example.com` is NOT loopback and returns false.
 */
export function isLoopbackHostLiteral(host: string): boolean {
  if (LOOPBACK_LITERALS.has(host)) return true
  // isIPv4 requires the FULL string to be a dotted-quad, so no trailing hostname label can slip
  // through; the first-octet check then confines it to the 127.0.0.0/8 loopback block.
  return isIPv4(host) && host.split('.')[0] === '127'
}
