### Install and Start AnyProxy via CLI Source: https://context7.com/alibaba/anyproxy/llms.txt Installs AnyProxy globally and demonstrates various command-line options for starting the proxy server with different configurations, including custom ports, HTTPS interception, rule modules, throttling, and silent mode. ```bash # Install AnyProxy globally npm install -g anyproxy # Start with default settings (port 8001 for proxy, 8002 for web interface) anyproxy # Start with custom proxy port anyproxy --port 1080 # Start with web interface on custom port anyproxy --web 8888 # Enable HTTPS interception (requires root CA setup) anyproxy --intercept # Apply custom rule module anyproxy --rule ./my-rule.js # Enable throttling (in kb/s) anyproxy --throttle 100 # Enable WebSocket interception anyproxy --ws-intercept # Silent mode (no console output) anyproxy --silent # Clear certificates and temp files anyproxy --clear ``` -------------------------------- ### Install and Use AnyProxy as an npm Module Source: https://github.com/alibaba/anyproxy/blob/master/docs/en/index.html Demonstrates how to install AnyProxy using npm and provides a basic example of creating and configuring a proxy server instance. It includes options for port, rules, web interface, and more. The server emits 'ready' and 'error' events. ```javascript npm i anyproxy --save const AnyProxy = require('anyproxy'); const options = { port: 8001, rule: require('myRuleModule'), webInterface: { enable: true, webPort: 8002 }, throttle: 10000, forceProxyHttps: false, wsIntercept: false, silent: false }; const proxyServer = new AnyProxy.ProxyServer(options); proxyServer.on('ready', () => { /* */ }); proxyServer.on('error', (e) => { /* */ }); proxyServer.start(); //when finished proxyServer.close(); ``` -------------------------------- ### Installation and Launch Source: https://github.com/alibaba/anyproxy/blob/master/docs/en/src_doc.md Instructions for installing AnyProxy globally and launching it with default or custom options. ```APIDOC ## Installation To install AnyProxy, run the following command: ```bash npm install -g anyproxy ``` For Debian and Ubuntu users, you might need to install `nodejs-legacy` first: ```bash sudo apt-get install nodejs-legacy ``` ## Launching AnyProxy Start AnyProxy with default settings (port 8001): ```bash anyproxy ``` Access the proxy at `http://127.0.0.1:8001`. Visit the web interface at `http://127.0.0.1:8002`. To specify a different port: ```bash anyproxy --port 1080 ``` ``` -------------------------------- ### Start AnyProxy with a Global npm Rule Package Source: https://github.com/alibaba/anyproxy/blob/master/docs/en/src_doc.md This command starts AnyProxy after installing a rule module package globally via npm. AnyProxy can then load this module by its package name, facilitating the reuse of rule modules across different projects or AnyProxy instances. ```bash npm i -g myRulePkg && anyproxy --rule myRulePkg #global-installed module ``` -------------------------------- ### AnyProxy CLI Installation and Launch Source: https://github.com/alibaba/anyproxy/blob/master/docs-src/en/README.md Instructions for installing AnyProxy globally using npm and launching it with default or custom port settings. ```APIDOC ## Installation To install AnyProxy globally, run the following command: ```bash npm install -g anyproxy ``` For Debian/Ubuntu users, you might need to install `nodejs-legacy` first: ```bash sudo apt-get install nodejs-legacy ``` ## Launching AnyProxy To start AnyProxy with default settings (port 8001): ```bash anyproxy ``` To specify a different port for the HTTP proxy: ```bash anyproxy --port 1080 ``` After launching, the HTTP proxy will be available at `127.0.0.1:8001` (or the specified port), and the web interface will be at `http://127.0.0.1:8002`. ``` -------------------------------- ### Install AnyProxy via npm Source: https://github.com/alibaba/anyproxy/blob/master/docs/en/src_doc.md Installs the AnyProxy package globally using npm. Ensure Node.js and npm are installed on your system. This command is typically run in a terminal. ```bash npm install -g anyproxy ``` -------------------------------- ### Start AnyProxy with a Local Rule File Source: https://github.com/alibaba/anyproxy/blob/master/docs-src/en/src_doc.md This command starts AnyProxy and loads a custom rule from a local Javascript file named `sample.js`. The rules allow for customization of request and response handling. ```bash anyproxy --rule sample.js ``` -------------------------------- ### Start AnyProxy with a Local npm Rule Package Source: https://github.com/alibaba/anyproxy/blob/master/docs/en/src_doc.md This command starts AnyProxy and loads a rule module from a local package directory. AnyProxy uses Node.js's `require()` mechanism, allowing for complex rule structures and dependencies managed via npm. ```bash anyproxy --rule ./myRulePkg/ #local module ``` -------------------------------- ### Install AnyProxy for Node.js Source: https://github.com/alibaba/anyproxy/wiki/v3.x-AnyProxy-docs Installs the AnyProxy package as a dependency for your Node.js project using npm. This is the first step to using AnyProxy as a module. ```bash npm install anyproxy --save ``` -------------------------------- ### AnyProxy Command Line Usage Source: https://github.com/alibaba/anyproxy/blob/master/docs-src/en/src_doc.md Instructions on how to install and launch AnyProxy from the command line, including options for specifying ports. ```APIDOC ## Installation To install AnyProxy: ```bash npm install -g anyproxy ``` For Debian/Ubuntu users, you might need to install `nodejs-legacy` first: ```bash sudo apt-get install nodejs-legacy ``` ## Launching AnyProxy To start AnyProxy with default settings (port 8001): ```bash anyproxy ``` To specify a different port: ```bash anyproxy --port 1080 ``` ## Accessing AnyProxy - The HTTP proxy server will be available at `127.0.0.1:8001` (or the specified port). - The web interface, if enabled, can be accessed at `http://127.0.0.1:8002`. ``` -------------------------------- ### Install Node.js Legacy on Debian/Ubuntu Source: https://github.com/alibaba/anyproxy/blob/master/docs/en/src_doc.md Installs the `nodejs-legacy` package on Debian or Ubuntu systems. This is a prerequisite for installing and running certain Node.js applications, including potentially older versions or specific configurations of AnyProxy. ```bash sudo apt-get install nodejs-legacy ``` -------------------------------- ### Start AnyProxy from Command Line Source: https://github.com/alibaba/anyproxy/blob/master/docs/cn/index.html Launches AnyProxy as a command-line tool. By default, it runs on port 8001. After starting, users need to configure their system's HTTP proxy to 127.0.0.1:8001 to route traffic through AnyProxy. The web interface, accessible at http://127.0.0.1:8002, displays all intercepted requests. ```bash anyproxy ``` -------------------------------- ### Install AnyProxy Globally Source: https://github.com/alibaba/anyproxy/blob/master/docs/cn/index.html Installs AnyProxy as a global npm module. This command is used on Debian/Ubuntu systems and may require installing 'nodejs-legacy' first. It makes the `anyproxy` command available in the terminal. ```bash sudo apt-get install nodejs-legacy npm install -g anyproxy ``` -------------------------------- ### Start AnyProxy with a Specific Port Source: https://github.com/alibaba/anyproxy/blob/master/docs/cn/index.html This command starts the AnyProxy server, listening on the specified port. This is useful for dedicating a specific port for proxying traffic. ```bash anyproxy --port 1080 ``` -------------------------------- ### Installing Third-Party Node Modules for AnyProxy Rules Source: https://github.com/alibaba/anyproxy/wiki/v3.x-What-is-rule-file-and-how-to-write-one Explains the command used to install external Node.js modules that can be utilized within AnyProxy rule files. This extends the functionality of the proxy by allowing the use of libraries like 'underscore'. ```bash anyproxy install ``` -------------------------------- ### Integrate AnyProxy as an NPM Module Source: https://github.com/alibaba/anyproxy/blob/master/docs/cn/index.html Demonstrates how to install AnyProxy as a dependency and use it programmatically within a Node.js application. It shows the initialization of the proxy server with various configuration options and event handling. ```javascript const AnyProxy = require('anyproxy'); const options = { port: 8001, rule: require('myRuleModule'), webInterface: { enable: true, webPort: 8002 }, throttle: 10000, forceProxyHttps: false, wsIntercept: false, // 不开启websocket代理 silent: false }; const proxyServer = new AnyProxy.ProxyServer(options); proxyServer.on('ready', () => { /* */ }); proxyServer.on('error', (e) => { /* */ }); proxyServer.start(); //when finished proxyServer.close(); ``` -------------------------------- ### Using AnyProxy as an NPM Module Source: https://github.com/alibaba/anyproxy/blob/master/docs/cn/index.html Programmatically integrate AnyProxy into your Node.js applications. This section covers installation, basic usage, and configuration options for the ProxyServer class. ```APIDOC ## Using AnyProxy as an NPM Module ### Installation Install AnyProxy as a dependency in your project: ```bash npm install anyproxy --save ``` ### Basic Usage Example Instantiate and start the AnyProxy server within your Node.js application. ```javascript const AnyProxy = require('anyproxy'); const options = { port: 8001, rule: require('myRuleModule'), // Optional: path to your custom rule module webInterface: { enable: true, webPort: 8002 }, throttle: 10000, // in kb/s forceProxyHttps: false, wsIntercept: false, // Enable WebSocket interception silent: false }; const proxyServer = new AnyProxy.ProxyServer(options); proxyServer.on('ready', () => { console.log('Proxy server is ready.'); }); proxyServer.on('error', (e) => { console.error('Proxy server error:', e); }); proxyServer.start(); // To close the server when needed: // proxyServer.close(); ``` ### Class: `AnyProxy.ProxyServer` #### Constructor `new AnyProxy.ProxyServer(options)` Creates a new proxy server instance. #### Options * **`port`** (number) - **Required**. The port on which the proxy server will listen. * **`rule`** (object) - An optional custom rule module to define request/response handling logic. * **`throttle`** (number) - Bandwidth throttle limit in kb/s. Defaults to unlimited. * **`forceProxyHttps`** (boolean) - If `true`, forces interception of all HTTPS requests, ignoring the rule module's instructions. Defaults to `false`. * **`silent`** (boolean) - If `true`, suppresses all console output from AnyProxy. Defaults to `false`. * **`dangerouslyIgnoreUnauthorized`** (boolean) - If `true`, ignores certificate errors in requests. Defaults to `false`. * **`wsIntercept`** (boolean) - If `true`, enables WebSocket proxying. Defaults to `false`. * **`webInterface`** (object) - Configuration for the web interface: * **`enable`** (boolean) - Enables the web interface. Defaults to `false`. * **`webPort`** (number) - The port for the web interface. Defaults to `8002`. #### Events * **`ready`**: Emitted when the proxy server has successfully started. ```javascript proxyServer.on('ready', function() { /* ... */ }); ``` * **`error`**: Emitted when the proxy server encounters an error. ```javascript proxyServer.on('error', function(e) { /* ... */ }); ``` #### Methods * **`start()`**: Starts the proxy server. ```javascript proxy.start(); ``` * **`close()`**: Stops and closes the proxy server. ```javascript proxy.close(); ``` ``` -------------------------------- ### Invoking AnyProxy with a Rule File Source: https://github.com/alibaba/anyproxy/wiki/v3.x-What-is-rule-file-and-how-to-write-one Demonstrates how to start the AnyProxy server and direct it to use a specific rule file for request and response handling. This is the primary method for enabling custom proxy logic. ```bash anyproxy --rule /path/to/your/ruleFile.js ``` -------------------------------- ### Command Line Usage Source: https://github.com/alibaba/anyproxy/blob/master/docs/cn/index.html Examples of using AnyProxy directly from the command line for basic proxying, HTTPS interception, and WebSocket interception. ```APIDOC ## Command Line Usage ### Start proxy on a specific port ```bash anyproxy --port 1080 ``` ### Intercept HTTPS requests This requires generating and trusting the root CA certificate first. Use `anyproxy-ca` to generate the certificate and then start AnyProxy with the `--intercept` flag. ```bash # Generate root CA certificate (trust this manually) anyproxy-ca # Start AnyProxy and intercept all HTTPS requests anyproxy --intercept ``` ### Intercept WebSocket requests To see WebSocket traffic in the AnyProxy interface, use the `--ws-intercept` flag. This is often used in conjunction with HTTPS interception. ```bash anyproxy --ws-intercept ``` ``` -------------------------------- ### Load AnyProxy Rule from an NPM Module Source: https://github.com/alibaba/anyproxy/blob/master/docs-src/en/src_doc.md Demonstrates how to load AnyProxy rules using NPM modules. This can be done with local modules by providing the path to the module directory or with globally installed modules by specifying the module name after installation. ```bash anyproxy --rule ./myRulePkg/ #local module ``` ```bash npm i -g myRulePkg && anyproxy --rule myRulePkg #global-installed module ``` -------------------------------- ### Using AnyProxy as an npm module Source: https://github.com/alibaba/anyproxy/blob/master/docs/en/src_doc.md Guide on how to integrate and use AnyProxy within your Node.js applications. ```APIDOC ## Use AnyProxy as an npm module Install AnyProxy as a dependency: ```bash npm install anyproxy --save ``` ### Basic Usage ```javascript const AnyProxy = require('anyproxy'); const options = { port: 8001, rule: require('myRuleModule'), webInterface: { enable: true, webPort: 8002 }, throttle: 10000, forceProxyHttps: false, wsIntercept: false, silent: false }; const proxyServer = new AnyProxy.ProxyServer(options); proxyServer.on('ready', () => { /* */ }); proxyServer.on('error', (e) => { /* */ }); proxyServer.start(); // To close the server proxyServer.close(); ``` ### AnyProxy.ProxyServer Class **Constructor**: `new AnyProxy.ProxyServer(options)` **`options`**: - `port` (number): Required. The port number for the proxy server. - `rule` (object): Your custom rule module. - `throttle` (number): Throttle speed in KB/s. Default is unlimited. - `forceProxyHttps` (boolean): Intercept all HTTPS requests. Default is `false`. - `silent` (boolean): Suppress console output. Default is `false`. - `dangerouslyIgnoreUnauthorized` (boolean): Ignore certificate errors. Default is `false`. - `wsIntercept` (boolean): Intercept WebSocket traffic. Default is `false`. - `webInterface` (object): Configuration for the web interface. - `enable` (boolean): Enable the web interface. Default is `false`. - `webPort` (number): The port for the web interface. **Events**: - `ready`: Emitted when the proxy server is ready. ```javascript proxy.on('ready', function() { }); ``` - `error`: Emitted when an error occurs within the proxy server. ```javascript proxy.on('error', function() { }); ``` **Methods**: - `start()`: Starts the proxy server. ```javascript proxy.start(); ``` - `close()`: Closes the proxy server. ```javascript proxy.close(); ``` ``` -------------------------------- ### Using AnyProxy as an NPM Module Source: https://github.com/alibaba/anyproxy/blob/master/docs-src/en/README.md Guide on how to integrate AnyProxy into your Node.js application as a module, including configuration options and event handling. ```APIDOC ## Usage as an NPM Module Install AnyProxy as a dependency: ```bash npm i anyproxy --save ``` ### Basic Usage Example ```js const AnyProxy = require('anyproxy'); const options = { port: 8001, rule: require('myRuleModule'), webInterface: { enable: true, webPort: 8002 }, throttle: 10000, forceProxyHttps: false, wsIntercept: false, silent: false }; const proxyServer = new AnyProxy.ProxyServer(options); proxyServer.on('ready', () => { /* ... */ }); proxyServer.on('error', (e) => { /* ... */ }); proxyServer.start(); // To close the proxy server later // proxyServer.close(); ``` ### Class: `AnyProxy.ProxyServer` * **`new AnyProxy.ProxyServer(options)`**: Creates a new proxy server instance. * **`options`** (object): Configuration for the proxy server. * `port` (number): Required. The port number for the proxy server. * `rule` (object): Your custom rule module. * `throttle` (number): Throttle speed in KB/s. Defaults to unlimited. * `forceProxyHttps` (boolean): Intercept all HTTPS requests. Defaults to `false`. * `silent` (boolean): Suppress console output. Defaults to `false`. * `dangerouslyIgnoreUnauthorized` (boolean): Ignore certificate errors. Defaults to `false`. * `wsIntercept` (boolean): Intercept WebSocket traffic. Defaults to `false`. * `webInterface` (object): Configuration for the web interface. * `enable` (boolean): Enable the web interface. Defaults to `false`. * `webPort` (number): The port for the web interface. * **Events**: * `'ready'`: Emitted when the proxy server is ready. ```js proxy.on('ready', function() { /* ... */ }); ``` * `'error'`: Emitted when an error occurs within the proxy server. ```js proxy.on('error', function(e) { /* ... */ }); ``` * **Methods**: * **`start()`**: Starts the proxy server. ```js proxy.start(); ``` * **`close()`**: Closes the proxy server. ```js proxy.close(); ``` ``` -------------------------------- ### Development Example: Hacking HTTP Response Source: https://github.com/alibaba/anyproxy/blob/master/docs-src/cn/README.md A step-by-step example demonstrating how to intercept a specific HTTP request, modify its response, and delay the response. ```APIDOC ## Development Example: Hacking HTTP Response This example shows how to create a rule module that intercepts responses for `GET http://httpbin.org/user-agent`, adds custom test information to the response body, and delays the response by 5 seconds. ### Step 1: Write the Rule Create a file named `sample.js` with the following content: ```js // file: sample.js module.exports = { summary: 'a rule to hack response', *beforeSendResponse(requestDetail, responseDetail) { if (requestDetail.url === 'http://httpbin.org/user-agent') { const newResponse = responseDetail.response; newResponse.body += '- AnyProxy Hacked!'; return new Promise((resolve, reject) => { setTimeout(() => { // delay resolve({ response: newResponse }); }, 5000); }); } }, }; ``` ### Step 2: Start AnyProxy with the Rule Run AnyProxy from your terminal, specifying the rule file: ```bash anyproxy --rule sample.js ``` ### Step 3: Test the Rule * **Using `curl`**: ```bash curl http://httpbin.org/user-agent --proxy http://127.0.0.1:8001 ``` * **Using a Web Browser**: Configure your browser's HTTP proxy to `127.0.0.1:8001` and visit `http://httpbin.org/user-agent`. * **Expected Response**: After passing through the proxy, the response should look like this (with a 5-second delay): ``` { "user-agent": "curl/7.43.0" } - AnyProxy Hacked! ``` ### Step 4: View Request Information Access the AnyProxy web interface by visiting `http://127.0.0.1:8002` in your browser. You should see the details of the request made in the previous step. ``` -------------------------------- ### Configure and Start AnyProxy Server in Node.js Source: https://github.com/alibaba/anyproxy/wiki/v3.x-AnyProxy-docs Demonstrates how to require the AnyProxy module, generate a root CA for HTTPS traffic if it doesn't exist, and configure a proxy server with various options. This snippet shows how to set up the proxy's port, hostname, rules, database file, web interface port, and other advanced settings. ```javascript var proxy = require("anyproxy"); //create cert when you want to use https features //please manually trust this rootCA when it is the first time you run it !proxy.isRootCAFileExists() && proxy.generateRootCA(); var options = { type : "http", port : 8001, hostname : "localhost", rule : require("path/to/my/ruleModule.js"), dbFile : null, // optional, save request data to a specified file, will use in-memory db if not specified webPort : 8002, // optional, port for web interface socketPort : 8003, // optional, internal port for web socket, replace this when it is conflict with your own service throttle : 10, // optional, speed limit in kb/s disableWebInterface : false, //optional, set it when you don't want to use the web interface setAsGlobalProxy : false, //set anyproxy as your system proxy silent : false //optional, do not print anything into terminal. do not set it when you are still debugging. }; new proxy.proxyServer(options); ``` -------------------------------- ### Integrate AnyProxy as an npm Module in Node.js Source: https://context7.com/alibaba/anyproxy/llms.txt Shows how to integrate AnyProxy into a Node.js application programmatically. It covers configuring proxy options, starting the server, handling events like 'ready' and 'error', and implementing graceful shutdown. ```javascript const AnyProxy = require('anyproxy'); // Configure proxy server const options = { port: 8001, rule: require('./my-rule-module'), webInterface: { enable: true, webPort: 8002 }, throttle: 10000, // 10 MB/s forceProxyHttps: false, wsIntercept: false, silent: false, dangerouslyIgnoreUnauthorized: false }; // Create and start proxy server const proxyServer = new AnyProxy.ProxyServer(options); proxyServer.on('ready', () => { console.log('Proxy server is ready'); console.log(`HTTP proxy: http://127.0.0.1:${options.port}`); console.log(`Web interface: http://127.0.0.1:${options.webInterface.webPort}`); }); proxyServer.on('error', (e) => { console.error('Proxy server error:', e); process.exit(1); }); proxyServer.start(); // Graceful shutdown process.on('SIGINT', async () => { console.log('Shutting down proxy server...'); await proxyServer.close(); process.exit(0); }); ``` -------------------------------- ### Ignore SSL Certificate Errors (Node.js) Source: https://github.com/alibaba/anyproxy/blob/master/docs-src/cn/src_doc.md Configure AnyProxy to ignore SSL certificate validation errors when starting it programmatically in Node.js. Similar to the CLI option, this setting applies globally to all sites and can reduce security. ```javascript const options = { ... dangerouslyIgnoreUnauthorized: true }; const anyproxyIns = new AnyProxy.ProxyCore(options); anyproxyIns.start(); ``` -------------------------------- ### Manage System Proxy Settings with AnyProxy Source: https://github.com/alibaba/anyproxy/blob/master/docs-src/en/src_doc.md Provides examples of how to use AnyProxy's utility functions to manage the system's global proxy settings. It demonstrates enabling the global proxy to point to a specific address and port, and disabling it. ```javascript // set 127.0.0.1:8001 as system http server AnyProxy.utils.systemProxyMgr.enableGlobalProxy('127.0.0.1', '8001'); // disable global proxy server AnyProxy.utils.systemProxyMgr.disableGlobalProxy(); ``` -------------------------------- ### Manage Global Proxy Settings with AnyProxy Source: https://github.com/alibaba/anyproxy/blob/master/docs/cn/index.html Provides examples of using AnyProxy's utility functions to enable and disable system-wide proxy configurations. Note that enabling the global proxy may prompt for administrator privileges. ```javascript // 配置127.0.0.1:8001为全局http代理服务器 AnyProxy.utils.systemProxyMgr.enableGlobalProxy('127.0.0.1', '8001'); // 关闭全局代理服务器 AnyProxy.utils.systemProxyMgr.disableGlobalProxy(); ``` -------------------------------- ### Example Response Detail Object in AnyProxy Source: https://github.com/alibaba/anyproxy/blob/master/docs-src/en/src_doc.md Demonstrates the structure of the 'responseDetail' object passed to the 'beforeSendResponse' function, containing the server's response details and the native response object. ```javascript { response: { statusCode: 200, header: { 'Content-Type': 'image/gif', Connection: 'close', 'Cache-Control': '...' }, body: '...' }, _res: { /* ... */ } } ``` -------------------------------- ### Load AnyProxy Rule from an Online File Source: https://github.com/alibaba/anyproxy/blob/master/docs-src/en/src_doc.md This command starts AnyProxy and loads a custom rule from a Javascript file hosted at a specified URL. This allows for dynamic rule updates without local file management. ```bash anyproxy --rule https://sample.com/rule.js ``` -------------------------------- ### Start AnyProxy and Intercept HTTPS Traffic Source: https://github.com/alibaba/anyproxy/blob/master/docs/cn/index.html This command initiates AnyProxy with the capability to intercept and process HTTPS traffic. It requires the root CA certificate to be generated and trusted by the client system. ```bash anyproxy --intercept ``` -------------------------------- ### Example Request Detail Object in AnyProxy Source: https://github.com/alibaba/anyproxy/blob/master/docs-src/en/src_doc.md Illustrates the structure of the 'requestDetail' object passed to the 'beforeSendRequest' function, including protocol, URL, request options, data, and native request object. ```javascript { protocol: 'http', url: 'http://anyproxy.io/', requestOptions: { hostname: 'anyproxy.io', port: 80, path: '/', method: 'GET', headers: { Host: 'anyproxy.io', 'Proxy-Connection': 'keep-alive', 'User-Agent': '...' } }, requestData: '...', _req: { /* ... */ } } ``` -------------------------------- ### Example Request Detail Structure (AnyProxy) Source: https://github.com/alibaba/anyproxy/blob/master/docs-src/en/README.md Illustrates the structure of the `requestDetail` object passed to `beforeSendRequest` and `beforeDealHttpsRequest`. It includes protocol, URL, request options, request data, and the native Node.js request object. ```javascript { protocol: 'http', url: 'http://anyproxy.io/', requestOptions: { hostname: 'anyproxy.io', port: 80, path: '/', method: 'GET', headers: { Host: 'anyproxy.io', 'Proxy-Connection': 'keep-alive', 'User-Agent': '...' } }, requestData: '...', _req: { /* ... */ } } ``` -------------------------------- ### Launch AnyProxy with HTTPS and WebSocket Interception Source: https://github.com/alibaba/anyproxy/blob/master/docs/en/index.html Shows command-line instructions for launching AnyProxy with specific features enabled. The `anyproxy-ca` command generates the necessary root CA certificate, which must be manually trusted. The `anyproxy --intercept` command starts the proxy and intercepts all HTTPS traffic, while `--ws-intercept` additionally records WebSocket data. ```bash # Generate root CA. Manually trust it after that. anyproxy-ca # Launch AnyProxy and intercept all HTTPS traffic anyproxy --intercept # Intercept WebSocket traffic as well anyproxy --ws-intercept ``` -------------------------------- ### JavaScript: Return Null in AnyProxy beforeSendResponse Source: https://github.com/alibaba/anyproxy/blob/master/docs-src/cn/src_doc.md This example shows how to return null from the `beforeSendResponse` function in AnyProxy. Returning null signifies that no modifications are made to the response, and the original response will be passed through. This is a common way to indicate that the request should proceed without intervention. ```javascript return null; ``` -------------------------------- ### Example Response Detail Structure (AnyProxy) Source: https://github.com/alibaba/anyproxy/blob/master/docs-src/en/README.md Shows the structure of the `responseDetail` object passed to `beforeSendResponse`. It contains the `response` object (with status code, headers, and body) and the native Node.js response object. ```javascript { response: { statusCode: 200, header: { 'Content-Type': 'image/gif', Connection: 'close', 'Cache-Control': '...' }, body: '...' }, _res: { /* ... */ } } ``` -------------------------------- ### JavaScript: Custom Error Page in AnyProxy Source: https://github.com/alibaba/anyproxy/blob/master/docs-src/cn/src_doc.md This example demonstrates how to return a custom error page when an error occurs during request processing in AnyProxy. It defines a response object with a specific status code, content type, and HTML body to be displayed to the client. This allows for more user-friendly error handling. ```javascript return { response: { statusCode: 200, header: { 'content-type': 'text/html' }, body: 'this could be a or ' } }; ``` -------------------------------- ### Sample Rule: Use Local Response - JavaScript Source: https://github.com/alibaba/anyproxy/blob/master/docs/cn/src_doc.md This is a sample AnyProxy rule written in JavaScript that intercepts requests to `http://httpbin.org/` and serves a local response instead of the actual server's response. This is useful for testing or developing without relying on external servers. ```javascript // rule_sample/sample_use_local_response.js module.exports = { //... other configurations * beforeSendResponse(requestDetail, responseDetail) { if (requestDetail.url.includes('httpbin.org')) { responseDetail.response.body = 'This is a local response!'; responseDetail.response.statusCode = 200; return responseDetail; } } }; ``` -------------------------------- ### Start AnyProxy with WebSocket Interception Source: https://github.com/alibaba/anyproxy/blob/master/docs/cn/index.html Enables AnyProxy to intercept and record WebSocket (wss) traffic. This is often used in conjunction with HTTPS interception to capture all types of encrypted communication. ```bash anyproxy --ws-intercept ``` -------------------------------- ### AnyProxy System Proxy Management Source: https://github.com/alibaba/anyproxy/blob/master/docs/en/index.html Provides examples for managing the system's proxy settings using AnyProxy's utility functions. This includes enabling the global proxy to a specific address and port, and disabling it entirely. Note that these operations may require administrator privileges. ```javascript // set 127.0.0.1:8001 as system http server AnyProxy.utils.systemProxyMgr.enableGlobalProxy('127.0.0.1', '8001'); // disable global proxy server AnyProxy.utils.systemProxyMgr.disableGlobalProxy(); ``` -------------------------------- ### Serve Local Responses with JavaScript Source: https://context7.com/alibaba/anyproxy/llms.txt Allows serving local responses instead of forwarding requests to the remote server. This is useful for mocking APIs. The example intercepts requests to httpbin.org and returns a predefined JSON response. No actual request is sent to the remote server. ```javascript // rule-local-response.js module.exports = { summary: 'Serve local responses', *beforeSendRequest(requestDetail) { // Define local response const localResponse = { statusCode: 200, header: { 'Content-Type': 'application/json', 'X-Served-By': 'AnyProxy-Local' }, body: JSON.stringify({ message: 'This is a local response', url: requestDetail.url, method: requestDetail.method, mocked: true }) }; // Intercept and return local response if (requestDetail.url.indexOf('http://httpbin.org') === 0) { return { response: localResponse }; } } }; // Test with curl // curl http://httpbin.org/anything --proxy http://127.0.0.1:8001 // Expected: {"message":"This is a local response","url":"http://httpbin.org/anything","method":"GET","mocked":true} // Note: No actual request is sent to httpbin.org ``` -------------------------------- ### Ignore SSL Certificate Errors (CLI) Source: https://github.com/alibaba/anyproxy/blob/master/docs-src/cn/src_doc.md Bypass SSL certificate validation errors when launching AnyProxy from the command line. This option globally ignores certificate issues for all HTTPS sites, which may pose a security risk. ```bash anyproxy -i --ignore-unauthorized-ssl ``` -------------------------------- ### Requiring a Third-Party Node Module in AnyProxy Rule File Source: https://github.com/alibaba/anyproxy/wiki/v3.x-What-is-rule-file-and-how-to-write-one Illustrates how to import and use an installed third-party Node.js module (e.g., 'underscore') within an AnyProxy rule file. This requires correctly constructing the path to the module within the AnyProxy environment. ```javascript var path = require("path"); var base = path.join(process.env.NODE_PATH, 'anyproxy', 'node_modules'); var underscore = require(path.join(base, 'underscore')); // Now you can use underscore functions, e.g.: // var list = [1, 2, 3, 4]; // console.log(underscore.first(list)); ``` -------------------------------- ### Add Response Header with AnyProxy Source: https://github.com/alibaba/anyproxy/blob/master/docs/en/src_doc.md This code example illustrates how to add custom headers to an HTTP response. It appends an 'X-Proxy-By: AnyProxy' header to responses originating from http://httpbin.org/user-agent. This is useful for server-side identification, debugging, or passing custom metadata to clients. The only dependency is AnyProxy. ```javascript module.exports = { /** * add response header * @param requestDetail * @param requestDetail.response * @returns {Promise<{response: {header: {'X-Proxy-By': string}}>}> */ *beforeSendResponse (requestDetail) { if (requestDetail.url.indexOf('httpbin.org/user-agent') !== -1) { // add header requestDetail.response.header['X-Proxy-By'] = 'AnyProxy'; } return requestDetail; } }; ``` -------------------------------- ### Handle HTTPS Request - AnyProxy JavaScript Source: https://github.com/alibaba/anyproxy/blob/master/docs/cn/src_doc.md This JavaScript code snippet is for the `beforeDealHttpsRequest` function in AnyProxy. Returning `true` instructs AnyProxy to attempt to replace certificates and parse HTTPS traffic, allowing you to see plaintext data. Returning `false` will result in data stream forwarding without decryption. ```javascript return true; ``` -------------------------------- ### Manage System Proxy Settings with AnyProxy (JavaScript) Source: https://context7.com/alibaba/anyproxy/llms.txt This snippet shows how to programmatically enable and disable system-wide proxy settings using AnyProxy's utilities. It includes examples for setting the proxy to a specific address and port, disabling it, and integrating with a running AnyProxy server. Note that enabling/disabling system proxies may require elevated privileges (sudo/admin). Dependencies: 'anyproxy'. ```javascript const AnyProxy = require('anyproxy'); const systemProxyMgr = AnyProxy.utils.systemProxyMgr; // Enable system proxy (may require sudo/admin privileges) systemProxyMgr.enableGlobalProxy('127.0.0.1', 8001) .then(() => { console.log('System proxy enabled'); }) .catch((err) => { console.error('Failed to enable system proxy:', err); }); // Disable system proxy systemProxyMgr.disableGlobalProxy() .then(() => { console.log('System proxy disabled'); }) .catch((err) => { console.error('Failed to disable system proxy:', err); }); // Example: Temporary proxy usage const proxyServer = new AnyProxy.ProxyServer({ port: 8001 }); proxyServer.on('ready', async () => { // Enable system proxy when server is ready await systemProxyMgr.enableGlobalProxy('127.0.0.1', 8001); console.log('Proxy server running with system-wide configuration'); }); // Cleanup on exit process.on('SIGINT', async () => { await systemProxyMgr.disableGlobalProxy(); await proxyServer.close(); process.exit(0); }); proxyServer.start(); ``` -------------------------------- ### Sample Rule: Modify Request Header - JavaScript Source: https://github.com/alibaba/anyproxy/blob/master/docs/cn/src_doc.md This sample AnyProxy rule in JavaScript modifies the `User-Agent` header for requests sent to `http://httpbin.org/`. It demonstrates how to intercept a request, modify its headers, and return the modified request. This is useful for simulating different clients or testing server-side routing. ```javascript // rule_sample/sample_modify_request_header.js module.exports = { //... other configurations * beforeSendRequest(requestDetail) { if (requestDetail.url.includes('httpbin.org')) { requestDetail.requestOptions.headers['User-Agent'] = 'AnyProxy-Test-Agent'; return requestDetail; } } }; ``` -------------------------------- ### Modify Request Protocol with AnyProxy Source: https://github.com/alibaba/anyproxy/blob/master/docs/en/src_doc.md This code example shows how to change the protocol of an HTTP request to HTTPS. It targets requests to http://httpbin.org and modifies them to use https. This is valuable for enforcing secure connections or testing how applications handle protocol upgrades. The essential dependency is AnyProxy. ```javascript module.exports = { /** * modify request protocol * @param requestDetail * @param requestDetail.url * @returns {Promise<{requestOptions: {url: string}}> */ *beforeSendRequest (requestDetail) { if (requestDetail.url.indexOf('http://httpbin.org') !== -1) { // modify protocol from http to https requestDetail.url = requestDetail.url.replace('http://', 'https://'); } return requestDetail; } }; ``` -------------------------------- ### Bypass Specific SSL Certificate Errors (Rule) Source: https://github.com/alibaba/anyproxy/blob/master/docs-src/cn/src_doc.md Implement a custom AnyProxy rule to selectively bypass SSL certificate validation for specific websites. This approach allows for more granular control over security by only ignoring errors for trusted domains. ```javascript module.exports = { *beforeSendRequest(requestDetail) { if (requestDetail.url.indexOf('https://the-site-you-know.com') === 0) { const newRequestOptions = requestDetail.requestOptions; // Set the rejectUnauthorized property to false newRequestOptions.rejectUnauthorized = false; return { requestOptions: newRequestOptions }; } } }; ``` -------------------------------- ### Append Text to HTML Responses with AnyProxy Source: https://github.com/alibaba/anyproxy/wiki/v3.x-代理服务器的新轮子:anyproxy This example shows how to modify the response data by appending 'Hello World!' to the end of all HTML content. It uses the `replaceServerResDataAsync` interface and checks the 'content-type' header to ensure the modification is applied only to HTML files. ```javascript module.exports = { replaceServerResDataAsync: function(req,res,serverResData,callback){ //append "hello world" to all web pages if(/html/i.test(res.headers['content-type'])){ var newDataStr = serverResData.toString(); newDataStr += "hello world!"; callback(newDataStr); }else{ callback(serverResData); } } }; ``` -------------------------------- ### Sample Rule: Modify Request Path - JavaScript Source: https://github.com/alibaba/anyproxy/blob/master/docs/cn/src_doc.md This sample AnyProxy rule in JavaScript redirects all requests intended for `http://httpbin.org/` to `http://httpbin.org/user-agent`. It intercepts the request, changes the URL path, and returns the modified request. This is useful for testing different endpoints or for load balancing scenarios. ```javascript // rule_sample/sample_modify_request_path.js module.exports = { //... other configurations * beforeSendRequest(requestDetail) { if (requestDetail.url.includes('httpbin.org/')) { requestDetail.url = 'http://httpbin.org/user-agent'; return requestDetail; } } }; ``` -------------------------------- ### Modify Request Headers with AnyProxy Rule Module Source: https://context7.com/alibaba/anyproxy/llms.txt Provides a JavaScript rule module example for AnyProxy that intercepts outgoing requests and modifies HTTP headers, specifically targeting a domain and updating the 'User-Agent' and adding a custom header. Includes a curl test command. ```javascript // rule-modify-headers.js module.exports = { summary: 'Modify request headers', *beforeSendRequest(requestDetail) { // Target specific domain if (requestDetail.url.indexOf('http://httpbin.org') === 0) { const newRequestOptions = requestDetail.requestOptions; // Modify User-Agent header newRequestOptions.headers['User-Agent'] = 'AnyProxy/CustomAgent'; // Add custom headers newRequestOptions.headers['X-Custom-Header'] = 'custom-value'; return { requestOptions: newRequestOptions }; } } }; // Test with curl // curl http://httpbin.org/user-agent --proxy http://127.0.0.1:8001 // Expected: {"user-agent": "AnyProxy/CustomAgent"} ``` -------------------------------- ### Sample Rule: Modify Response Header - JavaScript Source: https://github.com/alibaba/anyproxy/blob/master/docs/cn/src_doc.md This sample AnyProxy rule in JavaScript adds a custom header `X-Proxy-By: AnyProxy` to the responses from `http://httpbin.org/user-agent`. It intercepts the response, adds the header to the `response.header` object, and returns the modified response. This is useful for adding custom metadata to responses. ```javascript // rule_sample/sample_modify_response_header.js module.exports = { //... other configurations * beforeSendResponse(requestDetail, responseDetail) { if (requestDetail.url.includes('httpbin.org/user-agent')) { responseDetail.response.header['X-Proxy-By'] = 'AnyProxy'; return responseDetail; } } }; ``` -------------------------------- ### Sample Rule: Modify Response Status Code - JavaScript Source: https://github.com/alibaba/anyproxy/blob/master/docs/cn/src_doc.md This sample AnyProxy rule in JavaScript forces all responses from `http://httpbin.org/` to have a status code of 404. It intercepts the response, modifies the `statusCode` property, and returns the modified response. This is useful for testing how clients handle error responses. ```javascript // rule_sample/sample_modify_response_statuscode.js module.exports = { //... other configurations * beforeSendResponse(requestDetail, responseDetail) { if (requestDetail.url.includes('httpbin.org')) { responseDetail.response.statusCode = 404; return responseDetail; } } }; ``` -------------------------------- ### Sample Rule: Modify Request Protocol - JavaScript Source: https://github.com/alibaba/anyproxy/blob/master/docs/cn/src_doc.md This sample AnyProxy rule in JavaScript changes the protocol for requests to `http://httpbin.org/` from HTTP to HTTPS. It intercepts the request, modifies the URL to use HTTPS, and returns the modified request. This is useful for testing how applications handle protocol changes or for enforcing secure connections. ```javascript // rule_sample/sample_modify_request_protocol.js module.exports = { //... other configurations * beforeSendRequest(requestDetail) { if (requestDetail.url.startsWith('http://httpbin.org')) { requestDetail.url = requestDetail.url.replace('http://', 'https://'); return requestDetail; } } }; ``` -------------------------------- ### Sample Rule: Modify Response Body and Delay - JavaScript Source: https://github.com/alibaba/anyproxy/blob/master/docs/cn/src_doc.md This sample AnyProxy rule in JavaScript appends text to the response body of requests to `http://httpbin.org/user-agent` and introduces a 5-second delay before sending the response. It intercepts the response, modifies the body, and uses `responseDetail.response.delay` to set the delay. This is useful for testing client behavior under slow network conditions. ```javascript // rule_sample/sample_modify_response_data.js module.exports = { //... other configurations * beforeSendResponse(requestDetail, responseDetail) { if (requestDetail.url.includes('httpbin.org/user-agent')) { responseDetail.response.body += '--from AnyProxy'; responseDetail.response.delay = 5000; // 5 seconds delay return responseDetail; } } }; ``` -------------------------------- ### AnyProxy 引用规则:本地 NPM 包 Source: https://github.com/alibaba/anyproxy/blob/master/docs-src/cn/README.md 说明了如何将本地 NPM 包作为规则模块加载到 AnyProxy 中。这有助于组织和管理复杂的规则。 ```bash anyproxy --rule ./myRulePkg/ ``` -------------------------------- ### Use AnyProxy as an npm module Source: https://github.com/alibaba/anyproxy/blob/master/docs-src/en/src_doc.md Demonstrates how to use AnyProxy programmatically within a Node.js application. It shows the instantiation of the ProxyServer with various options and event handling for 'ready' and 'error'. ```javascript const AnyProxy = require('anyproxy'); const options = { port: 8001, rule: require('myRuleModule'), webInterface: { enable: true, webPort: 8002 }, throttle: 10000, forceProxyHttps: false, wsIntercept: false, silent: false }; const proxyServer = new AnyProxy.ProxyServer(options); proxyServer.on('ready', () => { /* */ }); proxyServer.on('error', (e) => { /* */ }); proxyServer.start(); //when finished proxyServer.close(); ``` -------------------------------- ### AnyProxy 引用规则:本地路径 Source: https://github.com/alibaba/anyproxy/blob/master/docs-src/cn/README.md 展示了如何通过本地文件路径来启动 AnyProxy 并加载规则模块。这是最直接的规则应用方式。 ```bash anyproxy --rule ./rule.js ``` -------------------------------- ### AnyProxy 引用规则:全局 NPM 包 Source: https://github.com/alibaba/anyproxy/blob/master/docs-src/cn/README.md 展示了如何安装全局 NPM 包后,再将其作为规则模块加载到 AnyProxy。这使得规则模块可以在全局范围内被 AnyProxy 调用。 ```bash npm i -g myRulePkg && anyproxy --rule myRulePkg ``` -------------------------------- ### Modify Request Headers in AnyProxy Source: https://github.com/alibaba/anyproxy/blob/master/docs/cn/index.html Modifies request headers for requests targeting a specific URL (e.g., httpbin.org). This example changes the 'User-Agent' header before the request is sent to the server. ```javascript module.exports = { *beforeSendRequest(requestDetail) { if (requestDetail.url.indexOf('http://httpbin.org') === 0) { const newRequestOptions = requestDetail.requestOptions; newRequestOptions.headers['User-Agent'] = 'AnyProxy/0.0.0'; return { requestOptions: newRequestOptions }; } } }; ``` -------------------------------- ### Modify Response Data with JavaScript Source: https://context7.com/alibaba/anyproxy/llms.txt Intercepts and modifies server responses before they reach the client. This example appends text to the response body and introduces a delay. It requires AnyProxy to be running. ```javascript // rule-modify-response.js module.exports = { summary: 'Modify response data', *beforeSendResponse(requestDetail, responseDetail) { if (requestDetail.url === 'http://httpbin.org/user-agent') { const newResponse = responseDetail.response; // Append to response body newResponse.body += ' -- Modified by AnyProxy --'; // Return with optional delay return new Promise((resolve) => { setTimeout(() => { resolve({ response: newResponse }); }, 1000); }); } } }; // Test with curl // curl 'http://httpbin.org/user-agent' --proxy http://127.0.0.1:8001 // Expected: {"user-agent": "curl/7.x.x"} -- Modified by AnyProxy -- ``` -------------------------------- ### AnyProxy.utils.systemProxyMgr Source: https://github.com/alibaba/anyproxy/blob/master/docs/en/index.html Utilities for managing the system's proxy settings. ```APIDOC ## AnyProxy.utils.systemProxyMgr ### Description Manages the system proxy configuration. May require sudo password. ### Methods #### `enableGlobalProxy(host: string, port: string)` - **Description**: Sets the system proxy to the specified host and port. - **Sample**: `AnyProxy.utils.systemProxyMgr.enableGlobalProxy('127.0.0.1', '8001');` #### `disableGlobalProxy()` - **Description**: Disables the system proxy settings. - **Sample**: `AnyProxy.utils.systemProxyMgr.disableGlobalProxy();` ```