import { describe, it, expect } from 'vitest';
import { createServer } from 'node:http';
import { pinnedFetch } from './ssrf-strict.js';

describe('pinnedFetch', () => {
  it('reaches a local server via pinned 127.0.0.1 using a fake Host header', async () => {
    const server = createServer((req, res) => {
      res.setHeader('content-type', 'application/json');
      res.end(JSON.stringify({ host: req.headers.host, path: req.url }));
    });
    await new Promise<void>((resolve) => server.listen(0, '127.0.0.1', resolve));
    const port = (server.address() as { port: number }).port;

    // We intentionally pass a non-matching hostname and pin localhost so the DNS is bypassed.
    try {
      const res = await pinnedFetch(`http://example.invalid:${port}/ping`, {
        pinnedIp: '127.0.0.1',
        family: 4,
      });
      const json = (await res.json()) as { host: string; path: string };
      expect(json.path).toBe('/ping');
      expect(json.host).toContain('example.invalid');
    } finally {
      await new Promise<void>((resolve) => server.close(() => resolve()));
    }
  });
});
