import type { DispatcherOptions, RequestOptions } from "../request.js"; import type EventEmitter from "node:events"; import type * as UndiciT from "undici"; import crypto from "node:crypto"; import path from "node:path"; import { mkdir } from "../fs.js"; import { isObject } from "../lang.js"; import { ConnectionRefusedError, DEFAULT_MAX_REDIRECTS, DEFAULT_TIMEOUT_IN_MILLISECONDS, DEFAULT_USER_AGENT, getDispatcher, InvalidProxyUrlError, isValidUrl, RequestTimeoutError, ResponseStatusCodeError, shouldUseProxy, } from "../request.js"; export interface ProxyEnvVar { name: string; value: string; } interface NoProxyEntry { hostname: string; port: number; } // We don't load undici on startup because this package is transitively imported // from too many places and it's too complex to optimize case by case. let undici: typeof UndiciT | undefined; const HTTPS_PROXY_ENV_VARS: string[] = ["https_proxy", "HTTPS_PROXY"]; const HTTP_PROXY_ENV_VARS: string[] = ["http_proxy", "HTTP_PROXY"]; const NO_PROXY_ENV_VARS: string[] = ["no_proxy", "NO_PROXY"]; // `URL` normalizes IPv6 loopback to `[::1]` and alternate IPv4 forms to // dotted decimal. Only IPv6 hostnames include brackets. const LOOPBACK_HOSTNAMES: Set = new Set([ "localhost", "0.0.0.0", "[::1]", ]); const DEFAULT_PORTS: Map = new Map([ ["http:", 80], ["https:", 443], ]); // Node tries each resolved address in turn, giving all but the last one only // 250ms by default. On hosts without IPv6, the IPv6 addresses fail instantly, // so a single lost SYN on IPv4 (resent after 1s) fails the whole request. // 1250ms leaves room for that resend plus the round trip. export const AUTO_SELECT_FAMILY_ATTEMPT_TIMEOUT_IN_MILLISECONDS = 1250; export async function generateTempFilePath(filePath: string): Promise { const { dir, ext, name } = path.parse(filePath); await mkdir(dir); return path.format({ dir, ext, name: `tmp-${name}-${crypto.randomBytes(8).toString("hex")}`, }); } export async function getBaseRequestOptions( requestUrl: string, { extraHeaders, abortSignal, queryParams }: RequestOptions = {}, dispatcherOrDispatcherOptions?: UndiciT.Dispatcher | DispatcherOptions, ): Promise<{ query?: Record | undefined; signal?: EventEmitter | AbortSignal | undefined; dispatcher: UndiciT.Dispatcher; headers: Record; }> { if (undici === undefined) { undici = await import("undici"); } const dispatcher = dispatcherOrDispatcherOptions instanceof undici.Dispatcher ? dispatcherOrDispatcherOptions : await getDispatcher(requestUrl, dispatcherOrDispatcherOptions); // We always build our own dispatcher instead of letting undici fall back to // the global one, which is a bare `new Agent()` and would drop our timeouts. // Configuring it with `setGlobalDispatcher` would affect the whole process. // https://github.com/nodejs/undici/blob/v7.29.0/lib/global.js#L10-L12 return { dispatcher: dispatcher.compose( undici.interceptors.redirect({ maxRedirections: DEFAULT_MAX_REDIRECTS }), // responseError is what makes 4xx and 5xx responses throw undici.interceptors.responseError(), ), headers: getHeaders(requestUrl, extraHeaders), ...(abortSignal !== undefined ? { signal: abortSignal } : {}), ...(queryParams !== undefined ? { query: queryParams } : {}), }; } export function getHeaders( requestUrl: string, extraHeaders: Record = {}, ): Record { const headers: Record = { ...extraHeaders, "User-Agent": extraHeaders["User-Agent"] ?? DEFAULT_USER_AGENT, }; const authHeader = getAuthHeader(requestUrl); if (authHeader !== undefined) { headers.Authorization = authHeader; } return headers; } export function getAuthHeader(requestUrl: string): string | undefined { const parsedUrl = new URL(requestUrl); if (parsedUrl.username === "") { return undefined; } return `Basic ${Buffer.from( `${parsedUrl.username}:${parsedUrl.password}`, ).toString("base64")}`; } /** * Determines whether a url points at the loopback interface. */ export function isLoopbackUrl(parsedUrl: URL): boolean { const hostname = parsedUrl.hostname.toLowerCase(); if (LOOPBACK_HOSTNAMES.has(hostname)) { return true; } // Subdomains of localhost, e.g. `api.localhost`. if (hostname.endsWith(".localhost")) { return true; } // The whole 127.0.0.0/8 range is loopback, not just 127.0.0.1. return /^127(?:\.\d{1,3}){3}$/.test(hostname); } /** * Determines whether `NO_PROXY` (or `no_proxy`) excludes a url from being * proxied. A value of `*` excludes everything; the other entries are matched as * described in {@link parseNoProxy}. */ export function isExcludedByNoProxy(parsedUrl: URL): boolean { // An empty or whitespace-only value means unset, so it falls through to the // other casing instead of shadowing it. const noProxy = NO_PROXY_ENV_VARS.map((name) => process.env[name]?.trim(), ).find((value) => value !== undefined && value !== ""); if (noProxy === undefined) { return false; } if (noProxy === "*") { return true; } const hostname = normalizeHostname(parsedUrl.hostname); const parsedPort = Number.parseInt(parsedUrl.port, 10); const port = Number.isNaN(parsedPort) ? DEFAULT_PORTS.get(parsedUrl.protocol) : parsedPort; for (const entry of parseNoProxy(noProxy)) { // A portless entry matches every port. if (entry.port !== 0 && entry.port !== port) { continue; } if ( hostname === entry.hostname || hostname.endsWith(`.${entry.hostname}`) ) { return true; } } return false; } /** * Finds the environment variable that configures the proxy for a given url, * following the usual precedence: the variable matching the url's protocol * first, lowercase before uppercase, then the other protocol's as a fallback. * * Empty and whitespace-only values are treated as unset, as that's how users * disable a variable inherited from a parent environment. The returned value is * trimmed, but not validated. * * @param requestUrl The url the proxy would be used for. * @returns The variable's name and value, or `undefined` if none is set or the * url's protocol isn't proxyable. */ export function findProxyEnvVar(requestUrl: string): ProxyEnvVar | undefined { const { protocol } = new URL(requestUrl); let names: string[]; if (protocol === "https:") { names = HTTPS_PROXY_ENV_VARS.concat(HTTP_PROXY_ENV_VARS); } else if (protocol === "http:") { names = HTTP_PROXY_ENV_VARS.concat(HTTPS_PROXY_ENV_VARS); } else { return undefined; } for (const name of names) { const value = process.env[name]?.trim(); if (value !== undefined && value !== "") { return { name, value }; } } return undefined; } /** * Resolves the proxy to use for a given url from the environment. * * @param requestUrl The url the proxy would be used for. * @returns The proxy url, or `undefined` if the environment configures none, * `NO_PROXY` excludes the url, or the url can't be proxied. * @throws InvalidProxyUrlError If the configured proxy isn't a valid http(s) url. */ export function resolveProxyFromEnv(requestUrl: string): string | undefined { // `shouldUseProxy` and `findProxyEnvVar` both parse the url. Requests to an // invalid one fail later with a better error than anything we'd raise here. if (!isValidUrl(requestUrl) || !shouldUseProxy(requestUrl)) { return undefined; } const proxyEnvVar = findProxyEnvVar(requestUrl); if (proxyEnvVar === undefined) { return undefined; } if (!isValidProxyUrl(proxyEnvVar.value)) { throw new InvalidProxyUrlError(proxyEnvVar.name); } return proxyEnvVar.value; } /** * Determines whether a value can be used as a proxy url. * * undici's `ProxyAgent` only speaks http(s). Checking the protocol here, rather * than leaving it to undici, catches two cases that would otherwise surface as * opaque errors: a scheme-less `host:port`, which parses as a url whose * protocol is the host and so never looks like a missing scheme, and `socks5:`, * which undici accepts before failing at request time. */ function isValidProxyUrl(value: string): boolean { if (!isValidUrl(value)) { return false; } const { protocol } = new URL(value); return protocol === "http:" || protocol === "https:"; } export async function getProxyDispatcher( proxy: string, options: Omit, ): Promise { if (undici === undefined) { undici = await import("undici"); } // TODO: ProxyAgent connects to the proxy with its own connector, built from // `proxyTls`, so the `autoSelectFamily` options from `getBaseDispatcherOptions` // don't reach that connection. return new undici.ProxyAgent({ uri: proxy, ...options, }); } export async function getPoolDispatcher( requestUrl: string, options: UndiciT.Pool.Options, ): Promise { if (undici === undefined) { undici = await import("undici"); } const parsedUrl = new URL(requestUrl); return new undici.Pool(parsedUrl.origin, options); } export async function getBasicDispatcher( options: UndiciT.Agent.Options, ): Promise { if (undici === undefined) { undici = await import("undici"); } return new undici.Agent(options); } export function getBaseDispatcherOptions( timeout: number = DEFAULT_TIMEOUT_IN_MILLISECONDS, isTestDispatcher: boolean = false, ): UndiciT.Client.Options { // These have good defaults for production, but need to be tweaked to avoid hanging tests. // https://github.com/nodejs/undici/blob/v7.29.0/docs/docs/best-practices/writing-tests.md const keepAliveTimeouts = isTestDispatcher ? { keepAliveTimeout: 10, keepAliveMaxTimeout: 10 } : {}; return { headersTimeout: timeout, bodyTimeout: timeout, connectTimeout: timeout, // `true` is already Node's default, but undici only forwards the attempt // timeout when `autoSelectFamily` is set autoSelectFamily: true, autoSelectFamilyAttemptTimeout: AUTO_SELECT_FAMILY_ATTEMPT_TIMEOUT_IN_MILLISECONDS, ...keepAliveTimeouts, }; } export function sanitizeUrl(requestUrl: string): string { const parsedUrl = new URL(requestUrl); // Return only the origin to avoid leaking sensitive information return parsedUrl.origin; } export function handleError(e: Error, requestUrl: string): void { let causeCode: unknown; if (isObject(e.cause)) { causeCode = e.cause.code; } const errorCode = "code" in e ? e.code : causeCode; if (errorCode === "ECONNREFUSED") { throw new ConnectionRefusedError(requestUrl, e); } if ( errorCode === "UND_ERR_CONNECT_TIMEOUT" || errorCode === "UND_ERR_HEADERS_TIMEOUT" || errorCode === "UND_ERR_BODY_TIMEOUT" ) { throw new RequestTimeoutError(requestUrl, e); } if (errorCode === "UND_ERR_RESPONSE") { describeResponseError(e); throw new ResponseStatusCodeError(requestUrl, e); } } /** * Restores the message that undici used to produce for status code errors. * * Until v7, undici's `throwOnError` described the failure as * `Response status code : `. The `responseError` interceptor that * replaced it always uses the generic "Response Error" instead, dropping the * only actionable part of the message. Consumers surface this message to users, * so we describe the error again. */ function describeResponseError(e: Error): void { if (e.message !== "Response Error") { return; } const statusCode = "statusCode" in e ? e.statusCode : undefined; if (typeof statusCode !== "number") { return; } // Importing `node:http` loads Node's whole HTTP stack, so we defer // using `process.getBuiltinModule` as a dynamic load. const reason = process.getBuiltinModule("node:http").STATUS_CODES[statusCode]; e.message = `Response status code ${statusCode}${ reason !== undefined ? `: ${reason}` : "" }`; } /** * Strips the brackets an IPv6 literal carries in a url, so that an entry can be * written either way. `URL` keeps them on `hostname`, while `NO_PROXY` entries * are commonly written without them. */ function normalizeHostname(hostname: string): string { return hostname.replace(/^\[|\]$/g, "").toLowerCase(); } /** * Parses a `NO_PROXY` value into its entries. * * Entries are separated by commas or whitespace. A leading `.` or `*.` marks * the suffix form (`.example.com`), but a bare `example.com` matches its * subdomains too, so both are stored the same way. An entry may carry a port, * as in `example.com:8080`, which restricts it to that port. CIDR ranges aren't * supported. */ function parseNoProxy(noProxy: string): NoProxyEntry[] { const entries: NoProxyEntry[] = []; for (const rawEntry of noProxy.split(/[,\s]/)) { const entry = rawEntry.trim(); if (entry === "") { continue; } // Only a bracketed literal or a colon-free host can carry a port, so that // the trailing group of a bare IPv6 entry isn't read as one. const withPort = entry.match(/^(\[[^\]]+\]|[^:]+):(\d+)$/); entries.push({ hostname: normalizeHostname( (withPort !== null ? withPort[1] : entry).replace(/^\*?\./, ""), ), port: withPort !== null ? Number.parseInt(withPort[2], 10) : 0, }); } return entries; }