What you will build
A safeFetch() wrapper for Node.js that you can hand arbitrary URLs — from users, RSS feeds or an AI agent — without letting those URLs reach your internal network or a cloud metadata endpoint.
Why string checks are not enough
Server-side request forgery (SSRF) occurs when an application fetches a remote resource without validating the user-supplied URL, letting an attacker make the server send requests to unexpected destinations — even ones protected by a firewall 1. Checking the hostname as a string fails in several ways:
- Alternate IP encodings. In Node.js,
new URL("http://2130706433/").hostnameandnew URL("http://0x7f.1/").hostnameboth return127.0.0.1, because the WHATWG URL parser normalizes numeric hosts. - DNS answers can change between the moment you check a hostname and the moment you connect; the OWASP cheat sheet discusses this under DNS pinning 2.
- Redirects. A harmless URL can redirect to a dangerous one 2.
- Cloud metadata. Addresses such as
169.254.169.254expose instance credentials on many cloud platforms and are a classic target 2.
The robust approach: validate the IP you actually connect to, every time you connect.
Prerequisites
Node.js (the built-in net and dns modules) and the undici package:
npm install undiciStep-by-step
1. Classify addresses with net.BlockList
net.BlockList lets you declare address ranges with addSubnet() and test an address with check() 3.
import { BlockList, isIP } from "node:net";
const blocked = new BlockList();
const v4: Array<[string, number]> = [
["0.0.0.0", 8],
["10.0.0.0", 8],
["100.64.0.0", 10],
["127.0.0.0", 8],
["169.254.0.0", 16],
["172.16.0.0", 12],
["192.168.0.0", 16],
];
const v6: Array<[string, number]> = [
["::1", 128],
["fc00::", 7],
["fe80::", 10],
];
for (const [network, prefix] of v4) blocked.addSubnet(network, prefix, "ipv4");
for (const [network, prefix] of v6) blocked.addSubnet(network, prefix, "ipv6");
export function isPrivate(address: string): boolean {
const mapped = /^::ffff:(\d+\.\d+\.\d+\.\d+)$/i.exec(address);
const ip = mapped ? mapped[1] : address;
const family = isIP(ip);
if (family === 4) return blocked.check(ip, "ipv4");
if (family === 6) return blocked.check(ip, "ipv6");
return true; // not an IP address at all: treat as unsafe
}2. Validate DNS answers at connect time
Resolve and validate inside the connection's lookup hook, so the address you check is the address you connect to. undici's Agent accepts connection options for its socket connector, including a custom lookup 4.
import { lookup } from "node:dns";
import { Agent } from "undici";
import { isPrivate } from "./ip";
export const safeAgent = new Agent({
connect: {
lookup(hostname, options, callback) {
lookup(hostname, { ...options, all: true }, (error, addresses) => {
if (error) return callback(error, "", 0);
if (addresses.length === 0 || addresses.some((a) => isPrivate(a.address))) {
return callback(new Error(`Blocked non-public address for ${hostname}`), "", 0);
}
if (options.all) return callback(null, addresses);
callback(null, addresses[0].address, addresses[0].family);
});
},
},
});Treating a mixed answer (one public and one private address) as unsafe is deliberate — an attacker controls which record you would get.
3. Follow redirects manually and re-validate every hop
IP-literal hosts never go through DNS lookup, so check them before connecting. Then disable automatic redirects and validate each Location yourself.
import { isIP } from "node:net";
import { fetch } from "undici";
import { safeAgent } from "./agent";
import { isPrivate } from "./ip";
export async function safeFetch(input: string, maxRedirects = 5) {
let url = new URL(input);
for (let hop = 0; hop <= maxRedirects; hop++) {
if (url.protocol !== "http:" && url.protocol !== "https:") throw new Error("Blocked protocol");
if (url.username || url.password) throw new Error("Credentials in URLs are not allowed");
const host = url.hostname.replace(/^\[|\]$/g, "");
if (host === "localhost" || (isIP(host) && isPrivate(host))) throw new Error("Blocked host");
const response = await fetch(url, {
dispatcher: safeAgent,
redirect: "manual",
signal: AbortSignal.timeout(15_000),
});
const location = response.headers.get("location");
if (response.status >= 300 && response.status < 400 && location) {
url = new URL(location, url);
continue;
}
return response;
}
throw new Error("Too many redirects");
}4. Cap time and size
Always set a timeout (as above), stop reading the body after a byte budget, and reject content types you do not expect. An unbounded response body is a denial-of-service vector even when the destination is legitimate.
Troubleshooting
| Symptom | Cause | Fix |
|---|---|---|
| A public site is blocked | Its DNS returns a mix of public and private records | Expected behavior — allow-list that host explicitly if you trust it |
| Requests hang | No timeouts | Use AbortSignal.timeout() and the agent's header/body timeouts |
| IPv6-only sites fail | The lookup hook ignores options.all | Return all addresses when options.all is set |
Next steps
- Prefer an allow-list of destinations whenever your use case allows it; the OWASP cheat sheet recommends allow-listing where the set of targets is known 2.
- Network controls are half the story for AI agents: the pages they fetch can also carry instructions aimed at your model. See Prompt Injection in RAG Pipelines.