ssrf-guard
v2.2.0
Published
SSRF protection: validate URLs, pin resolved IPs to the socket, eliminating the DNS-rebind window
Readme
ssrf-guard
SSRF protection for Node.js and Cloudflare Workers.
The key differentiator: validateUrl returns the resolved IP addresses so you can pin them directly to the socket — eliminating the TOCTOU/DNS-rebind window that exists between a validation step and the actual fetch. safeFetch does this automatically.
Unlike request-filtering-agent, ssrf-guard exposes the resolved addresses to the caller, letting you reuse them across retries or pass them to your own HTTP client.
Installation
pnpm add ssrf-guardRequires Node.js ≥ 24. The ssrf-guard entry point (isPrivateIp, validateResolvedAddresses, etc.) is pure and also runs in Cloudflare Workers. The ssrf-guard/node entry point requires Node.js and uses node:dns, node:net, and undici.
Quick start
Check whether an IP is private (core, works everywhere)
import { isPrivateIp, isPublicHostname } from "ssrf-guard";
isPrivateIp("127.0.0.1"); // true
isPrivateIp("10.0.0.1"); // true
isPrivateIp("::ffff:10.0.0.1"); // true (IPv4-mapped IPv6)
isPrivateIp("0x7f000001"); // true (hex form of 127.0.0.1)
isPrivateIp("8.8.8.8"); // false
isPublicHostname("example.com"); // true
isPublicHostname("localhost"); // false
isPublicHostname("foo.localhost"); // false
isPublicHostname("10.0.0.1"); // falseValidate a URL and get pinned addresses (Node.js)
import { validateUrl } from "ssrf-guard/node";
const addresses = await validateUrl("https://example.com/", {
blockedHostnames: {
exact: ["metadata.google.internal"],
suffixes: [".local", ".internal"],
},
});
// addresses: [{ address: '93.184.216.34', family: 4 }]
// Now use those addresses to build a pinned dispatcher — DNS won't be
// queried again so rebinding between check and fetch is impossible.Safe fetch with automatic pinning (Node.js)
import { safeFetch } from "ssrf-guard/node";
const response = await safeFetch("https://example.com/image.png", {
blockedHostnames: {
exact: ["metadata.google.internal"],
suffixes: [".internal"],
},
headers: { "user-agent": "my-crawler/1.0" },
});safeFetch resolves DNS once, validates the result, pins the addresses to the socket via an undici Agent, and follows redirects — re-validating each hop.
Both APIs always block localhost, localhost subdomains, and .local hostnames; a supplied
blockedHostnames policy adds to that baseline rather than replacing it.
API reference
ssrf-guard (core — pure, no Node built-ins)
isPrivateIp(ip: string): boolean
Returns true if ip is a private, loopback, link-local, unspecified, multicast, reserved, or other special-use address. Handles all RFC-legal IPv4 forms (dotted decimal, octal components, hex components, integer), IPv6, IPv4-mapped IPv6 (::ffff:), the deprecated IPv4-compatible block (::/96, e.g. ::7f00:1), and special-use IPv6 ranges such as ULA, link-local, documentation, discard, NAT64, 6to4, and Teredo.
false means only that ip is not a private address. A string that is not an IP address at all, such as example.com or 127.0.0.1., also returns false. To fetch a URL safely, use safeFetch, or validateUrl and pin the addresses it returns. isPublicHostname is only a preliminary check: it does not resolve DNS, so a public-looking hostname can still point at a private address.
normalizeUrlHostname(hostname: string): string
Lowercases, strips trailing dots, and unwraps brackets from IPv6 hostnames as extracted from a URL object.
isBlockedHostname(hostname: string, policy: BlockedHostnamePolicy): boolean
Returns true if hostname matches an exact entry or a suffix in policy.
mergeBlockedHostnamePolicies(...policies: BlockedHostnamePolicy[]): BlockedHostnamePolicy
Returns the union of exact and suffix hostname entries from the supplied policies.
isPublicHostname(hostname: string, options?: PublicHostnameOptions): boolean
Returns true for DNS-free public host checks. It normalizes case/trailing dots/IPv6 brackets, rejects private or special-use IP literals, applies a blocked-hostname policy, and rejects single-label hostnames unless allowSingleLabel: true is set.
By default it uses LOCALHOST_BLOCKED_HOSTNAME_POLICY, which blocks localhost, *.localhost, and *.local.
interface PublicHostnameOptions {
blockedHostnames?: BlockedHostnamePolicy;
allowSingleLabel?: boolean;
}validateResolvedAddresses<T>(rawUrl, hostname, addresses): T[]
Filters out null-route addresses (0.0.0.0, ::), throws UnsafeResolvedAddressError for private IPs and for any address that is not a valid IP, and throws with code: DNS_NULL_ROUTE_CODE when no usable addresses remain.
UnsafeResolvedAddressError
Thrown by validateResolvedAddresses. Properties: rawUrl: string, address: string, code: "private_address" | "invalid_resolved_address". rawUrl and the message carry the URL with userinfo masked and the query string and fragment removed.
DNS_NULL_ROUTE_CODE
String constant 'DNS_NULL_ROUTE' — the code property on the error thrown when DNS resolves only to null-route addresses.
BlockedHostnamePolicy
interface BlockedHostnamePolicy {
exact: readonly string[];
suffixes: readonly string[];
}ResolvedSafeAddress
interface ResolvedSafeAddress {
address: string;
family: 4 | 6;
}ssrf-guard/node (Node.js ≥ 24 only)
validateUrl(rawUrl: string, options?: ValidateUrlOptions): Promise<ResolvedSafeAddress[]>
Validates a URL and returns the resolved addresses:
- Parses the URL — throws
UnsafeUrlErrorfor invalid URLs. - Rejects protocols outside
allowedProtocols(bothhttp:andhttps:by default). - Checks against the localhost baseline plus the optional
blockedHostnamespolicy. - Rejects literal private IP addresses without DNS lookup.
- Resolves DNS and validates all returned addresses.
interface ValidateUrlOptions {
blockedHostnames?: BlockedHostnamePolicy;
allowedProtocols?: readonly ("http:" | "https:")[];
timeoutMs?: number;
signal?: AbortSignal;
}AllowedProtocol is the exported union type "http:" | "https:" used by both option objects.
safeFetch(initialUrl: string | URL, options?: SafeFetchOptions): Promise<Response>
Fetches a URL safely:
- Validates and pins DNS addresses before each hop.
- Follows redirects up to
maxRedirects(default: 10), re-validating each. - On a redirect to another origin, drops
authorization,cookie,cookie2, andproxy-authorization, plus any header named incrossOriginStripHeaders(case-insensitive). List custom credential headers such asx-api-keythere, or they are sent to the new origin. Once dropped, a header stays dropped for the rest of the redirects. - Gives up with a
TimeoutErrorif the final response headers have not arrived withintimeoutMs(default: 30 000). The deadline covers DNS, connecting, and every redirect hop. It stops oncesafeFetchreturns, so it does not cut off a long download; instead the body fails if no data arrives fortimeoutMs. - Fails the body read once more than
maxResponseBytes(default: 10 MiB) have arrived, with aTypeErrorwhosecause.codeisUND_ERR_RES_EXCEEDED_MAX_SIZE. The limit counts bytes on the wire, before decompression, so a small gzip or brotli body can decode to far more than this. If you read the whole body into memory, cap the decoded size yourself while you read it, or sendaccept-encoding: identityso that the server sends it uncompressed. - Pass
InfinityfortimeoutMsormaxResponseBytesto turn that limit off. - Passes remaining
RequestInitoptions through toundici.
interface SafeFetchOptions extends Omit<RequestInit, "signal"> {
blockedHostnames?: BlockedHostnamePolicy;
allowedProtocols?: readonly ("http:" | "https:")[];
maxRedirects?: number;
crossOriginStripHeaders?: readonly string[];
timeoutMs?: number;
maxResponseBytes?: number;
signal?: AbortSignal;
}createPinnedDispatcher(resolvedAddresses: NonEmptyResolvedSafeAddresses, options?: PinnedDispatcherOptions): Agent
Creates an undici Agent whose lookup callback is hardwired to the provided addresses, preventing any further DNS resolution.
PinnedDispatcherOptions accepts connections, headersTimeout, bodyTimeout,
keepAliveTimeout, keepAliveMaxTimeout, maxResponseSize, and connect: { timeout?: number }, which are passed to
Undici while the dispatcher keeps its pinned DNS lookup. PinnedDispatcherCacheOptions adds
maxSize.
createPinnedDispatcherCache(options?): PinnedDispatcherCache
Creates a small LRU cache for pinned undici dispatchers. This is useful for crawlers that validate DNS once per request but want to reuse sockets for repeated requests to the same validated address set.
const cache = createPinnedDispatcherCache({
maxSize: 100,
connections: 5,
headersTimeout: 10_000,
bodyTimeout: 30_000,
keepAliveTimeout: 5_000,
keepAliveMaxTimeout: 60_000,
connect: { timeout: 5_000 },
});
const dispatcher = cache.get(resolvedAddresses);
await cache.close();After close() begins, the cache is terminal: get() throws and repeated close() calls share the
same best-effort shutdown.
UnsafeUrlError
Thrown by validateUrl and safeFetch. Properties: rawUrl: string, reason: string, code: UnsafeUrlErrorCode. rawUrl and the message carry the URL with userinfo masked and the query string and fragment removed.
Branch on code, not reason: the codes stay the same across releases, while reason is wording for people and may change.
| code | Thrown when |
| -------------------------- | ------------------------------------------------------------------------------------------- |
| invalid_url | The URL cannot be parsed. |
| protocol_not_allowed | The protocol is not http: or https:, or not in allowedProtocols. |
| hostname_not_allowed | The hostname is localhost, ends in .localhost or .local, or is in blockedHostnames. |
| private_address | The host is a private IP address, or DNS resolved it to one. |
| invalid_resolved_address | DNS returned something that is not an IP address. |
| invalid_redirect | safeFetch got a redirect with no Location header or one it cannot parse. |
| too_many_redirects | safeFetch followed more than maxRedirects redirects. |
code is undefined only on an UnsafeUrlError that you construct yourself without one. When every address is a null route, validateUrl throws a different error, with code: DNS_NULL_ROUTE_CODE.
License
MIT
