{"_id":"@a_harmless_pyro/proxy-chain","name":"@a_harmless_pyro/proxy-chain","dist-tags":{"latest":"2.6.0"},"versions":{"2.6.0":{"name":"@a_harmless_pyro/proxy-chain","version":"2.6.0","description":"Node.js implementation of a proxy server (think Squid) with support for SSL, authentication, upstream proxy chaining, and protocol tunneling.","main":"dist/index.js","license":"Apache-2.0","repository":{"type":"git","url":"git+https://github.com/AHarmlessPyro/proxy-chain"},"bugs":{"url":"https://github.com/AHarmlessPyro/proxy-chain/issues"},"publishConfig":{"access":"public"},"scripts":{"build:watch":"tsc -w","build":"tsc","clean":"rimraf dist","prepublishOnly":"npm run build","local-proxy":"node ./dist/run_locally.js","test":"nyc cross-env NODE_OPTIONS=--insecure-http-parser mocha --bail","lint":"eslint .","lint:fix":"eslint . --fix"},"engines":{"node":">=14"},"devDependencies":{"@apify/eslint-config":"^1.0.0","@apify/tsconfig":"^0.1.1","@types/jest":"^28.1.2","@types/node":"^24.3.0","basic-auth":"^2.0.1","basic-auth-parser":"^0.0.2","body-parser":"^1.19.0","chai":"^4.3.4","cross-env":"^7.0.3","eslint":"^9.18.0","express":"^4.17.1","faye-websocket":"^0.11.4","got-scraping":"^3.2.4-beta.0","isparta":"^4.1.1","mocha":"^10.0.0","nyc":"^15.1.0","portastic":"^1.0.1","proxy":"^1.0.2","puppeteer":"^19.6.3","request":"^2.88.2","rimraf":"^4.1.2","sinon":"^13.0.2","sinon-stub-promise":"^4.0.0","socksv5":"^0.0.6","through":"^2.3.8","ts-node":"^10.2.1","typescript":"^5.9.2","typescript-eslint":"^8.20.0","underscore":"^1.13.1","ws":"^8.2.2"},"nyc":{"reporter":["text","html","lcov"],"exclude":["**/test/**"]},"dependencies":{"socks":"^2.8.3","socks-proxy-agent":"^8.0.3","tslib":"^2.3.1"},"licenseText":"                                 Apache License\n                           Version 2.0, January 2004\n                        http://www.apache.org/licenses/\n\n   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION\n\n   1. Definitions.\n\n      \"License\" shall mean the terms and conditions for use, reproduction,\n      and distribution as defined by Sections 1 through 9 of this document.\n\n      \"Licensor\" shall mean the copyright owner or entity authorized by\n      the copyright owner that is granting the License.\n\n      \"Legal Entity\" shall mean the union of the acting entity and all\n      other entities that control, are controlled by, or are under common\n      control with that entity. For the purposes of this definition,\n      \"control\" means (i) the power, direct or indirect, to cause the\n      direction or management of such entity, whether by contract or\n      otherwise, or (ii) ownership of fifty percent (50%) or more of the\n      outstanding shares, or (iii) beneficial ownership of such entity.\n\n      \"You\" (or \"Your\") shall mean an individual or Legal Entity\n      exercising permissions granted by this License.\n\n      \"Source\" form shall mean the preferred form for making modifications,\n      including but not limited to software source code, documentation\n      source, and configuration files.\n\n      \"Object\" form shall mean any form resulting from mechanical\n      transformation or translation of a Source form, including but\n      not limited to compiled object code, generated documentation,\n      and conversions to other media types.\n\n      \"Work\" shall mean the work of authorship, whether in Source or\n      Object form, made available under the License, as indicated by a\n      copyright notice that is included in or attached to the work\n      (an example is provided in the Appendix below).\n\n      \"Derivative Works\" shall mean any work, whether in Source or Object\n      form, that is based on (or derived from) the Work and for which the\n      editorial revisions, annotations, elaborations, or other modifications\n      represent, as a whole, an original work of authorship. For the purposes\n      of this License, Derivative Works shall not include works that remain\n      separable from, or merely link (or bind by name) to the interfaces of,\n      the Work and Derivative Works thereof.\n\n      \"Contribution\" shall mean any work of authorship, including\n      the original version of the Work and any modifications or additions\n      to that Work or Derivative Works thereof, that is intentionally\n      submitted to Licensor for inclusion in the Work by the copyright owner\n      or by an individual or Legal Entity authorized to submit on behalf of\n      the copyright owner. For the purposes of this definition, \"submitted\"\n      means any form of electronic, verbal, or written communication sent\n      to the Licensor or its representatives, including but not limited to\n      communication on electronic mailing lists, source code control systems,\n      and issue tracking systems that are managed by, or on behalf of, the\n      Licensor for the purpose of discussing and improving the Work, but\n      excluding communication that is conspicuously marked or otherwise\n      designated in writing by the copyright owner as \"Not a Contribution.\"\n\n      \"Contributor\" shall mean Licensor and any individual or Legal Entity\n      on behalf of whom a Contribution has been received by Licensor and\n      subsequently incorporated within the Work.\n\n   2. Grant of Copyright License. Subject to the terms and conditions of\n      this License, each Contributor hereby grants to You a perpetual,\n      worldwide, non-exclusive, no-charge, royalty-free, irrevocable\n      copyright license to reproduce, prepare Derivative Works of,\n      publicly display, publicly perform, sublicense, and distribute the\n      Work and such Derivative Works in Source or Object form.\n\n   3. Grant of Patent License. Subject to the terms and conditions of\n      this License, each Contributor hereby grants to You a perpetual,\n      worldwide, non-exclusive, no-charge, royalty-free, irrevocable\n      (except as stated in this section) patent license to make, have made,\n      use, offer to sell, sell, import, and otherwise transfer the Work,\n      where such license applies only to those patent claims licensable\n      by such Contributor that are necessarily infringed by their\n      Contribution(s) alone or by combination of their Contribution(s)\n      with the Work to which such Contribution(s) was submitted. If You\n      institute patent litigation against any entity (including a\n      cross-claim or counterclaim in a lawsuit) alleging that the Work\n      or a Contribution incorporated within the Work constitutes direct\n      or contributory patent infringement, then any patent licenses\n      granted to You under this License for that Work shall terminate\n      as of the date such litigation is filed.\n\n   4. Redistribution. You may reproduce and distribute copies of the\n      Work or Derivative Works thereof in any medium, with or without\n      modifications, and in Source or Object form, provided that You\n      meet the following conditions:\n\n      (a) You must give any other recipients of the Work or\n          Derivative Works a copy of this License; and\n\n      (b) You must cause any modified files to carry prominent notices\n          stating that You changed the files; and\n\n      (c) You must retain, in the Source form of any Derivative Works\n          that You distribute, all copyright, patent, trademark, and\n          attribution notices from the Source form of the Work,\n          excluding those notices that do not pertain to any part of\n          the Derivative Works; and\n\n      (d) If the Work includes a \"NOTICE\" text file as part of its\n          distribution, then any Derivative Works that You distribute must\n          include a readable copy of the attribution notices contained\n          within such NOTICE file, excluding those notices that do not\n          pertain to any part of the Derivative Works, in at least one\n          of the following places: within a NOTICE text file distributed\n          as part of the Derivative Works; within the Source form or\n          documentation, if provided along with the Derivative Works; or,\n          within a display generated by the Derivative Works, if and\n          wherever such third-party notices normally appear. The contents\n          of the NOTICE file are for informational purposes only and\n          do not modify the License. You may add Your own attribution\n          notices within Derivative Works that You distribute, alongside\n          or as an addendum to the NOTICE text from the Work, provided\n          that such additional attribution notices cannot be construed\n          as modifying the License.\n\n      You may add Your own copyright statement to Your modifications and\n      may provide additional or different license terms and conditions\n      for use, reproduction, or distribution of Your modifications, or\n      for any such Derivative Works as a whole, provided Your use,\n      reproduction, and distribution of the Work otherwise complies with\n      the conditions stated in this License.\n\n   5. Submission of Contributions. Unless You explicitly state otherwise,\n      any Contribution intentionally submitted for inclusion in the Work\n      by You to the Licensor shall be under the terms and conditions of\n      this License, without any additional terms or conditions.\n      Notwithstanding the above, nothing herein shall supersede or modify\n      the terms of any separate license agreement you may have executed\n      with Licensor regarding such Contributions.\n\n   6. Trademarks. This License does not grant permission to use the trade\n      names, trademarks, service marks, or product names of the Licensor,\n      except as required for reasonable and customary use in describing the\n      origin of the Work and reproducing the content of the NOTICE file.\n\n   7. Disclaimer of Warranty. Unless required by applicable law or\n      agreed to in writing, Licensor provides the Work (and each\n      Contributor provides its Contributions) on an \"AS IS\" BASIS,\n      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or\n      implied, including, without limitation, any warranties or conditions\n      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A\n      PARTICULAR PURPOSE. You are solely responsible for determining the\n      appropriateness of using or redistributing the Work and assume any\n      risks associated with Your exercise of permissions under this License.\n\n   8. Limitation of Liability. In no event and under no legal theory,\n      whether in tort (including negligence), contract, or otherwise,\n      unless required by applicable law (such as deliberate and grossly\n      negligent acts) or agreed to in writing, shall any Contributor be\n      liable to You for damages, including any direct, indirect, special,\n      incidental, or consequential damages of any character arising as a\n      result of this License or out of the use or inability to use the\n      Work (including but not limited to damages for loss of goodwill,\n      work stoppage, computer failure or malfunction, or any and all\n      other commercial damages or losses), even if such Contributor\n      has been advised of the possibility of such damages.\n\n   9. Accepting Warranty or Additional Liability. While redistributing\n      the Work or Derivative Works thereof, You may choose to offer,\n      and charge a fee for, acceptance of support, warranty, indemnity,\n      or other liability obligations and/or rights consistent with this\n      License. However, in accepting such obligations, You may act only\n      on Your own behalf and on Your sole responsibility, not on behalf\n      of any other Contributor, and only if You agree to indemnify,\n      defend, and hold each Contributor harmless for any liability\n      incurred by, or claims asserted against, such Contributor by reason\n      of your accepting any such warranty or additional liability.\n\n   END OF TERMS AND CONDITIONS\n\n   APPENDIX: How to apply the Apache License to your work.\n\n      To apply the Apache License to your work, attach the following\n      boilerplate notice, with the fields enclosed by brackets \"{}\"\n      replaced with your own identifying information. (Don't include\n      the brackets!)  The text should be enclosed in the appropriate\n      comment syntax for the file format. We also recommend that a\n      file or class name and description of purpose be included on the\n      same \"printed page\" as the copyright notice for easier\n      identification within third-party archives.\n\n   Copyright 2018 Apify Technologies s.r.o.\n\n   Licensed under the Apache License, Version 2.0 (the \"License\");\n   you may not use this file except in compliance with the License.\n   You may obtain a copy of the License at\n\n       http://www.apache.org/licenses/LICENSE-2.0\n\n   Unless required by applicable law or agreed to in writing, software\n   distributed under the License is distributed on an \"AS IS\" BASIS,\n   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n   See the License for the specific language governing permissions and\n   limitations under the License.\n","_id":"@a_harmless_pyro/proxy-chain@2.6.0","dist":{"shasum":"cb939963ea0d2bd87107f42b65c15fffcdcfb68a","integrity":"sha512-3NS6ckz+DLupimW1GvMLqQG6zW4eL+d4tUOW+UF3Jca8NZqwPyL9JnbOB6x2S7S7s5CAmxlVQFnBRHMruSQw4Q==","tarball":"https://registry.npmjs.org/@a_harmless_pyro/proxy-chain/-/proxy-chain-2.6.0.tgz","fileCount":100,"unpackedSize":238001,"signatures":[{"keyid":"SHA256:DhQ8wR5APBvFHLF/+Tc+AYvPOdTpcIDqOhxsBHRwC7U","sig":"MEYCIQDCii+Ejz/rY9xJtNQD/zQa0VZ5zVA9UDsRoft6w2/vNQIhANXCMVwBsQntc8+dkpTZjzN2sTtJIoyCKTbO6UC+bPCS"}]},"_npmUser":{"name":"a_harmless_pyro","email":"ninadsinhaa@gmail.com"},"directories":{},"maintainers":[{"name":"a_harmless_pyro","email":"ninadsinhaa@gmail.com"}],"_npmOperationalInternal":{"host":"s3://npm-registry-packages-npm-production","tmp":"tmp/proxy-chain_2.6.0_1756925930774_0.6143081037516562"},"_hasShrinkwrap":false}},"time":{"created":"2025-09-03T18:58:50.700Z","2.6.0":"2025-09-03T18:58:50.962Z","modified":"2025-09-03T18:58:51.260Z"},"maintainers":[{"name":"a_harmless_pyro","email":"ninadsinhaa@gmail.com"}],"description":"Node.js implementation of a proxy server (think Squid) with support for SSL, authentication, upstream proxy chaining, and protocol tunneling.","repository":{"type":"git","url":"git+https://github.com/AHarmlessPyro/proxy-chain"},"bugs":{"url":"https://github.com/AHarmlessPyro/proxy-chain/issues"},"license":"Apache-2.0","readme":"# Programmable HTTP proxy server for Node.js\n\n[![npm version](https://badge.fury.io/js/proxy-chain.svg)](http://badge.fury.io/js/proxy-chain)\n\nA programmable proxy server (think Squid) with support for SSL/TLS, authentication, upstream proxy chaining, SOCKS4/5 protocol,\ncustom HTTP responses, and traffic statistics.\nThe authentication and proxy chaining configuration is defined in code and can be fully dynamic, giving you a high level of customization for your use case.\n\nFor example, the proxy-chain package is useful if you need to use headless Chrome web browser and proxies with authentication,\nbecause Chrome doesn't support proxy URLs with password, such as `http://username:password@proxy.example.com:8080`.\nWith this package, you can set up a local proxy server without any password\nthat will forward requests to the upstream proxy with password.\nFor details, read [How to make headless Chrome and Puppeteer use a proxy server with authentication](https://blog.apify.com/how-to-make-headless-chrome-and-puppeteer-use-a-proxy-server-with-authentication-249a21a79212/).\n\nThe proxy-chain package is developed by [Apify](https://apify.com/), the full-stack web scraping and data extraction platform, to support their [Apify Proxy](https://apify.com/proxy) product,\nwhich provides an easy access to a large pool of datacenter and residential IP addresses all around the world. The proxy-chain package is also used by [Crawlee](https://crawlee.dev/),\nthe world's most popular web craling library for Node.js.\n\nThe proxy-chain package currently supports HTTP/SOCKS forwarding and HTTP CONNECT tunneling to forward arbitrary protocols such as HTTPS or FTP ([learn more](https://blog.apify.com/tunneling-arbitrary-protocols-over-http-proxy-with-static-ip-address-b3a2222191ff)). The HTTP CONNECT tunneling also supports the SOCKS protocol. Also, proxy-chain only supports the Basic [Proxy-Authorization](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Proxy-Authorization).\n\n## Run a simple HTTP/HTTPS proxy server\n\n```javascript\nconst ProxyChain = require('proxy-chain');\n\nconst server = new ProxyChain.Server({ port: 8000 });\n\nserver.listen(() => {\n    console.log(`Proxy server is listening on port ${server.port}`);\n});\n```\n\n## Run a HTTP/HTTPS proxy server with credentials and upstream proxy\n\n```javascript\nconst ProxyChain = require('proxy-chain');\n\nconst server = new ProxyChain.Server({\n    // Port where the server will listen. By default 8000.\n    port: 8000,\n\n    // Optional host where the proxy server will listen.\n    // If not specified, the sever listens on an unspecified IP address (0.0.0.0 in IPv4, :: in IPv6)\n    // You can use this option to limit the access to the proxy server.\n    host: 'localhost',\n\n    // Enables verbose logging\n    verbose: true,\n\n    // Custom user-defined function to authenticate incoming proxy requests,\n    // and optionally provide the URL to chained upstream proxy.\n    // The function must return an object (or promise resolving to the object) with the following signature:\n    // { requestAuthentication: boolean, upstreamProxyUrl: string, failMsg?: string, customTag?: unknown }\n    // If the function is not defined or is null, the server runs in simple mode.\n    // Note that the function takes a single argument with the following properties:\n    // * request      - An instance of http.IncomingMessage class with information about the client request\n    //                  (which is either HTTP CONNECT for SSL protocol, or other HTTP request)\n    // * username     - Username parsed from the Proxy-Authorization header. Might be empty string.\n    // * password     - Password parsed from the Proxy-Authorization header. Might be empty string.\n    // * hostname     - Hostname of the target server\n    // * port         - Port of the target server\n    // * isHttp       - If true, this is a HTTP request, otherwise it's a HTTP CONNECT tunnel for SSL\n    //                  or other protocols\n    // * connectionId - Unique ID of the HTTP connection. It can be used to obtain traffic statistics.\n    prepareRequestFunction: ({ request, username, password, hostname, port, isHttp, connectionId }) => {\n        return {\n            // If set to true, the client is sent HTTP 407 resposne with the Proxy-Authenticate header set,\n            // requiring Basic authentication. Here you can verify user credentials.\n            requestAuthentication: username !== 'bob' || password !== 'TopSecret',\n\n            // Sets up an upstream HTTP/HTTPS/SOCKS proxy to which all the requests are forwarded.\n            // If null, the proxy works in direct mode, i.e. the connection is forwarded directly\n            // to the target server. This field is ignored if \"requestAuthentication\" is true.\n            // The username and password must be URI-encoded.\n            upstreamProxyUrl: `http://username:password@proxy.example.com:3128`,\n            // Or use SOCKS4/5 proxy, e.g.\n            // upstreamProxyUrl: `socks://username:password@proxy.example.com:1080`,\n\n            // Applies to HTTPS upstream proxy. If set to true, requests made to the proxy will\n            // ignore certificate errors. Useful when upstream proxy uses self-signed certificate. By default \"false\".\n            ignoreUpstreamProxyCertificate: true\n\n            // If \"requestAuthentication\" is true, you can use the following property\n            // to define a custom error message to return to the client instead of the default \"Proxy credentials required\"\n            failMsg: 'Bad username or password, please try again.',\n\n            // Optional custom tag that will be passed back via\n            // `tunnelConnectResponded` or `tunnelConnectFailed` events\n            // Can be used to pass information between proxy-chain\n            // and any external code or application using it\n            customTag: { userId: '123' },\n        };\n    },\n});\n\nserver.listen(() => {\n  console.log(`Proxy server is listening on port ${server.port}`);\n});\n\n// Emitted when HTTP connection is closed\nserver.on('connectionClosed', ({ connectionId, stats }) => {\n  console.log(`Connection ${connectionId} closed`);\n  console.dir(stats);\n});\n\n// Emitted when HTTP request fails\nserver.on('requestFailed', ({ request, error }) => {\n  console.log(`Request ${request.url} failed`);\n  console.error(error);\n});\n```\n\n## SOCKS support\nSOCKS protocol is supported for versions 4 and 5, specifically: `['socks', 'socks4', 'socks4a', 'socks5', 'socks5h']`, where `socks` will default to version 5.\n\nYou can use an `upstreamProxyUrl` like `socks://username:password@proxy.example.com:1080`.\n\n## Error status codes\n\nThe `502 Bad Gateway` HTTP status code is not comprehensive enough. Therefore, the server may respond with `590-599` instead:\n\n### `590 Non Successful`\n\nUpstream responded with non-200 status code.\n\n### `591 RESERVED`\n\n*This status code is reserved for further use.*\n\n### `592 Status Code Out Of Range`\n\nUpstream respondend with status code different than 100-999.\n\n### `593 Not Found`\n\nDNS lookup failed - [`EAI_NODATA`](https://github.com/libuv/libuv/blob/cdbba74d7a756587a696fb3545051f9a525b85ac/include/uv.h#L82) or [`EAI_NONAME`](https://github.com/libuv/libuv/blob/cdbba74d7a756587a696fb3545051f9a525b85ac/include/uv.h#L83).\n\n### `594 Connection Refused`\n\nUpstream refused connection.\n\n### `595 Connection Reset`\n\nConnection reset due to loss of connection or timeout.\n\n### `596 Broken Pipe`\n\nTrying to write on a closed socket.\n\n### `597 Auth Failed`\n\nIncorrect upstream credentials.\n\n### `598 RESERVED`\n\n*This status code is reserved for further use.*\n\n### `599 Upstream Error`\n\nGeneric upstream error.\n\n---\n\n`590` and `592` indicate an issue on the upstream side. \\\n`593` indicates an incorrect `proxy-chain` configuration.\\\n`594`, `595` and `596` may occur due to connection loss.\\\n`597` indicates incorrect upstream credentials.\\\n`599` is a generic error, where the above is not applicable.\n\n## Custom error responses\n\nTo return a custom HTTP response to indicate an error to the client,\nyou can throw the `RequestError` from inside of the `prepareRequestFunction` function.\nThe class constructor has the following parameters: `RequestError(body, statusCode, headers)`.\nBy default, the response will have `Content-Type: text/plain; charset=utf-8`.\n\n```javascript\nconst ProxyChain = require('proxy-chain');\n\nconst server = new ProxyChain.Server({\n    prepareRequestFunction: ({ request, username, password, hostname, port, isHttp, connectionId }) => {\n        if (username !== 'bob') {\n           throw new ProxyChain.RequestError('Only Bob can use this proxy!', 400);\n        }\n    },\n});\n```\n\n## Measuring traffic statistics\n\nTo get traffic statistics for a certain HTTP connection, you can use:\n```javascript\nconst stats = server.getConnectionStats(connectionId);\nconsole.dir(stats);\n```\n\nThe resulting object looks like:\n```javascript\n{\n    // Number of bytes sent to client\n    srcTxBytes: Number,\n    // Number of bytes received from client\n    srcRxBytes: Number,\n    // Number of bytes sent to target server (proxy or website)\n    trgTxBytes: Number,\n    // Number of bytes received from target server (proxy or website)\n    trgRxBytes: Number,\n}\n```\n\nIf the underlying sockets were closed, the corresponding values will be `null`,\nrather than `0`.\n\n## Custom responses\n\nCustom responses allow you to override the response to a HTTP requests to the proxy, without contacting any target host.\nFor example, this is useful if you want to provide a HTTP proxy-style interface\nto an external API or respond with some custom page to certain requests.\nNote that this feature is only available for HTTP connections. That's because HTTPS\nconnections cannot be intercepted without access to the target host's private key.\n\nTo provide a custom response, the result of the `prepareRequestFunction` function must\ndefine the `customResponseFunction` property, which contains a function that generates the custom response.\nThe function is passed no parameters and it must return an object (or a promise resolving to an object)\nwith the following properties:\n\n```javascript\n{\n  // Optional HTTP status code of the response. By default it is 200.\n  statusCode: 200,\n\n  // Optional HTTP headers of the response\n  headers: {\n    'X-My-Header': 'bla bla',\n  }\n\n  // Optional string with the body of the HTTP response\n  body: 'My custom response',\n\n  // Optional encoding of the body. If not provided, defaults to 'UTF-8'\n  encoding: 'UTF-8',\n}\n```\n\nHere is a simple example:\n\n```javascript\nconst ProxyChain = require('proxy-chain');\n\nconst server = new ProxyChain.Server({\n    port: 8000,\n    prepareRequestFunction: ({ request, username, password, hostname, port, isHttp }) => {\n        return {\n            customResponseFunction: () => {\n                return {\n                    statusCode: 200,\n                    body: `My custom response to ${request.url}`,\n                };\n            },\n        };\n    },\n});\n\nserver.listen(() => {\n  console.log(`Proxy server is listening on port ${server.port}`);\n});\n```\n\n## Routing CONNECT to another HTTP server\n\nWhile `customResponseFunction` enables custom handling methods such as `GET` and `POST`, many HTTP clients rely on `CONNECT` tunnels.\nIt's possible to route those requests differently using the `customConnectServer` option. It accepts an instance of Node.js HTTP server.\n\n```javascript\nconst http = require('http');\nconst ProxyChain = require('proxy-chain');\n\nconst exampleServer = http.createServer((request, response) => {\n    response.end('Hello from a custom server!');\n});\n\nconst server = new ProxyChain.Server({\n    port: 8000,\n    prepareRequestFunction: ({ request, username, password, hostname, port, isHttp }) => {\n        if (request.url.toLowerCase() === 'example.com:80') {\n            return {\n                customConnectServer: exampleServer,\n            };\n        }\n\n        return {};\n    },\n});\n\nserver.listen(() => {\n  console.log(`Proxy server is listening on port ${server.port}`);\n});\n```\n\nIn the example above, all CONNECT tunnels to `example.com` are overridden.\nThis is an unsecure server, so it accepts only `http:` requests.\n\nIn order to intercept `https:` requests, `https.createServer` should be used instead, along with a self signed certificate.\n\n```javascript\nconst https = require('https');\nconst fs = require('fs');\nconst key = fs.readFileSync('./test/ssl.key');\nconst cert = fs.readFileSync('./test/ssl.crt');\n\nconst exampleServer = https.createServer({\n    key,\n    cert,\n}, (request, response) => {\n    response.end('Hello from a custom server!');\n});\n```\n\n## Closing the server\n\nTo shut down the proxy server, call the `close([destroyConnections], [callback])` function. For example:\n\n```javascript\nserver.close(true, () => {\n  console.log('Proxy server was closed.');\n});\n```\n\nThe `closeConnections` parameter indicates whether pending proxy connections should be forcibly closed.\nIf it's `false`, the function will wait until all connections are closed, which can take a long time.\nIf the `callback` parameter is omitted, the function returns a promise.\n\n\n## Accessing the CONNECT response headers for proxy tunneling\n\nSome upstream proxy providers might include valuable debugging information in the CONNECT response\nheaders when establishing the proxy tunnel, for they may not modify future data in the tunneled\nconnection.\n\nThe proxy server would emit a `tunnelConnectResponded` event for exposing such information, where\nthe parameter types of the event callback are described in [Node.js's documentation][1]. Example:\n\n[1]: https://nodejs.org/api/http.html#http_event_connect\n\n```javascript\nserver.on('tunnelConnectResponded', ({ proxyChainId, response, socket, head, customTag }) => {\n    console.log(`CONNECT response headers received: ${response.headers}`);\n});\n```\n\nAlternatively a [helper function](##helper-functions) may be used:\n\n```javascript\nlistenConnectAnonymizedProxy(anonymizedProxyUrl, ({ response, socket, head }) => {\n    console.log(`CONNECT response headers received: ${response.headers}`);\n});\n```\n\nYou can also listen to CONNECT requests that receive response with status code different from 200.\nThe proxy server would emit a `tunnelConnectFailed` event.\n\n```javascript\nserver.on('tunnelConnectFailed', ({ proxyChainId, response, socket, head, customTag }) => {\n    console.log(`CONNECT response failed with status code: ${response.statusCode}`);\n});\n```\n\n## Helper functions\n\nThe package also provides several utility functions.\n\n\n### `anonymizeProxy({ url, port }, callback)`\n\nParses and validates a HTTP/HTTPS proxy URL. If the proxy requires authentication,\nthen the function starts an open local proxy server that forwards to the proxy.\nThe port (on which the local proxy server will start) can be set via the `port` property of the first argument, if not provided, it will be chosen randomly.\n\nFor HTTPS proxy with self-signed certificate, set `ignoreProxyCertificate` property of the first argument to `true` to ignore certificate errors in\nproxy requests.\n\nThe function takes an optional callback that receives the anonymous proxy URL.\nIf no callback is supplied, the function returns a promise that resolves to a String with\nanonymous proxy URL or the original URL if it was already anonymous.\n\nThe following example shows how you can use a proxy with authentication\nfrom headless Chrome and [Puppeteer](https://github.com/GoogleChrome/puppeteer).\nFor details, read this [blog post](https://blog.apify.com/how-to-make-headless-chrome-and-puppeteer-use-a-proxy-server-with-authentication-249a21a79212).\n\n```javascript\nconst puppeteer = require('puppeteer');\nconst proxyChain = require('proxy-chain');\n\n(async() => {\n    const oldProxyUrl = 'http://bob:password123@proxy.example.com:8000';\n    const newProxyUrl = await proxyChain.anonymizeProxy(oldProxyUrl);\n\n    // Prints something like \"http://127.0.0.1:45678\"\n    console.log(newProxyUrl);\n\n    const browser = await puppeteer.launch({\n        args: [`--proxy-server=${newProxyUrl}`],\n    });\n\n    // Do your magic here...\n    const page = await browser.newPage();\n    await page.goto('https://www.example.com');\n    await page.screenshot({ path: 'example.png' });\n    await browser.close();\n\n    // Clean up\n    await proxyChain.closeAnonymizedProxy(newProxyUrl, true);\n})();\n```\n\n### `closeAnonymizedProxy(anonymizedProxyUrl, closeConnections, callback)`\n\nCloses anonymous proxy previously started by `anonymizeProxy()`.\nIf proxy was not found or was already closed, the function has no effect\nand its result is `false`. Otherwise the result is `true`.\n\nThe `closeConnections` parameter indicates whether pending proxy connections are forcibly closed.\nIf it's `false`, the function will wait until all connections are closed, which can take a long time.\n\nThe function takes an optional callback that receives the result Boolean from the function.\nIf callback is not provided, the function returns a promise instead.\n\n### `createTunnel(proxyUrl, targetHost, options, callback)`\n\nCreates a TCP tunnel to `targetHost` that goes through a HTTP/HTTPS proxy server\nspecified by the `proxyUrl` parameter.\n\nThe optional `options` parameter is an object with the following properties:\n- `port: Number` - Enables specifying the local port to listen at. By default `0`,\n   which means a random port will be selected.\n- `hostname: String` - Local hostname to listen at. By default `localhost`.\n- `ignoreProxyCertificate` - For HTTPS proxy, ignore certificate errors in proxy requests. Useful for proxy with self-signed certificate. By default `false`.\n- `verbose: Boolean` - If `true`, the functions logs a lot. By default `false`.\n\nThe result of the function is a local endpoint in a form of `hostname:port`.\nAll TCP connections made to the local endpoint will be tunneled through the proxy to the target host and port.\nFor example, this is useful if you want to access a certain service from a specific IP address.\n\nThe tunnel should be eventually closed by calling the `closeTunnel()` function.\n\nThe `createTunnel()` function accepts an optional Node.js-style callback that receives the path to the local endpoint.\nIf no callback is supplied, the function returns a promise that resolves to a String with\nthe path to the local endpoint.\n\nFor more information, read this [blog post](https://blog.apify.com/tunneling-arbitrary-protocols-over-http-proxy-with-static-ip-address-b3a2222191ff).\n\nExample:\n\n```javascript\nconst host = await createTunnel('http://bob:pass123@proxy.example.com:8000', 'service.example.com:356');\n// Prints something like \"localhost:56836\"\nconsole.log(host);\n```\n\n### `closeTunnel(tunnelString, closeConnections, callback)`\n\nCloses tunnel previously started by `createTunnel()`.\nThe result value is `false` if the tunnel was not found or was already closed, otherwise it is `true`.\n\nThe `closeConnections` parameter indicates whether pending connections are forcibly closed.\nIf it's `false`, the function will wait until all connections are closed, which can take a long time.\n\nThe function takes an optional callback that receives the result of the function.\nIf the callback is not provided, the function returns a promise instead.\n\n### `listenConnectAnonymizedProxy(anonymizedProxyUrl, tunnelConnectRespondedCallback)`\n\nAllows to configure a callback on the anonymized proxy URL for the CONNECT response headers. See the\nabove section [Accessing the CONNECT response headers for proxy tunneling](#accessing-the-connect-response-headers-for-proxy-tunneling)\nfor details.\n\n### `redactUrl(url, passwordReplacement)`\n\nTakes a URL and hides the password from it. For example:\n\n```javascript\n// Prints 'http://bob:<redacted>@example.com'\nconsole.log(redactUrl('http://bob:pass123@example.com'));\n```\n","readmeFilename":"README.md","_rev":"1-f1df52349b31da361356002b26152192"}