-
Notifications
You must be signed in to change notification settings - Fork 30
/
prevent-xhr.js
369 lines (345 loc) · 13.1 KB
/
prevent-xhr.js
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
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
import {
hit,
objectToString,
generateRandomResponse,
matchRequestProps,
getXhrData,
logMessage,
toRegExp,
isValidStrPattern,
escapeRegExp,
isEmptyObject,
getNumberFromString,
nativeIsFinite,
nativeIsNaN,
parseMatchProps,
isValidParsedData,
getMatchPropsData,
getRequestProps,
getRandomIntInclusive,
getRandomStrByLength,
} from '../helpers';
/* eslint-disable max-len */
/**
* @scriptlet prevent-xhr
*
* @description
* Prevents `xhr` calls if **all** given parameters match.
*
* Related UBO scriptlet:
* https://github.com/gorhill/uBlock/wiki/Resources-Library#no-xhr-ifjs-
*
* ### Syntax
*
* ```text
* example.org#%#//scriptlet('prevent-xhr'[, propsToMatch[, randomize]])
* ```
*
* - `propsToMatch` — optional, string of space-separated properties to match; possible props:
* - string or regular expression for matching the URL passed to `XMLHttpRequest.open()` call;
* empty string or wildcard `*` for all `XMLHttpRequest.open()` calls match
* - colon-separated pairs `name:value` where
* - `name` is XMLHttpRequest object property name
* - `value` is string or regular expression for matching the value of the option
* passed to `XMLHttpRequest.open()` call
* - `randomize` — defaults to `false` for empty responseText,
* optional argument to randomize responseText and response of matched XMLHttpRequest's response; possible values:
* - `true` to randomize responseText and response, random alphanumeric string of 10 symbols
* - colon-separated pair `name:value` string value to customize responseText and response data where
* - `name` — only `length` supported for now
* - `value` — range on numbers, for example `100-300`, limited to 500000 characters
*
* > Usage with no arguments will log XMLHttpRequest objects to browser console;
* > it may be useful for debugging but it is not allowed for prod versions of filter lists.
*
* ### Examples
*
* 1. Log all XMLHttpRequests
*
* ```adblock
* example.org#%#//scriptlet('prevent-xhr')
* ```
*
* 1. Prevent all XMLHttpRequests
*
* ```adblock
* example.org#%#//scriptlet('prevent-xhr', '*')
* example.org#%#//scriptlet('prevent-xhr', '')
* ```
*
* 1. Prevent XMLHttpRequests for specific url
*
* ```adblock
* example.org#%#//scriptlet('prevent-xhr', 'example.org')
* ```
*
* 1. Prevent XMLHttpRequests for specific request method
*
* ```adblock
* example.org#%#//scriptlet('prevent-xhr', 'method:HEAD')
* ```
*
* 1. Prevent XMLHttpRequests for specific url and specified request methods
*
* ```adblock
* example.org#%#//scriptlet('prevent-xhr', 'example.org method:/HEAD|GET/')
* ```
*
* 1. Prevent XMLHttpRequests for specific url and randomize it's response text
*
* ```adblock
* example.org#%#//scriptlet('prevent-xhr', 'example.org', 'true')
* ```
*
* 1. Prevent XMLHttpRequests for specific url and randomize it's response text with range
*
* ```adblock
* example.org#%#//scriptlet('prevent-xhr', 'example.org', 'length:100-300')
* ```
*
* @added v1.5.0.
*/
/* eslint-enable max-len */
export function preventXHR(source, propsToMatch, customResponseText) {
// do nothing if browser does not support Proxy (e.g. Internet Explorer)
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy
if (typeof Proxy === 'undefined') {
return;
}
const nativeOpen = window.XMLHttpRequest.prototype.open;
const nativeGetResponseHeader = window.XMLHttpRequest.prototype.getResponseHeader;
const nativeGetAllResponseHeaders = window.XMLHttpRequest.prototype.getAllResponseHeaders;
let xhrData;
let modifiedResponse = '';
let modifiedResponseText = '';
const openWrapper = (target, thisArg, args) => {
// Get original request properties
// eslint-disable-next-line prefer-spread
xhrData = getXhrData.apply(null, args);
if (typeof propsToMatch === 'undefined') {
// Log if no propsToMatch given
logMessage(source, `xhr( ${objectToString(xhrData)} )`, true);
hit(source);
} else if (matchRequestProps(source, propsToMatch, xhrData)) {
thisArg.shouldBePrevented = true;
// Add xhrData to thisArg to keep original values in case of multiple requests
// https://github.com/AdguardTeam/Scriptlets/issues/347
thisArg.xhrData = xhrData;
}
// Trap setRequestHeader of target xhr object to mimic request headers later;
// needed for getResponseHeader() and getAllResponseHeaders() methods
if (thisArg.shouldBePrevented) {
thisArg.collectedHeaders = [];
const setRequestHeaderWrapper = (target, thisArg, args) => {
// Collect headers
thisArg.collectedHeaders.push(args);
return Reflect.apply(target, thisArg, args);
};
const setRequestHeaderHandler = {
apply: setRequestHeaderWrapper,
};
// setRequestHeader() can only be called on xhr.open(),
// so we can safely proxy it here
thisArg.setRequestHeader = new Proxy(thisArg.setRequestHeader, setRequestHeaderHandler);
}
return Reflect.apply(target, thisArg, args);
};
const sendWrapper = (target, thisArg, args) => {
if (!thisArg.shouldBePrevented) {
return Reflect.apply(target, thisArg, args);
}
if (thisArg.responseType === 'blob') {
modifiedResponse = new Blob();
}
if (thisArg.responseType === 'arraybuffer') {
modifiedResponse = new ArrayBuffer();
}
if (customResponseText) {
const randomText = generateRandomResponse(customResponseText);
if (randomText) {
modifiedResponse = randomText;
modifiedResponseText = randomText;
} else {
logMessage(source, `Invalid randomize parameter: '${customResponseText}'`);
}
}
/**
* Create separate XHR request with original request's input
* to be able to collect response data without triggering
* listeners on original XHR object
*/
const forgedRequest = new XMLHttpRequest();
/**
* Used to manually simulate the progression of the readyState property.
* By using Object.defineProperty, the function ensures
* that the readyState can be modified and configured appropriately,
* while allowing the property to be writable.
* @param {number} state - request status number.
*/
const transitionReadyState = (state) => {
if (state === 4) {
const {
responseURL,
responseXML,
} = forgedRequest;
// Mock response object
Object.defineProperties(thisArg, {
readyState: { value: 4, writable: false },
statusText: { value: 'OK', writable: false },
responseURL: { value: responseURL || thisArg.xhrData.url, writable: false },
responseXML: { value: responseXML, writable: false },
status: { value: 200, writable: false },
response: { value: modifiedResponse, writable: false },
responseText: { value: modifiedResponseText, writable: false },
});
hit(source);
} else {
Object.defineProperty(thisArg, 'readyState', {
value: state,
writable: true,
configurable: true,
});
}
const stateEvent = new Event('readystatechange');
thisArg.dispatchEvent(stateEvent);
};
// All events added to avoid problems with anti-adblockers
// https://github.com/AdguardTeam/Scriptlets/issues/414
forgedRequest.addEventListener('readystatechange', () => {
// simulate the lifecycle
transitionReadyState(1);
const loadStartEvent = new ProgressEvent('loadstart');
thisArg.dispatchEvent(loadStartEvent);
transitionReadyState(2);
transitionReadyState(3);
const progressEvent = new ProgressEvent('progress');
thisArg.dispatchEvent(progressEvent);
transitionReadyState(4);
});
setTimeout(() => {
const loadEvent = new ProgressEvent('load');
thisArg.dispatchEvent(loadEvent);
const loadEndEvent = new ProgressEvent('loadend');
thisArg.dispatchEvent(loadEndEvent);
}, 1);
nativeOpen.apply(forgedRequest, [thisArg.xhrData.method, thisArg.xhrData.url]);
// Mimic request headers before sending
// setRequestHeader can only be called on open request objects
thisArg.collectedHeaders.forEach((header) => {
const name = header[0];
const value = header[1];
forgedRequest.setRequestHeader(name, value);
});
return undefined;
};
/**
* Mock XMLHttpRequest.prototype.getHeaderHandler() to avoid adblocker detection.
*
* @param {Function} target XMLHttpRequest.prototype.getHeaderHandler().
* @param {XMLHttpRequest} thisArg The request.
* @param {string[]} args Header name is passed as first argument.
*
* @returns {string|null} Header value or null if header is not set.
*/
const getHeaderWrapper = (target, thisArg, args) => {
if (!thisArg.shouldBePrevented) {
return nativeGetResponseHeader.apply(thisArg, args);
}
if (!thisArg.collectedHeaders.length) {
return null;
}
// The search for the header name is case-insensitive
// https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/getResponseHeader
const searchHeaderName = args[0].toLowerCase();
const matchedHeader = thisArg.collectedHeaders.find((header) => {
const headerName = header[0].toLowerCase();
return headerName === searchHeaderName;
});
return matchedHeader
? matchedHeader[1]
: null;
};
/**
* Mock XMLHttpRequest.prototype.getAllResponseHeaders() to avoid adblocker detection.
*
* @param {Function} target XMLHttpRequest.prototype.getAllResponseHeaders().
* @param {XMLHttpRequest} thisArg The request.
*
* @returns {string} All headers as a string. For no headers an empty string is returned.
*/
const getAllHeadersWrapper = (target, thisArg) => {
if (!thisArg.shouldBePrevented) {
return nativeGetAllResponseHeaders.call(thisArg);
}
if (!thisArg.collectedHeaders.length) {
return '';
}
const allHeadersStr = thisArg.collectedHeaders
.map((header) => {
/**
* TODO: array destructuring may be used here
* after the typescript implementation and bundling refactoring
* as now there is an error: slicedToArray is not defined
*/
const headerName = header[0];
const headerValue = header[1];
// In modern browsers, the header names are returned in all lower case, as per the latest spec.
// https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/getAllResponseHeaders
return `${headerName.toLowerCase()}: ${headerValue}`;
})
.join('\r\n');
return allHeadersStr;
};
const openHandler = {
apply: openWrapper,
};
const sendHandler = {
apply: sendWrapper,
};
const getHeaderHandler = {
apply: getHeaderWrapper,
};
const getAllHeadersHandler = {
apply: getAllHeadersWrapper,
};
XMLHttpRequest.prototype.open = new Proxy(XMLHttpRequest.prototype.open, openHandler);
XMLHttpRequest.prototype.send = new Proxy(XMLHttpRequest.prototype.send, sendHandler);
XMLHttpRequest.prototype.getResponseHeader = new Proxy(
XMLHttpRequest.prototype.getResponseHeader,
getHeaderHandler,
);
XMLHttpRequest.prototype.getAllResponseHeaders = new Proxy(
XMLHttpRequest.prototype.getAllResponseHeaders,
getAllHeadersHandler,
);
}
export const preventXHRNames = [
'prevent-xhr',
// aliases are needed for matching the related scriptlet converted into our syntax
'no-xhr-if.js',
'ubo-no-xhr-if.js',
'ubo-no-xhr-if',
];
// eslint-disable-next-line prefer-destructuring
preventXHR.primaryName = preventXHRNames[0];
preventXHR.injections = [
hit,
objectToString,
generateRandomResponse,
matchRequestProps,
getXhrData,
logMessage,
toRegExp,
isValidStrPattern,
escapeRegExp,
isEmptyObject,
getNumberFromString,
nativeIsFinite,
nativeIsNaN,
parseMatchProps,
isValidParsedData,
getMatchPropsData,
getRequestProps,
getRandomIntInclusive,
getRandomStrByLength,
];