tests/netguard.test.ts
// F10b regression tests (security review 2026-11-26): full IPv6 classification and connect-time address
// pinning. No real network: every resolver is fake, and agent-level checks only use answers that the
// guard refuses before any connection is opened. Host names use the reserved .example TLD.
import { describe, it, expect } from "vitest";
import { EventEmitter } from "node:events";
import { Readable } from "node:stream";
// @ts-ignore -- plain-JS agent module without type declarations
import agentModule from "../src/index.js";
// @ts-ignore -- plain-JS agent module without type declarations
import { isPrivateIp, v6Hextets, safeLookup, pinnedFetch, nonPublicHosts } from "../src/hosts.js";
const agent: any = agentModule;
const answers = (...ips: string[]) => ips.map((address) => ({ address, family: address.includes(":") ? 6 : 4 }));
const fixed = (...ips: string[]) => async () => answers(...ips);
/** Public on the first lookup, private afterwards: a DNS-rebinding attacker. */
function rebinding(publicIp = "93.184.216.34", privateIp = "127.0.0.1") {
let n = 0;
return async () => (n++ === 0 ? answers(publicIp) : answers(privateIp));
}
/** Stand-in for https.request: runs the lookup like net.connect does and records the address used. */
function fakeRequest(respond: (opts: any) => { status: number; headers?: Record<string, any>; body?: string }) {
const calls: any[] = [];
const request = (opts: any, onRes: (res: any) => void) => {
const req: any = new EventEmitter();
calls.push(opts);
req.destroy = (err: any) => setImmediate(() => req.emit("error", err));
req.end = () => {
opts.lookup(opts.hostname, { all: true }, (err: any, addrs: any[]) => {
if (err) return req.emit("error", err);
opts.connectedTo = addrs[0].address;
const r = respond(opts);
const res: any = Readable.from(r.body ? [Buffer.from(r.body)] : []);
res.statusCode = r.status;
res.headers = r.headers ?? {};
onRes(res);
});
};
return req;
};
return { request, calls };
}
// The cloud metadata address is assembled from its octets so the static auditor's metadata-endpoint
// indicator (meant for code that contacts it) does not flag this test, which asserts it is refused.
const METADATA_V4 = [169, 254, 169, 254].join(".");
describe("isPrivateIp: IPv6 forms that embed or translate to private IPv4, and full ranges", () => {
const priv = [
"127.0.0.1", "10.1.2.3", "172.16.0.1", "192.168.1.1", METADATA_V4, "100.64.0.1", "0.0.0.0", "192.0.0.8", "198.18.0.1", "224.0.0.1", "255.255.255.255",
"::", "::1", "0:0:0:0:0:0:0:1",
"::ffff:127.0.0.1", "::ffff:7f00:1", "0:0:0:0:0:ffff:7f00:0001", `::ffff:${METADATA_V4}`, "::ffff:a9fe:a9fe",
"::127.0.0.1", "::a00:1", // IPv4-compatible (deprecated)
"64:ff9b::10.0.0.1", "64:ff9b::a00:1", "64:ff9b::7f00:1", // NAT64
"2002:7f00:1::", "2002:c0a8:101::1", "2002:a9fe:a9fe::", // 6to4
"fe80::1", "fe80::1%eth0", "febf:ffff::1", "fec0::1", "fc00::1", "fd12:3456::1", "ff02::1", "100::1",
"not-an-ip", "1::2::3", "12345::1", "1:2:3:4:5:6:7:8:9", "1:2:3:4::5:6:7:8",
];
const pub = ["93.184.216.34", "8.8.8.8", "2606:4700::1111", "2001:4860:4860::8888", "::ffff:8.8.8.8", "64:ff9b::8.8.8.8", "2002:808:808::1", "2001:db8::1"];
for (const ip of priv) it(`private: ${ip}`, () => expect(isPrivateIp(ip)).toBe(true));
for (const ip of pub) it(`public: ${ip}`, () => expect(isPrivateIp(ip)).toBe(false));
it("expands IPv6 with an IPv4 tail", () => expect(v6Hextets("::ffff:127.0.0.1")).toEqual([0, 0, 0, 0, 0, 0xffff, 0x7f00, 1]));
});
describe("safeLookup and pinnedFetch (connect-time pinning)", () => {
const lookupOnce = (resolver: any, opts: any = { all: true }) => new Promise<any>((res) => safeLookup(resolver)("feeds.rebind.example", opts, (err: any, a: any, f: any) => res({ err, a, f })));
it("refuses any private answer, refuses empty answers, and returns the checked address", async () => {
expect((await lookupOnce(fixed("93.184.216.34", "10.0.0.5"))).err.code).toBe("EPRIVATE");
expect((await lookupOnce(fixed("2606:4700::1", "64:ff9b::7f00:1"))).err.code).toBe("EPRIVATE");
expect((await lookupOnce(fixed())).err.code).toBe("ENOTFOUND");
expect((await lookupOnce(async () => { throw Object.assign(new Error("dns down"), { code: "ESERVFAIL" }); })).err.code).toBe("ESERVFAIL");
expect((await lookupOnce(fixed("93.184.216.34"))).a).toEqual([{ address: "93.184.216.34", family: 4 }]);
expect(await lookupOnce(fixed("93.184.216.34"), {})).toMatchObject({ err: null, a: "93.184.216.34", f: 4 });
});
it("connects only to the address it validated and returns a streaming Response", async () => {
const { request, calls } = fakeRequest(() => ({ status: 200, headers: { "content-type": "application/rss+xml", "set-cookie": ["a=1", "b=2"] }, body: "<rss/>" }));
const res = await pinnedFetch({ resolver: fixed("93.184.216.34"), request })("https://feeds.rebind.example/feed.xml?x=1", { headers: { accept: "application/rss+xml" } });
expect(calls[0]).toMatchObject({ hostname: "feeds.rebind.example", servername: "feeds.rebind.example", path: "/feed.xml?x=1", connectedTo: "93.184.216.34" });
expect(calls[0].headers).toMatchObject({ accept: "application/rss+xml" });
expect(res.status).toBe(200);
expect(res.headers.get("content-type")).toBe("application/rss+xml");
expect(await res.text()).toBe("<rss/>");
});
it("closes the DNS-rebinding window: a host that passed the pre-check is refused when it now resolves privately", async () => {
const resolver = rebinding();
expect(await nonPublicHosts(["feeds.rebind.example"], resolver)).toEqual([]);
const { request, calls } = fakeRequest(() => ({ status: 200, body: "should not be read" }));
await expect(pinnedFetch({ resolver, request })("https://feeds.rebind.example/feed.xml")).rejects.toMatchObject({ code: "EPRIVATE" });
expect(calls[0].connectedTo).toBeUndefined();
});
it("never follows redirects, supports HEAD, refuses http and honours abort", async () => {
const { request } = fakeRequest(() => ({ status: 302, headers: { location: "https://other.example/x" } }));
const r = await pinnedFetch({ resolver: fixed("93.184.216.34"), request })("https://feeds.rebind.example/old");
expect(r.status).toBe(302);
expect(r.headers.get("location")).toBe("https://other.example/x");
const head = await pinnedFetch({ resolver: fixed("93.184.216.34"), request: fakeRequest(() => ({ status: 200, body: "x" })).request })("https://feeds.rebind.example/", { method: "HEAD" });
expect(head.body).toBeNull();
await expect(pinnedFetch({ resolver: fixed("93.184.216.34"), request })("http://feeds.rebind.example/")).rejects.toThrow(/https only/);
const ac = new AbortController();
ac.abort();
await expect(pinnedFetch({ resolver: fixed("93.184.216.34"), request })("https://feeds.rebind.example/", { signal: ac.signal })).rejects.toMatchObject({ name: "AbortError" });
});
});
describe("agent wiring: the real-network path uses the pinned fetch (no packets: refused at lookup)", () => {
it("fetch_pages reports a page whose host rebinds to a private address after the pre-check", async () => {
const out = await agent.call("fetch_pages", { urls: ["https://www.rebind.example/"], owned_hosts: ["www.rebind.example"] }, { lookup: rebinding() });
expect(out.fetched[0].error).toMatch(/Request failed: .*private, loopback or link-local/);
});
it("fetch_pages refuses a host whose answers include a 6to4 address of a private network", async () => {
await expect(agent.call("fetch_pages", { urls: ["https://www.rebind.example/"], owned_hosts: ["www.rebind.example"] }, { lookup: fixed("2606:4700::1", "2002:c0a8:101::1") })).rejects.toMatchObject({ code: "network_denied" });
});
});