Something went wrong. Try again.
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242// DNS-rebinding-safe fetch for user-supplied URLs.// Resolve once, reject private records, then dial the pinned address.
import dns from 'dns/promises';import http from 'http';import https from 'https';import { URL } from 'url';import { isIP } from 'net';import { isPrivateUrl, isPrivateAddress } from './ssrf';
const DEFAULT_TIMEOUT_MS = 15_000;const DEFAULT_MAX_BYTES = 2 * 1024 * 1024; // 2 MiBconst DEFAULT_MAX_REDIRECTS = 5;const REDIRECT_STATUS_CODES = new Set([301, 302, 303, 307, 308]);
export interface PinnedFetchOptions { method?: 'GET' | 'HEAD'; headers?: Record<string, string>; timeoutMs?: number; maxBytes?: number; maxRedirects?: number; allowedContentTypes?: string[]; // prefix match, e.g. 'text/html'}
export interface PinnedFetchResult { status: number; url: string; contentType: string; body: Buffer; truncated: boolean;}
class PinnedFetchError extends Error { statusCode?: number; constructor(message: string, statusCode?: number) { super(message); this.statusCode = statusCode; }}
// Resolve a hostname and refuse any response that includes a private address.// A literal IP in the URL is checked directly.async function resolvePinnedAddress(hostname: string): Promise<string> { if (isIP(hostname)) { if (isPrivateAddress(hostname)) { throw new PinnedFetchError('Requests to private/internal addresses are not allowed', 400); } return hostname; } const results = await dns.lookup(hostname, { all: true, verbatim: true }); if (results.length === 0) { throw new PinnedFetchError('DNS resolution failed', 502); } // If *any* record is private, refuse — defeats dual-answer rebinding tricks. for (const r of results) { if (isPrivateAddress(r.address)) { throw new PinnedFetchError('Requests to private/internal addresses are not allowed', 400); } } return results[0].address;}
function normaliseContentType(raw: string | undefined): string { return (raw || '').toLowerCase().split(';')[0].trim();}
function assertAllowedContentType(contentType: string, allowed: string[] | undefined): void { if (!allowed || allowed.length === 0) return; const normal = normaliseContentType(contentType); const ok = allowed.some((prefix) => normal.startsWith(prefix.toLowerCase())); if (!ok) { throw new PinnedFetchError(`Unsupported content-type: ${normal || 'unknown'}`, 415); }}
// Single hop, no redirect following. Caller implements redirect logic so each// hop is re-validated through the SSRF pipeline.function requestOnce( target: URL, pinnedAddress: string, opts: PinnedFetchOptions,): Promise<PinnedFetchResult & { location?: string }> { const isHttps = target.protocol === 'https:'; const transport = isHttps ? https : http; const port = target.port || (isHttps ? '443' : '80'); const headers: Record<string, string> = { host: target.host, ...(opts.headers || {}), }; const timeoutMs = opts.timeoutMs ?? DEFAULT_TIMEOUT_MS; const maxBytes = opts.maxBytes ?? DEFAULT_MAX_BYTES;
return new Promise((resolve, reject) => { let settled = false; const settle = (fn: () => void) => { if (settled) return; settled = true; fn(); };
const req = transport.request({ method: opts.method ?? 'GET', host: pinnedAddress, // Using `host` (IP) means TLS would ordinarily fail the SNI hostname // match — set servername explicitly so the cert is validated against // the original hostname. servername: isHttps ? target.hostname : undefined, port: Number(port), path: target.pathname + target.search, headers, timeout: timeoutMs, } as http.RequestOptions & { servername?: string });
req.on('error', (err) => settle(() => reject(new PinnedFetchError(err.message, 502)))); req.on('timeout', () => { req.destroy(); settle(() => reject(new PinnedFetchError('Request timed out', 504))); });
req.on('response', (res) => { const status = res.statusCode ?? 0; const contentType = (res.headers['content-type'] as string | undefined) || ''; const location = (res.headers['location'] as string | undefined) || undefined;
// Redirects: don't bother reading the body. if (REDIRECT_STATUS_CODES.has(status)) { res.resume(); settle(() => resolve({ status, url: target.toString(), contentType, body: Buffer.alloc(0), truncated: false, location, }), ); return; }
// 2xx/4xx/5xx: buffer up to maxBytes, then stop. try { assertAllowedContentType(contentType, opts.allowedContentTypes); } catch (err) { res.destroy(); settle(() => reject(err)); return; }
// Declared length check — cheap early reject before any bytes flow. const declaredLen = res.headers['content-length'] ? Number(res.headers['content-length']) : undefined; if (declaredLen !== undefined && declaredLen > maxBytes) { res.destroy(); settle(() => reject(new PinnedFetchError('Response too large', 413))); return; }
const chunks: Buffer[] = []; let total = 0; let truncated = false;
const finalize = () => { settle(() => resolve({ status, url: target.toString(), contentType, body: Buffer.concat(chunks), truncated, }), ); };
res.on('data', (chunk: Buffer) => { if (truncated) return; const remaining = maxBytes - total; if (chunk.length <= remaining) { chunks.push(chunk); total += chunk.length; return; } if (remaining > 0) chunks.push(chunk.subarray(0, remaining)); total += remaining; truncated = true; res.destroy(); finalize(); }); res.on('end', finalize); res.on('error', (err) => settle(() => reject(new PinnedFetchError(err.message, 502)))); });
req.end(); });}
// Fetches `url` with DNS resolution pinned per hop, a bounded body, optional// content-type allowlist, and manual redirect following (each hop re-validated// through `isPrivateUrl` + a fresh DNS lookup against the SSRF blocklist).export async function pinnedFetch(url: string, opts: PinnedFetchOptions = {}): Promise<PinnedFetchResult> { let current = new URL(url); const maxRedirects = opts.maxRedirects ?? DEFAULT_MAX_REDIRECTS;
for (let hop = 0; hop <= maxRedirects; hop += 1) { if (!['http:', 'https:'].includes(current.protocol)) { throw new PinnedFetchError('Invalid URL protocol', 400); } // Syntactic check first so literal private IPs / blocked DNS names are // caught without even resolving. if (isPrivateUrl(current)) { throw new PinnedFetchError('Requests to private/internal addresses are not allowed', 400); }
const pinned = await resolvePinnedAddress(current.hostname); const result = await requestOnce(current, pinned, opts);
if (REDIRECT_STATUS_CODES.has(result.status)) { if (hop === maxRedirects) { throw new PinnedFetchError('Too many redirects', 508); } if (!result.location) { throw new PinnedFetchError(`Redirect ${result.status} missing Location header`, 502); } current = new URL(result.location, current); continue; }
return { status: result.status, url: result.url, contentType: result.contentType, body: result.body, truncated: result.truncated, }; }
throw new PinnedFetchError('Too many redirects', 508);}
export { PinnedFetchError };