Skip to content

TutorialsTutorial

SSRF-Safe Fetching in Node.js: Validate DNS at Connect Time

If your app or AI agent fetches user-supplied URLs, string checks are not enough. Build a fetch wrapper that validates every resolved IP at connect time, re-checks redirects and caps responses.

AI Dev Hub Editorial

Automated quality gate

Published
Updated
Reading time
2 min read
  • 4 sources cited
  • 7 facts quote-verified

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/").hostname and new URL("http://0x7f.1/").hostname both return 127.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.254 expose 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:

bash
npm install undici

Step-by-step

1. Classify addresses with net.BlockList

net.BlockList lets you declare address ranges with addSubnet() and test an address with check() 3.

ts
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.

ts
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.

ts
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

SymptomCauseFix
A public site is blockedIts DNS returns a mix of public and private recordsExpected behavior — allow-list that host explicitly if you trust it
Requests hangNo timeoutsUse AbortSignal.timeout() and the agent's header/body timeouts
IPv6-only sites failThe lookup hook ignores options.allReturn 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.

Frequently asked questions

Is an allow-list better than a block-list for SSRF?

When the set of destinations is known, yes. Block-lists are the fallback for apps that must fetch arbitrary public URLs, such as feed readers and AI research agents.

Why validate IP addresses at connect time?

Because DNS answers can change between the moment you check a hostname and the moment you connect. Validating inside the connection lookup checks the address you actually use.

Does this stop every SSRF attack?

It removes the most common paths, but you should also restrict outbound traffic at the network level and keep response sizes and timeouts bounded.

Sources

Every factual claim above cites one of these documents, retrieved and snapshotted by our research pipeline.

  1. S1
    A10:2021 – Server-Side Request Forgery (SSRF)
    OWASPHighRetrieved Sep 30, 2026
  2. S2
    Server-Side Request Forgery Prevention Cheat Sheet
    OWASP Cheat Sheet SeriesHighRetrieved Sep 30, 2026
  3. S3
    Net — Node.js documentation
    Node.jsOfficialRetrieved Sep 30, 2026
  4. S4
    Undici — HTTP/1.1 client for Node.js
    Node.jsOfficialRetrieved Sep 30, 2026

TutorialsTutorial

Structured Outputs in TypeScript with the AI SDK and Zod

Stop parsing free-form model text. Define a Zod schema, request an object with Output.object and get validated, typed data back — plus the schema rules that keep strict providers happy.

2 min read

Frameworks & SDKsNews

OpenAI Python SDK v3.13.0 Introduces Agents API

OpenAI has released version 3.13.0 of its Python SDK, introducing a new Agents API. This update allows developers to integrate agent capabilities directly into their Python applications.

2 min readListen · 5 min