// test-block.mjs
// Control test: the same raw SOCKS5 CONNECT but with a plain hostname
// (no null byte). The wildcard allowlist correctly blocks this request,
// demonstrating that the bypass in test-not-block.mjs comes specifically
// from the null-byte parser differential, not from the SOCKS path itself.

import net from 'node:net'

if (!process.env.ALL_PROXY) {
  console.error(
    'ERROR: ALL_PROXY is not set.\n' +
    'This script must run inside a Claude Code sandbox Bash session.\n' +
    'The sandbox injects ALL_PROXY=socks5h://host:port automatically.\n\n' +
    'If you see this error, the sandbox did not start. Likely cause:\n' +
    '  bubblewrap needs SYS_ADMIN. Re-run the container with:\n' +
    '    docker run --rm -it --privileged <image>\n' +
    '  or: --cap-add=SYS_ADMIN --security-opt=seccomp=unconfined'
  )
  process.exit(1)
}

const [h, p] = process.env.ALL_PROXY.replace('socks5h://', '').split(':')
const s = net.connect(parseInt(p), h, () => s.write(Buffer.from([5, 1, 0])))

s.once('data', () => {
  // Plain hostname, no null byte. Allowlist: ["*.google.com"].
  // JavaScript endsWith('.google.com') -> false, request denied.
  const hb = Buffer.from('example.com', 'binary')

  const r = Buffer.allocUnsafe(7 + hb.length)
  r[0] = 5         // SOCKS version
  r[1] = 1         // CONNECT
  r[2] = 0         // reserved
  r[3] = 3         // DOMAINNAME address type
  r[4] = hb.length // hostname length
  hb.copy(r, 5)
  r.writeUInt16BE(80, 5 + hb.length) // destination port

  s.write(r)
  s.once('data', d => {
    console.log(d[1] === 0x02 ? 'BLOCKED' : 'BYPASSED rep=' + d[1].toString(16))
  })
})
