import { describe, expect, it } from 'vitest'
import { isLoopbackHostLiteral } from '../src/net/loopbackLiteral.js'

describe('isLoopbackHostLiteral — strict loopback-literal check (FIX C-host-1 / anti-SSRF)', () => {
  it('accepts exact loopback literals', () => {
    expect(isLoopbackHostLiteral('localhost')).toBe(true)
    expect(isLoopbackHostLiteral('::1')).toBe(true)
    expect(isLoopbackHostLiteral('[::1]')).toBe(true)
  })

  it('accepts any well-formed IPv4 in 127.0.0.0/8', () => {
    expect(isLoopbackHostLiteral('127.0.0.1')).toBe(true)
    expect(isLoopbackHostLiteral('127.0.0.2')).toBe(true)
    expect(isLoopbackHostLiteral('127.5.5.5')).toBe(true)
    expect(isLoopbackHostLiteral('127.255.255.255')).toBe(true)
  })

  it('rejects non-loopback IPs and wildcards', () => {
    expect(isLoopbackHostLiteral('0.0.0.0')).toBe(false)
    expect(isLoopbackHostLiteral('192.168.1.10')).toBe(false)
    expect(isLoopbackHostLiteral('10.0.0.5')).toBe(false)
    expect(isLoopbackHostLiteral('::')).toBe(false)
  })

  it('REJECTS suffixed hostnames that merely start with 127. (the S-GATE bypass)', () => {
    expect(isLoopbackHostLiteral('127.0.0.1.attacker.example.com')).toBe(false)
    expect(isLoopbackHostLiteral('127.evil.net')).toBe(false)
    expect(isLoopbackHostLiteral('127.0.0.1.evil.example.com')).toBe(false)
    expect(isLoopbackHostLiteral('127.0.0.1x')).toBe(false)
  })

  it('rejects malformed / non-dotted-quad partials and out-of-range octets', () => {
    expect(isLoopbackHostLiteral('127.1')).toBe(false)
    expect(isLoopbackHostLiteral('127.0.0.256')).toBe(false)
    expect(isLoopbackHostLiteral('0127.0.0.1')).toBe(false)
    expect(isLoopbackHostLiteral('')).toBe(false)
    expect(isLoopbackHostLiteral('127')).toBe(false)
  })
})
