src/hosts.js
// SSRF guard for fetch_pages: owned_hosts must be public DNS names (no IP literals, localhost or
// local/intranet suffixes) and, on the real network, must resolve only to public addresses.
import { isIP } from "node:net";
import { lookup as dnsLookup } from "node:dns/promises";
import { request as httpsRequest } from "node:https";
import { Readable } from "node:stream";
import { AgentError } from "../sdk/index.js";
const BLOCKED_SUFFIXES = [".localhost", ".local", ".internal", ".lan", ".home", ".corp", ".intranet", ".arpa"];
/** Throws invalid_input unless every host is a public-looking DNS name; returns them lower-cased. */
export function checkOwnedHosts(list) {
const out = [];
for (const raw of list) {
const h = String(raw).trim().toLowerCase().replace(/\.$/, "");
if (isIP(h.replace(/^\[|\]$/g, "")) !== 0) throw new AgentError("invalid_input", `owned_hosts: IP addresses are not accepted ("${h.slice(0, 80)}"); list the site's host name.`);
if (h === "localhost" || BLOCKED_SUFFIXES.some((s) => h.endsWith(s)) || !/\.[a-z][a-z0-9-]*[a-z0-9]$/.test(h)) {
throw new AgentError("invalid_input", `owned_hosts: "${h.slice(0, 80)}" is not a public DNS host name (local and intranet names are refused).`);
}
if (!out.includes(h)) out.push(h);
}
return out;
}
// ---------------------------------------------------------------------------------------------
// Address classification and connect-time pinning (security review 2026-11-26, finding F10b).
// Zero dependencies: node:net, node:dns, node:https and node:stream only.
// ---------------------------------------------------------------------------------------------
function privateV4(ip) {
const [a, b, c] = ip.split(".").map(Number);
return (
a === 0 || a === 10 || a === 127 || (a === 169 && b === 254) || (a === 172 && b >= 16 && b <= 31) ||
(a === 192 && b === 168) || (a === 100 && b >= 64 && b <= 127) || a >= 224 ||
(a === 192 && b === 0 && c === 0) || (a === 198 && (b === 18 || b === 19))
);
}
/** Expands any IPv6 text form (including a dotted IPv4 tail and a zone id) to 8 numbers, or null. */
export function v6Hextets(ip) {
let s = String(ip).toLowerCase().replace(/%.*$/, "");
const tail = /^(.*:)(\d+\.\d+\.\d+\.\d+)$/.exec(s);
if (tail) {
if (isIP(tail[2]) !== 4) return null;
const [a, b, c, d] = tail[2].split(".").map(Number);
s = `${tail[1]}${((a << 8) | b).toString(16)}:${((c << 8) | d).toString(16)}`;
}
const halves = s.split("::");
if (halves.length > 2) return null;
const left = halves[0] ? halves[0].split(":") : [];
const right = halves.length === 2 && halves[1] ? halves[1].split(":") : [];
const fill = halves.length === 2 ? 8 - left.length - right.length : 0;
if (fill < 0 || (halves.length === 2 && fill === 0)) return null;
const parts = [...left, ...Array(fill).fill("0"), ...right];
if (parts.length !== 8 || parts.some((p) => !/^[0-9a-f]{1,4}$/.test(p))) return null;
return parts.map((p) => parseInt(p, 16));
}
const v4Of = (hi, lo) => `${hi >> 8}.${hi & 255}.${lo >> 8}.${lo & 255}`;
/**
* True for loopback, private, link-local, CGNAT, multicast and reserved IPv4 ranges, and for IPv6 that is
* loopback/unspecified, unique-local (fc00::/7), link-local or site-local (fe80::/10, fec0::/10), multicast,
* discard (100::/64), or that embeds or translates to such an IPv4 address: IPv4-mapped (any notation),
* IPv4-compatible, NAT64 (64:ff9b::/96) and 6to4 (2002::/16). Unparseable input counts as private.
*/
export function isPrivateIp(ip) {
if (isIP(ip) === 4) return privateV4(ip);
const h = v6Hextets(ip);
if (!h) return true;
const zeroTo = (n) => h.slice(0, n).every((x) => x === 0);
if (zeroTo(7) && (h[7] === 0 || h[7] === 1)) return true;
if (zeroTo(5) && h[5] === 0xffff) return privateV4(v4Of(h[6], h[7]));
if (zeroTo(6)) return privateV4(v4Of(h[6], h[7]));
if (h[0] === 0x64 && h[1] === 0xff9b && h.slice(2, 6).every((x) => x === 0)) return privateV4(v4Of(h[6], h[7]));
if (h[0] === 0x2002) return privateV4(v4Of(h[1], h[2]));
if (h[0] === 0x100 && h.slice(1, 4).every((x) => x === 0)) return true;
if ((h[0] & 0xfe00) === 0xfc00) return true;
if ((h[0] & 0xffc0) === 0xfe80 || (h[0] & 0xffc0) === 0xfec0) return true;
if ((h[0] & 0xff00) === 0xff00) return true;
return false;
}
/**
* A `lookup` for node:https that resolves once, refuses the connection when ANY answer is private and
* hands the socket exactly the address it checked. Used at connect time, it closes the DNS-rebinding gap
* between "check the host" and "fetch" (the fetch would otherwise resolve again).
*/
export function safeLookup(resolver = dnsLookup) {
return (hostname, options, cb) => {
const all = typeof options === "object" && options !== null && options.all === true;
Promise.resolve()
.then(() => resolver(hostname, { all: true, verbatim: true }))
.then((addrs) => {
if (!Array.isArray(addrs) || !addrs.length) return cb(Object.assign(new Error(`${hostname} did not resolve`), { code: "ENOTFOUND" }), all ? [] : "", 4);
if (addrs.some((a) => isPrivateIp(a.address))) return cb(Object.assign(new Error(`${hostname} resolves to a private, loopback or link-local address; connection refused`), { code: "EPRIVATE" }), all ? [] : "", 4);
if (all) return cb(null, addrs.map((a) => ({ address: a.address, family: a.family })));
cb(null, addrs[0].address, addrs[0].family);
})
.catch((e) => cb(e, all ? [] : "", 4));
};
}
const NULL_BODY = new Set([101, 103, 204, 205, 304]);
/**
* fetch-compatible GET/HEAD over node:https whose TCP connection only ever goes to an address that
* safeLookup validated. It never follows redirects (the caller and the SDK re-check every hop), keeps TLS
* certificate checks on, and streams the body so callers' size caps apply. deps.request is for tests.
*/
export function pinnedFetch({ resolver = dnsLookup, request } = {}) {
return async (url, init = {}) => {
const u = new URL(String(url));
if (u.protocol !== "https:") throw Object.assign(new Error("pinnedFetch: https only"), { code: "EPROTO" });
const doRequest = request ?? httpsRequest;
const headers = {};
new Headers(init.headers ?? {}).forEach((v, k) => {
headers[k] = v;
});
return new Promise((resolve, reject) => {
const signal = init.signal;
let req;
const onAbort = () => req?.destroy(Object.assign(new Error("The operation was aborted"), { name: "AbortError" }));
if (signal?.aborted) return reject(Object.assign(new Error("The operation was aborted"), { name: "AbortError" }));
req = doRequest(
{ method: init.method ?? "GET", protocol: "https:", hostname: u.hostname, port: u.port || 443, path: `${u.pathname}${u.search}`, headers, lookup: safeLookup(resolver), servername: u.hostname },
(res) => {
const out = new Headers();
for (const [k, v] of Object.entries(res.headers ?? {})) {
if (Array.isArray(v)) v.forEach((x) => out.append(k, String(x)));
else if (v !== undefined) out.set(k, String(v));
}
const status = res.statusCode >= 200 && res.statusCode <= 599 ? res.statusCode : 502;
const body = NULL_BODY.has(status) || (init.method ?? "GET") === "HEAD" ? null : Readable.toWeb(res);
if (!body) res.resume?.();
signal?.removeEventListener?.("abort", onAbort);
if (signal) signal.addEventListener("abort", () => res.destroy?.(Object.assign(new Error("The operation was aborted"), { name: "AbortError" })), { once: true });
resolve(new Response(body, { status, headers: out }));
},
);
if (signal) signal.addEventListener("abort", onAbort, { once: true });
req.on("error", (e) => reject(e));
req.end();
});
};
}
/** Hosts whose DNS answers are not all public addresses (fails closed when a lookup fails). */
export async function nonPublicHosts(hosts, lookup = dnsLookup) {
const rejected = [];
for (const h of hosts) {
try {
const addrs = await lookup(h, { all: true, verbatim: true });
if (!addrs.length || addrs.some((a) => isPrivateIp(a.address))) rejected.push(h);
} catch {
rejected.push(h);
}
}
return rejected;
}