@nomicfoundation/hardhat-utils 4.1.9 → 4.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -3,6 +3,7 @@ import type EventEmitter from "node:events";
3
3
  import type * as UndiciT from "undici";
4
4
 
5
5
  import crypto from "node:crypto";
6
+ import { STATUS_CODES } from "node:http";
6
7
  import path from "node:path";
7
8
 
8
9
  import { mkdir } from "../fs.js";
@@ -13,14 +14,44 @@ import {
13
14
  DEFAULT_TIMEOUT_IN_MILLISECONDS,
14
15
  DEFAULT_USER_AGENT,
15
16
  getDispatcher,
17
+ InvalidProxyUrlError,
18
+ isValidUrl,
16
19
  RequestTimeoutError,
17
20
  ResponseStatusCodeError,
21
+ shouldUseProxy,
18
22
  } from "../request.js";
19
23
 
24
+ export interface ProxyEnvVar {
25
+ name: string;
26
+ value: string;
27
+ }
28
+
29
+ interface NoProxyEntry {
30
+ hostname: string;
31
+ port: number;
32
+ }
33
+
20
34
  // We don't load undici on startup because this package is transitively imported
21
35
  // from too many places and it's too complex to optimize case by case.
22
36
  let undici: typeof UndiciT | undefined;
23
37
 
38
+ const HTTPS_PROXY_ENV_VARS: string[] = ["https_proxy", "HTTPS_PROXY"];
39
+ const HTTP_PROXY_ENV_VARS: string[] = ["http_proxy", "HTTP_PROXY"];
40
+ const NO_PROXY_ENV_VARS: string[] = ["no_proxy", "NO_PROXY"];
41
+
42
+ // `URL` normalizes IPv6 loopback to `[::1]` and alternate IPv4 forms to
43
+ // dotted decimal. Only IPv6 hostnames include brackets.
44
+ const LOOPBACK_HOSTNAMES: Set<string> = new Set([
45
+ "localhost",
46
+ "0.0.0.0",
47
+ "[::1]",
48
+ ]);
49
+
50
+ const DEFAULT_PORTS: Map<string, number> = new Map([
51
+ ["http:", 80],
52
+ ["https:", 443],
53
+ ]);
54
+
24
55
  export async function generateTempFilePath(filePath: string): Promise<string> {
25
56
  const { dir, ext, name } = path.parse(filePath);
26
57
 
@@ -42,7 +73,6 @@ export async function getBaseRequestOptions(
42
73
  signal?: EventEmitter | AbortSignal | undefined;
43
74
  dispatcher: UndiciT.Dispatcher;
44
75
  headers: Record<string, string>;
45
- throwOnError: true;
46
76
  }> {
47
77
  if (undici === undefined) {
48
78
  undici = await import("undici");
@@ -53,13 +83,17 @@ export async function getBaseRequestOptions(
53
83
  ? dispatcherOrDispatcherOptions
54
84
  : await getDispatcher(requestUrl, dispatcherOrDispatcherOptions);
55
85
 
56
- // We could use the global dispatcher if neither dispatcher nor dispatcherOptions were passed,
57
- // but there's no way to configure it, so we don't do it.
58
- // https://github.com/nodejs/undici/blob/961b76ad7cac17d23580d172702e11a080974f5d/lib/global.js#L9
86
+ // We always build our own dispatcher instead of letting undici fall back to
87
+ // the global one, which is a bare `new Agent()` and would drop our timeouts.
88
+ // Configuring it with `setGlobalDispatcher` would affect the whole process.
89
+ // https://github.com/nodejs/undici/blob/v7.29.0/lib/global.js#L10-L12
59
90
  return {
60
- dispatcher,
91
+ dispatcher: dispatcher.compose(
92
+ undici.interceptors.redirect({ maxRedirections: DEFAULT_MAX_REDIRECTS }),
93
+ // responseError is what makes 4xx and 5xx responses throw
94
+ undici.interceptors.responseError(),
95
+ ),
61
96
  headers: getHeaders(requestUrl, extraHeaders),
62
- throwOnError: true,
63
97
  ...(abortSignal !== undefined ? { signal: abortSignal } : {}),
64
98
  ...(queryParams !== undefined ? { query: queryParams } : {}),
65
99
  };
@@ -93,6 +127,151 @@ export function getAuthHeader(requestUrl: string): string | undefined {
93
127
  ).toString("base64")}`;
94
128
  }
95
129
 
130
+ /**
131
+ * Determines whether a url points at the loopback interface.
132
+ */
133
+ export function isLoopbackUrl(parsedUrl: URL): boolean {
134
+ const hostname = parsedUrl.hostname.toLowerCase();
135
+
136
+ if (LOOPBACK_HOSTNAMES.has(hostname)) {
137
+ return true;
138
+ }
139
+
140
+ // Subdomains of localhost, e.g. `api.localhost`.
141
+ if (hostname.endsWith(".localhost")) {
142
+ return true;
143
+ }
144
+
145
+ // The whole 127.0.0.0/8 range is loopback, not just 127.0.0.1.
146
+ return /^127(?:\.\d{1,3}){3}$/.test(hostname);
147
+ }
148
+
149
+ /**
150
+ * Determines whether `NO_PROXY` (or `no_proxy`) excludes a url from being
151
+ * proxied. A value of `*` excludes everything; the other entries are matched as
152
+ * described in {@link parseNoProxy}.
153
+ */
154
+ export function isExcludedByNoProxy(parsedUrl: URL): boolean {
155
+ // An empty or whitespace-only value means unset, so it falls through to the
156
+ // other casing instead of shadowing it.
157
+ const noProxy = NO_PROXY_ENV_VARS.map((name) =>
158
+ process.env[name]?.trim(),
159
+ ).find((value) => value !== undefined && value !== "");
160
+
161
+ if (noProxy === undefined) {
162
+ return false;
163
+ }
164
+
165
+ if (noProxy === "*") {
166
+ return true;
167
+ }
168
+
169
+ const hostname = normalizeHostname(parsedUrl.hostname);
170
+ const parsedPort = Number.parseInt(parsedUrl.port, 10);
171
+ const port = Number.isNaN(parsedPort)
172
+ ? DEFAULT_PORTS.get(parsedUrl.protocol)
173
+ : parsedPort;
174
+
175
+ for (const entry of parseNoProxy(noProxy)) {
176
+ // A portless entry matches every port.
177
+ if (entry.port !== 0 && entry.port !== port) {
178
+ continue;
179
+ }
180
+
181
+ if (
182
+ hostname === entry.hostname ||
183
+ hostname.endsWith(`.${entry.hostname}`)
184
+ ) {
185
+ return true;
186
+ }
187
+ }
188
+
189
+ return false;
190
+ }
191
+
192
+ /**
193
+ * Finds the environment variable that configures the proxy for a given url,
194
+ * following the usual precedence: the variable matching the url's protocol
195
+ * first, lowercase before uppercase, then the other protocol's as a fallback.
196
+ *
197
+ * Empty and whitespace-only values are treated as unset, as that's how users
198
+ * disable a variable inherited from a parent environment. The returned value is
199
+ * trimmed, but not validated.
200
+ *
201
+ * @param requestUrl The url the proxy would be used for.
202
+ * @returns The variable's name and value, or `undefined` if none is set or the
203
+ * url's protocol isn't proxyable.
204
+ */
205
+ export function findProxyEnvVar(requestUrl: string): ProxyEnvVar | undefined {
206
+ const { protocol } = new URL(requestUrl);
207
+
208
+ let names: string[];
209
+ if (protocol === "https:") {
210
+ names = HTTPS_PROXY_ENV_VARS.concat(HTTP_PROXY_ENV_VARS);
211
+ } else if (protocol === "http:") {
212
+ names = HTTP_PROXY_ENV_VARS.concat(HTTPS_PROXY_ENV_VARS);
213
+ } else {
214
+ return undefined;
215
+ }
216
+
217
+ for (const name of names) {
218
+ const value = process.env[name]?.trim();
219
+
220
+ if (value !== undefined && value !== "") {
221
+ return { name, value };
222
+ }
223
+ }
224
+
225
+ return undefined;
226
+ }
227
+
228
+ /**
229
+ * Resolves the proxy to use for a given url from the environment.
230
+ *
231
+ * @param requestUrl The url the proxy would be used for.
232
+ * @returns The proxy url, or `undefined` if the environment configures none,
233
+ * `NO_PROXY` excludes the url, or the url can't be proxied.
234
+ * @throws InvalidProxyUrlError If the configured proxy isn't a valid http(s) url.
235
+ */
236
+ export function resolveProxyFromEnv(requestUrl: string): string | undefined {
237
+ // `shouldUseProxy` and `findProxyEnvVar` both parse the url. Requests to an
238
+ // invalid one fail later with a better error than anything we'd raise here.
239
+ if (!isValidUrl(requestUrl) || !shouldUseProxy(requestUrl)) {
240
+ return undefined;
241
+ }
242
+
243
+ const proxyEnvVar = findProxyEnvVar(requestUrl);
244
+
245
+ if (proxyEnvVar === undefined) {
246
+ return undefined;
247
+ }
248
+
249
+ if (!isValidProxyUrl(proxyEnvVar.value)) {
250
+ throw new InvalidProxyUrlError(proxyEnvVar.name);
251
+ }
252
+
253
+ return proxyEnvVar.value;
254
+ }
255
+
256
+ /**
257
+ * Determines whether a value can be used as a proxy url.
258
+ *
259
+ * undici's `ProxyAgent` only speaks http(s). Checking the protocol here, rather
260
+ * than leaving it to undici, catches two cases that would otherwise surface as
261
+ * opaque errors: a scheme-less `host:port`, which parses as a url whose
262
+ * protocol is the host and so never looks like a missing scheme, and `socks5:`,
263
+ * which undici accepts before failing at request time.
264
+ */
265
+ function isValidProxyUrl(value: string): boolean {
266
+ if (!isValidUrl(value)) {
267
+ return false;
268
+ }
269
+
270
+ const { protocol } = new URL(value);
271
+
272
+ return protocol === "http:" || protocol === "https:";
273
+ }
274
+
96
275
  export async function getProxyDispatcher(
97
276
  proxy: string,
98
277
  options: Omit<UndiciT.ProxyAgent.Options, "uri">,
@@ -134,7 +313,7 @@ export function getBaseDispatcherOptions(
134
313
  isTestDispatcher: boolean = false,
135
314
  ): UndiciT.Client.Options {
136
315
  // These have good defaults for production, but need to be tweaked to avoid hanging tests.
137
- // https://github.com/nodejs/undici/blob/961b76ad7cac17d23580d172702e11a080974f5d/docs/docs/best-practices/writing-tests.md
316
+ // https://github.com/nodejs/undici/blob/v7.29.0/docs/docs/best-practices/writing-tests.md
138
317
  const keepAliveTimeouts = isTestDispatcher
139
318
  ? { keepAliveTimeout: 10, keepAliveMaxTimeout: 10 }
140
319
  : {};
@@ -143,7 +322,6 @@ export function getBaseDispatcherOptions(
143
322
  headersTimeout: timeout,
144
323
  bodyTimeout: timeout,
145
324
  connectTimeout: timeout,
146
- maxRedirections: DEFAULT_MAX_REDIRECTS,
147
325
  ...keepAliveTimeouts,
148
326
  };
149
327
  }
@@ -173,7 +351,77 @@ export function handleError(e: Error, requestUrl: string): void {
173
351
  throw new RequestTimeoutError(requestUrl, e);
174
352
  }
175
353
 
176
- if (errorCode === "UND_ERR_RESPONSE_STATUS_CODE") {
354
+ if (errorCode === "UND_ERR_RESPONSE") {
355
+ describeResponseError(e);
177
356
  throw new ResponseStatusCodeError(requestUrl, e);
178
357
  }
179
358
  }
359
+
360
+ /**
361
+ * Restores the message that undici used to produce for status code errors.
362
+ *
363
+ * Until v7, undici's `throwOnError` described the failure as
364
+ * `Response status code <code>: <reason>`. The `responseError` interceptor that
365
+ * replaced it always uses the generic "Response Error" instead, dropping the
366
+ * only actionable part of the message. Consumers surface this message to users,
367
+ * so we describe the error again.
368
+ */
369
+ function describeResponseError(e: Error): void {
370
+ if (e.message !== "Response Error") {
371
+ return;
372
+ }
373
+
374
+ const statusCode = "statusCode" in e ? e.statusCode : undefined;
375
+ if (typeof statusCode !== "number") {
376
+ return;
377
+ }
378
+
379
+ const reason = STATUS_CODES[statusCode];
380
+
381
+ e.message = `Response status code ${statusCode}${
382
+ reason !== undefined ? `: ${reason}` : ""
383
+ }`;
384
+ }
385
+
386
+ /**
387
+ * Strips the brackets an IPv6 literal carries in a url, so that an entry can be
388
+ * written either way. `URL` keeps them on `hostname`, while `NO_PROXY` entries
389
+ * are commonly written without them.
390
+ */
391
+ function normalizeHostname(hostname: string): string {
392
+ return hostname.replace(/^\[|\]$/g, "").toLowerCase();
393
+ }
394
+
395
+ /**
396
+ * Parses a `NO_PROXY` value into its entries.
397
+ *
398
+ * Entries are separated by commas or whitespace. A leading `.` or `*.` marks
399
+ * the suffix form (`.example.com`), but a bare `example.com` matches its
400
+ * subdomains too, so both are stored the same way. An entry may carry a port,
401
+ * as in `example.com:8080`, which restricts it to that port. CIDR ranges aren't
402
+ * supported.
403
+ */
404
+ function parseNoProxy(noProxy: string): NoProxyEntry[] {
405
+ const entries: NoProxyEntry[] = [];
406
+
407
+ for (const rawEntry of noProxy.split(/[,\s]/)) {
408
+ const entry = rawEntry.trim();
409
+
410
+ if (entry === "") {
411
+ continue;
412
+ }
413
+
414
+ // Only a bracketed literal or a colon-free host can carry a port, so that
415
+ // the trailing group of a bare IPv6 entry isn't read as one.
416
+ const withPort = entry.match(/^(\[[^\]]+\]|[^:]+):(\d+)$/);
417
+
418
+ entries.push({
419
+ hostname: normalizeHostname(
420
+ (withPort !== null ? withPort[1] : entry).replace(/^\*?\./, ""),
421
+ ),
422
+ port: withPort !== null ? Number.parseInt(withPort[2], 10) : 0,
423
+ });
424
+ }
425
+
426
+ return entries;
427
+ }
package/src/request.ts CHANGED
@@ -15,6 +15,7 @@ import {
15
15
  } from "./errors/request.js";
16
16
  import { move, remove } from "./fs.js";
17
17
  import {
18
+ findProxyEnvVar,
18
19
  generateTempFilePath,
19
20
  getBaseDispatcherOptions,
20
21
  getBaseRequestOptions,
@@ -22,6 +23,9 @@ import {
22
23
  getPoolDispatcher,
23
24
  getProxyDispatcher,
24
25
  handleError,
26
+ isExcludedByNoProxy,
27
+ isLoopbackUrl,
28
+ resolveProxyFromEnv,
25
29
  } from "./internal/request.js";
26
30
 
27
31
  export const DEFAULT_TIMEOUT_IN_MILLISECONDS = 300_000; // Aligned with undici
@@ -41,7 +45,9 @@ let undici: typeof Undici | undefined;
41
45
  * Options to configure the dispatcher.
42
46
  *
43
47
  * @param timeout The timeout in milliseconds. Defaults to {@link DEFAULT_TIMEOUT_IN_MILLISECONDS}.
44
- * @param proxy The proxy to use. If not provided, no proxy is used.
48
+ * @param proxy The proxy to use. If not provided, it's resolved from the
49
+ * `https_proxy`/`HTTPS_PROXY` and `http_proxy`/`HTTP_PROXY` environment
50
+ * variables, unless `NO_PROXY` excludes the url or it points at loopback.
45
51
  * @param pool Whether to use a pool dispatcher. Defaults to `false`.
46
52
  * @param maxConnections The maximum number of connections to use in the pool. Defaults to {@link DEFAULT_POOL_MAX_CONNECTIONS}.
47
53
  * @param isTestDispatcher Whether to use a test dispatcher. Defaults to `false`. It's highly recommended to use a test dispatcher in tests to avoid hanging tests.
@@ -284,14 +290,21 @@ export async function download(
284
290
 
285
291
  /**
286
292
  * Creates a dispatcher based on the provided options.
287
- * If the `proxy` option is set, it creates a {@link Undici.ProxyAgent} dispatcher.
293
+ * If the `proxy` option is set, or a proxy is configured in the environment for
294
+ * the given url, it creates a {@link Undici.ProxyAgent} dispatcher.
288
295
  * If the `pool` option is set to `true`, it creates a {@link Undici.Pool} dispatcher.
289
296
  * Otherwise, it creates a basic {@link Undici.Agent} dispatcher.
290
297
  *
298
+ * A proxy resolved from the environment takes precedence over `pool`, as a
299
+ * {@link Undici.Pool} is bound to a single origin and can't tunnel. Set
300
+ * `NO_PROXY` to opt a host out, or pass a {@link Undici.Dispatcher} to the
301
+ * request helpers to bypass this entirely.
302
+ *
291
303
  * @param url The url to make requests to.
292
304
  * @param options The options to configure the dispatcher. See {@link DispatcherOptions}.
293
305
  * @returns The configured dispatcher instance.
294
- * @throws DispatcherError If the dispatcher can't be created.
306
+ * @throws DispatcherError If the dispatcher can't be created, including when the
307
+ * proxy configured in the environment isn't a valid url.
295
308
  */
296
309
  export async function getDispatcher(
297
310
  url: string,
@@ -304,15 +317,17 @@ export async function getDispatcher(
304
317
  }: DispatcherOptions = {},
305
318
  ): Promise<Dispatcher> {
306
319
  try {
307
- if (pool !== undefined && proxy !== undefined) {
320
+ if (pool === true && proxy !== undefined) {
308
321
  throw new Error(
309
322
  "The pool and proxy options can't be used at the same time",
310
323
  );
311
324
  }
312
325
  const baseOptions = getBaseDispatcherOptions(timeout, isTestDispatcher);
313
326
 
314
- if (proxy !== undefined) {
315
- return await getProxyDispatcher(proxy, baseOptions);
327
+ const resolvedProxy = proxy ?? resolveProxyFromEnv(url);
328
+
329
+ if (resolvedProxy !== undefined) {
330
+ return await getProxyDispatcher(resolvedProxy, baseOptions);
316
331
  }
317
332
 
318
333
  if (pool === true) {
@@ -345,26 +360,18 @@ export async function getTestDispatcher(
345
360
  /**
346
361
  * Determines whether a proxy should be used for a given url.
347
362
  *
363
+ * Loopback addresses are never proxied, so that a local node stays reachable
364
+ * when a proxy is configured for everything else. Beyond those, `NO_PROXY` (or
365
+ * `no_proxy`) is the opt-out: `*` disables proxying entirely, and every other
366
+ * entry is matched as described in {@link isExcludedByNoProxy}.
367
+ *
348
368
  * @param url The url to check.
349
369
  * @returns `true` if a proxy should be used for the url, `false` otherwise.
350
370
  */
351
371
  export function shouldUseProxy(url: string): boolean {
352
- const { hostname } = new URL(url);
353
- const noProxy = process.env.NO_PROXY;
354
-
355
- if (hostname === "localhost" || hostname === "127.0.0.1" || noProxy === "*") {
356
- return false;
357
- }
372
+ const parsedUrl = new URL(url);
358
373
 
359
- if (noProxy !== undefined && noProxy !== "") {
360
- const noProxySet = new Set(noProxy.split(","));
361
-
362
- if (noProxySet.has(hostname)) {
363
- return false;
364
- }
365
- }
366
-
367
- return true;
374
+ return !isLoopbackUrl(parsedUrl) && !isExcludedByNoProxy(parsedUrl);
368
375
  }
369
376
 
370
377
  /**
@@ -383,40 +390,26 @@ export function isValidUrl(url: string): boolean {
383
390
  }
384
391
 
385
392
  /**
386
- * Returns the proxy URL from environment variables based on the target URL.
387
- * For HTTPS URLs, checks `https_proxy` then `HTTPS_PROXY`.
388
- * For HTTP URLs, checks `http_proxy` then `HTTP_PROXY`.
393
+ * Returns the proxy url from environment variables based on the target url.
394
+ * For HTTPS urls, checks `https_proxy` then `HTTPS_PROXY`.
395
+ * For HTTP urls, checks `http_proxy` then `HTTP_PROXY`.
389
396
  * Falls back to the other protocol's proxy if none found.
390
397
  *
391
- * @param url The target URL to determine proxy for.
392
- * @returns The proxy URL, or `undefined` if none are set.
398
+ * Empty and whitespace-only values are treated as unset, and the returned value
399
+ * is trimmed. It isn't validated: use {@link isValidUrl} if you need that.
400
+ *
401
+ * @param url The target url to determine proxy for.
402
+ * @returns The proxy url, or `undefined` if none are set.
393
403
  */
394
404
  export function getProxyUrl(url: string): string | undefined {
395
- const { protocol } = new URL(url);
396
-
397
- if (protocol === "https:") {
398
- return (
399
- process.env.https_proxy ??
400
- process.env.HTTPS_PROXY ??
401
- process.env.http_proxy ??
402
- process.env.HTTP_PROXY
403
- );
404
- } else if (protocol === "http:") {
405
- return (
406
- process.env.http_proxy ??
407
- process.env.HTTP_PROXY ??
408
- process.env.https_proxy ??
409
- process.env.HTTPS_PROXY
410
- );
411
- }
412
-
413
- return undefined;
405
+ return findProxyEnvVar(url)?.value;
414
406
  }
415
407
 
416
408
  export {
417
409
  ConnectionRefusedError,
418
410
  DispatcherError,
419
411
  DownloadError,
412
+ InvalidProxyUrlError,
420
413
  RequestError,
421
414
  RequestTimeoutError,
422
415
  ResponseStatusCodeError,