可以高度定制的代理服務器anyproxy


簡介

anyproxy是一款可以高度定制的代理服務器,基於nodejs。

特征

支持https明文代理 支持低網速模擬 支持二次開發,可以用javascript控制代理的全部流程,搭建前端個性化調試環境 提供web版界面,觀測請求情況

設計

anyproxy把http通信過程中的各個階段進行抽離,分解成三個階段:

收到來自客戶端請求之后,允許開發者直接從本地提供返回 在轉發請求到服務器前,允許開發者對發送的請求進行修改 在收到服務器響應之后,允許開發者對響應內容進行修改,再返回給客戶端

代理流程

對於上述每個階段,anyproxy都提供了API接口,引入開發者編寫自己的規則代碼,實時干預通信過程,以此滿足各類自定義需求。

具體地,我們提供的接口包括:

收到用戶請求之后

shouldUseLocalResponse ,是否在本地直接發送響應(不再向服務器發出請求) dealLocalResponse 如果shouldUseLocalResponse返回true,會調用這個函數來獲取本地響應內容(異步接口) 向服務端發出請求之前

replaceRequestProtocol 替換向服務器發出的請求協議,支持http和https的替換 replaceRequestOption 替換向服務器發出的請求參數,即nodeJS中的 request option replaceRequestData 替換請求的body 向用戶返回服務端的響應之前

replaceResponseStatusCode 替換服務器響應的http狀態碼 replaceResponseHeader 替換服務器響應的http頭 replaceServerResDataAsync 替換服務器響應的數據(異步接口) pauseBeforeSendingResponse 在請求返回給用戶前的延遲時間

快速開始

安裝

安裝Nodejs npm install -g anyproxy,有可能需要sudo python可選安裝

啟動

默認啟動anyproxy 定制啟動端口anyproxy --port 8001 使用某個規則文件anyproxy --rule ./rule_sample/rule_allow_CORS.js 代理https請求anyproxy --intercept(需要安裝證書,詳情見下文) 其他命令可以通過anyproxy -h查看

加載網頁界面

訪問https://127.0.0.1:8002,你會在瀏覽器里看到實時的請求。 要確保是現代瀏覽器
web

HTTPS相關教程

生成RootCA

命令行執行 sudo anyproxy –root 找到RootCA文件

方法一: 執行完成之后,會打開證書的安裝路徑,即可看到 rootCA.crt 文件 方法二: 啟動anyproxy,瀏覽器打開 https://localhost:8002/fetchCrtFile ,也能獲取rootCA.crt文件 方法三:啟動anyproxy,https://localhost:8002/qr_root 可以獲取證書路徑的二維碼,移動端安裝時會比較便捷 打開上述rootCA.crt文件 根據操作系統提示,信任rootCA
windows
mac其他

如果在訪問時出現UNAUTHORIZED_CERTIFICATE一類的安全警告,請重新檢查證書的安裝情況 證書只需生成一次,使用前每個終端都需要信任它

明文解析HTTPS

需要解析HTTPS時,用intercept參數來啟動anyproxy anyproxy --intercept 為終端設置代理,在UI界面就能看到明文的HTTPS請求數據了,帶把小鎖的就是HTTPS請求

進階 - 用rule來手動處理https請求(如:代理文件到本地)

AnyProxy默認不會解析https請求,你需要引入shouldInterceptHttpsReq這個函數來顯式指定解析哪個請求。具體可以參照這份sample : rule_intercept_some_https_requests.js

其他

anyproxy --clear可以清除所有已生成的證書。清除后,各終端需要重新安裝證書。 日常開發中,不要使用anyproxy --type https來調試。AnyProxy使用https over http的方法來進行代理,而這條命令啟動的是一個https代理服務器,兩者使用場景完全不同。

AnyProxy規則文件樣例

修改請求頭:防止CDN返回304

以“防止CDN返回304”這個需求為例,最直接的方案是攔截請求,在發送到CDN前刪除header中的if-modified-since字段。在AnyProxy中,配置replaceRequestOption接口,3行代碼就能實現這個自定義功能:

?
1
2
3
4
5
6
7
8
9
// rule file
module.exports = {
   //在向服務器發出請求前,AnyProxy會調用這個接口,可以在此時修改發送請求的參數
   replaceRequestOption : function (req, option ){
       var newOption = option ;
       delete newOption.headers[ 'if-modified-since' ];
       return newOption;
   }
};

修改響應數據

再舉個例子,如果你想修改響應數據,在所有html文件最后加個”Hello World”,就需要調用replaceServerResDataAsync接口,並結合content-type字段來進行修改,大約需要8行代碼。

?
1
2
3
4
5
6
7
8
9
10
11
12
13
// rule file
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);
         }
     }
};

把所有的響應延遲1500毫秒

?
1
2
3
4
5
6
7
8
module.exports = {
 
     pauseBeforeSendingResponse : function (req,res){
         //delay all the response for 1500ms
         return 1500;
     }
 
};

為ajax請求增加跨域頭

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
// rule scheme :
 
module.exports = {
     shouldUseLocalResponse : function (req,reqBody){
         //intercept all options request
         if(req.method == "OPTIONS" ){
             return true ;
         } else {
             return false ;
         }
     },
 
     dealLocalResponse : function (req,reqBody,callback){
         if(req.method == "OPTIONS" ){
             callback(200,mergeCORSHeader(req.headers), "" );
         }
     },
 
     replaceResponseHeader: function (req,res,header){
         return mergeCORSHeader(req.headers, header);
     }
 
};
 
function mergeCORSHeader(reqHeader,originHeader){
     var targetObj = originHeader || {};
 
     delete targetObj[ "Access-Control-Allow-Credentials" ];
     delete targetObj[ "Access-Control-Allow-Origin" ];
     delete targetObj[ "Access-Control-Allow-Methods" ];
     delete targetObj[ "Access-Control-Allow-Headers" ];
 
     targetObj[ "access-control-allow-credentials" ] = "true" ;
     targetObj[ "access-control-allow-origin" ]      = reqHeader[ 'origin' ] || "-___-||" ;
     targetObj[ "access-control-allow-methods" ]     = "GET, POST, PUT" ;
     targetObj[ "access-control-allow-headers" ]     = reqHeader[ 'access-control-request-headers' ] || "-___-||" ;
 
     return targetObj;
}

截獲github.com的https請求,再在最后加點文字

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
module.exports = {
 
 
     replaceServerResDataAsync: function (req,res,serverResData,callback){
         // add "hello github" to all github pages
         if(req.headers.host == "github.com" ){
             serverResData += "hello github" ;
         }
         callback(serverResData);
     },
 
     shouldInterceptHttpsReq : function (req){
         //intercept https://github.com/
         //otherwise, all the https traffic will not go through this proxy
 
         // return true ;
         if(req.headers.host == "github.com" ){
             return true ;
         } else {
             return false ;
         }
     }
};

去除響應頭里緩存相關的頭

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
// rule scheme :
 
module.exports = {
   replaceRequestOption : function (req, option ){
       var newOption = option ;
       delete newOption.headers[ 'if-none-match' ];
       delete newOption.headers[ 'if-modified-since' ];
 
       return newOption;
   },
 
     replaceResponseHeader: function (req,res,header){
         header = header || {};
         header[ "Cache-Control" ]                    = "no-cache, no-store, must-revalidate" ;
         header[ "Pragma" ]                           = "no-cache" ;
         header[ "Expires" ]                          = 0;
 
         return header;
     }
};

在請求發送到服務端前對參數做一些調整

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
module.exports = {
 
     replaceRequestOption : function (req, option ){
         // replace request towards https://www.taobao.com
         //                     to https://www.taobao.com/about/
 
         /*
         option scheme:
         {
             hostname : "www.taobao.com"
             port     : 80
             path     : "/"
             method   : "GET"
             headers  : {cookie:""}
         }
         */
         if( option .hostname == "www.taobao.com" && option .path == "/" ){
             option .path = "/about/" ;
         }
     }
};

改變服務端響應的http狀態碼

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
module.exports = {
 
     replaceResponseStatusCode: function (req,res,statusCode){
         //redirect requests toward https://www.taobao.com/*
         //                      to https://www.etao.com
         //using 302
 
         if(req.headers.host == "www.taobao.com" ){
             statusCode = 302;
         }
 
         return statusCode;
     },
 
     replaceResponseHeader: function (req,res,header){
         if(req.headers.host == "www.taobao.com" ){
             header.location = "https://www.etao.com" ;
         }
 
         return header;
     }
};

把響應映射到本地

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
// replace all the images with local one
var fs      = require( "fs" );
 
var LOCAL_IMAGE = "/Users/path/to/image.png" ;
 
module.exports = {
 
     summary: function (){
         return "replace all the images with local one" ;
     },
 
     //mark if use local response
     shouldUseLocalResponse : function (req,reqBody){
         if(/\.(png|gif|jpg|jpeg)$/.test(req.url)){
             req.replaceLocalFile = true ;
             return true ;
         } else {
             return false ;
         }
     },
 
     dealLocalResponse : function (req,reqBody,callback){
         if(req.replaceLocalFile){
             callback(200, { "content-type" : "image/png" }, fs.readFileSync(LOCAL_IMAGE) );
         }
     }
};

整體結構

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
/*
read the following wiki before using rule file
*/
module.exports = {
   /*
   These functions will overwrite the default ones, write your own when necessary.
     Comments in Chinese are nothing but a translation of key points. Be relax if you dont understand.
     致中文用戶:中文注釋都是只摘要,必要時請參閱英文文檔。歡迎提出修改建議。
   */
     summary: function (){
         return "this is a blank rule for AnyProxy" ;
     },
 
 
 
 
     //=======================
     // when getting a request from user
     //收到用戶請求之后
     //=======================
 
     //是否截獲https請求
     //should intercept https request, or it will be forwarded to real server
     shouldInterceptHttpsReq : function (req){
         return false ;
     },
 
     //是否在本地直接發送響應(不再向服務器發出請求)
   //whether to intercept this request by local logic
   //if the return value is true , anyproxy will call dealLocalResponse to get response data and will not send request to remote server anymore
     //req is the user 's request sent to the proxy server
   shouldUseLocalResponse : function(req,reqBody){
         return false;
   },
 
     //如果shouldUseLocalResponse返回true,會調用這個函數來獲取本地響應內容
     //you may deal the response locally instead of sending it to server
     //this function be called when shouldUseLocalResponse returns true
     //callback(statusCode,resHeader,responseData)
     //e.g. callback(200,{"content-type":"text/html"},"hello world")
   dealLocalResponse : function(req,reqBody,callback){
         callback(statusCode,resHeader,responseData)
   },
 
 
 
     //=======================
     //when ready to send a request to server
     //向服務端發出請求之前
     //=======================
 
     //替換向服務器發出的請求協議(http和https的替換)
     //replace the request protocol when sending to the real server
     //protocol : "http" or "https"
     replaceRequestProtocol:function(req,protocol){
       var newProtocol = protocol;
       return newProtocol;
     },
 
     //替換向服務器發出的請求參數(option)
     //option is the configuration of the http request sent to remote server. You may refers to https://nodejs.org/api/http.html#http_http_request_options_callback
     //you may return a customized option to replace the original one
     //you should not overwrite content-length header in options, since anyproxy will handle it for you
     replaceRequestOption : function(req,option){
         var newOption = option;
         return newOption;
     },
 
     //替換請求的body
     //replace the request body
     replaceRequestData: function(req,data){
         return data;
     },
 
 
 
     //=======================
     //when ready to send the response to user after receiving response from server
     //向用戶返回服務端的響應之前
     //=======================
 
     //替換服務器響應的http狀態碼
     //replace the statusCode before it' s sent to the user
     replaceResponseStatusCode: function (req,res,statusCode){
       var newStatusCode = statusCode;
       return newStatusCode;
     },
 
     //替換服務器響應的http頭
     // replace the httpHeader before it 's sent to the user
     //Here header == res.headers
     replaceResponseHeader: function(req,res,header){
       var newHeader = header;
       return newHeader;
     },
 
     //替換服務器響應的數據
     //replace the response from the server before it' s sent to the user
     //you may return either a Buffer or a string
     //serverResData is a Buffer. for those non-unicode reponse , serverResData.toString() should not be your first choice.
     replaceServerResDataAsync: function (req,res,serverResData,callback){
         callback(serverResData);
     },
 
     //Deprecated
     // replaceServerResData: function (req,res,serverResData){
     //     return serverResData;
     // },
 
     //在請求返回給用戶前的延遲時間
     // add a pause before sending response to user
     pauseBeforeSendingResponse : function (req,res){
       var timeInMS = 1; //delay all requests for 1ms
       return timeInMS;
     }
 
};

AnyProxy其他特性

支持Https的中間人(man-in-the-middle)代理,同時提供便捷的根證書安裝路徑,方便移動端導入證書 低網速網速模擬,協助調試2G/3G下的表現 可以導出所有請求記錄,供后期數據分析使用 可以進行模塊化調用,做二次封裝,合並到現有的前端集成開發環境中,個性化搭建自己的調試環境

文檔和支持

HTTPS相關配置的中文文檔

What is rule file and how to write one

代理服務器的新輪子:anyproxy

 

轉載:https://www.2cto.com/kf/201707/654139.html


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM