forked from codemanki/cloudscraper
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
258 lines (209 loc) · 8.02 KB
/
index.js
File metadata and controls
258 lines (209 loc) · 8.02 KB
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
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
var vm = require('vm');
var requestModule = require('request');
var jar = requestModule.jar();
var request = requestModule.defaults({jar: jar}), // Cookies should be enabled
UserAgent = 'Ubuntu Chromium/34.0.1847.116 Chrome/34.0.1847.116 Safari/537.36',
Timeout = 6000, // Cloudflare requires a delay of 5 seconds, so wait for at least 6.
cloudscraper = {};
/**
* Performs get request to url with headers.
* @param {String} url
* @param {Function} callback function(error, response, body) {}
* @param {Object} headers Hash with headers, e.g. {'Referer': 'http://google.com', 'User-Agent': '...'}
*/
cloudscraper.get = function(url, callback, headers) {
performRequest({
method: 'GET',
url: url,
headers: headers
}, callback);
};
/**
* Performs post request to url with headers.
* @param {String} url
* @param {String|Object} body Will be passed as form data
* @param {Function} callback function(error, response, body) {}
* @param {Object} headers Hash with headers, e.g. {'Referer': 'http://google.com', 'User-Agent': '...'}
*/
cloudscraper.post = function(url, body, callback, headers) {
var data = '',
bodyType = Object.prototype.toString.call(body);
if(bodyType === '[object String]') {
data = body;
} else if (bodyType === '[object Object]') {
data = Object.keys(body).map(function(key) {
return key + '=' + body[key];
}).join('&');
}
headers = headers || {};
headers['Content-Type'] = headers['Content-Type'] || 'application/x-www-form-urlencoded; charset=UTF-8';
headers['Content-Length'] = headers['Content-Length'] || data.length;
performRequest({
method: 'POST',
body: data,
url: url,
headers: headers
}, callback);
}
/**
* Performs get or post request with generic request options
* @param {Object} options Object to be passed to request's options argument
* @param {Function} callback function(error, response, body) {}
*/
cloudscraper.request = function(options, callback) {
performRequest(options, callback);
}
function performRequest(options, callback) {
var method;
options = options || {};
options.headers = options.headers || {};
makeRequest = requestMethod(options.method);
//Can't just do the normal options.encoding || 'utf8'
//because null is a valid encoding.
if('encoding' in options) {
options.realEncoding = options.encoding;
} else {
options.realEncoding = 'utf8';
}
options.encoding = null;
if (!options.url || !callback) {
throw new Error('To perform request, define both url and callback');
}
options.headers['User-Agent'] = options.headers['User-Agent'] || UserAgent;
makeRequest(options, function(error, response, body) {
var validationError;
var stringBody;
if (error || !body || !body.toString) {
return callback({ errorType: 0, error: error }, body, response);
}
stringBody = body.toString('utf8');
if (validationError = checkForErrors(error, stringBody)) {
return callback(validationError, body, response);
}
// If body contains specified string, solve challenge
if (stringBody.indexOf('a = document.getElementById(\'jschl-answer\');') !== -1) {
setTimeout(function() {
return solveChallenge(response, stringBody, options, callback);
}, Timeout);
} else if (stringBody.indexOf('You are being redirected') !== -1 ||
stringBody.indexOf('sucuri_cloudproxy_js') !== -1) {
setCookieAndReload(response, stringBody, options, callback);
} else {
// All is good
processResponseBody(options, error, response, body, callback);
}
});
}
function checkForErrors(error, body) {
var match;
// Pure request error (bad connection, wrong url, etc)
if(error) {
return { errorType: 0, error: error };
}
// Finding captcha
if (body.indexOf('why_captcha') !== -1 || /cdn-cgi\/l\/chk_captcha/i.test(body)) {
return { errorType: 1 };
}
// trying to find '<span class="cf-error-code">1006</span>'
match = body.match(/<\w+\s+class="cf-error-code">(.*)<\/\w+>/i);
if (match) {
return { errorType: 2, error: parseInt(match[1]) };
}
return false;
}
function solveChallenge(response, body, options, callback) {
var challenge = body.match(/name="jschl_vc" value="(\w+)"/),
host = response.request.host,
makeRequest = requestMethod(options.method),
jsChlVc,
answerResponse,
answerUrl;
if (!challenge) {
return callback({errorType: 3, error: 'I cant extract challengeId (jschl_vc) from page'}, body, response);
}
jsChlVc = challenge[1];
challenge = body.match(/getElementById\('cf-content'\)[\s\S]+?setTimeout.+?\r?\n([\s\S]+?a\.value =.+?)\r?\n/i);
if (!challenge) {
return callback({errorType: 3, error: 'I cant extract method from setTimeOut wrapper'}, body, response);
}
challenge_pass = body.match(/name="pass" value="(.+?)"/)[1];
challenge = challenge[1];
challenge = challenge.replace(/a\.value =(.+?) \+ .+?;/i, '$1');
challenge = challenge.replace(/\s{3,}[a-z](?: = |\.).+/g, '');
challenge = challenge.replace(/'; \d+'/g, '');
try {
answerResponse = {
'jschl_vc': jsChlVc,
'jschl_answer': (eval(challenge) + response.request.host.length),
'pass': challenge_pass
};
} catch (err) {
return callback({errorType: 3, error: 'Error occurred during evaluation: ' + err.message}, body, response);
}
answerUrl = response.request.uri.protocol + '//' + host + '/cdn-cgi/l/chk_jschl';
options.headers['Referer'] = response.request.uri.href; // Original url should be placed as referer
options.url = answerUrl;
options.qs = answerResponse;
// Make request with answer
makeRequest(options, function(error, response, body) {
if(error) {
return callback({ errorType: 0, error: error }, response, body);
}
if(response.statusCode === 302) { //occurrs when posting. request is supposed to auto-follow these
//by default, but for some reason it's not
options.url = response.headers.location;
delete options.qs;
makeRequest(options, function(error, response, body) {
processResponseBody(options, error, response, body, callback);
});
} else {
processResponseBody(options, error, response, body, callback);
}
});
}
function setCookieAndReload(response, body, options, callback) {
var challenge = body.match(/S='([^']+)'/);
var makeRequest = requestMethod(options.method);
if (!challenge) {
return callback({errorType: 3, error: 'I cant extract cookie generation code from page'}, body, response);
}
var base64EncodedCode = challenge[1];
var cookieSettingCode = new Buffer(base64EncodedCode, 'base64').toString('ascii');
var sandbox = {
location: {
reload: function() {}
},
document: {}
};
vm.runInNewContext(cookieSettingCode, sandbox);
try {
jar.setCookie(sandbox.document.cookie, response.request.uri.href, {ignoreError: true});
} catch (err) {
return callback({errorType: 3, error: 'Error occurred during evaluation: ' + err.message}, body, response);
}
makeRequest(options, function(error, response, body) {
if(error) {
return callback({ errorType: 0, error: error }, response, body);
}
processResponseBody(options, error, response, body, callback);
});
}
// Workaround for better testing. Request has pretty poor API
function requestMethod(method) {
// For now only GET and POST are supported
method = method.toUpperCase();
return method === 'POST' ? request.post : request.get;
}
function processResponseBody(options, error, response, body, callback) {
if(typeof options.realEncoding === 'string') {
body = body.toString(options.realEncoding);
// In case of real encoding, try to validate the response
// and find potential errors there.
// If encoding is not provided, return response as it is
if (validationError = checkForErrors(error, body)) {
return callback(validationError, response, body);
}
}
callback(error, response, body);
}
module.exports = cloudscraper;