-
Notifications
You must be signed in to change notification settings - Fork 30
/
Copy pathprevent-fetch.js
276 lines (262 loc) · 9.16 KB
/
prevent-fetch.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
import {
hit,
getFetchData,
objectToString,
matchRequestProps,
logMessage,
noopPromiseResolve,
modifyResponse,
toRegExp,
isValidStrPattern,
escapeRegExp,
isEmptyObject,
getRequestData,
getRequestProps,
parseMatchProps,
isValidParsedData,
getMatchPropsData,
generateRandomResponse,
nativeIsFinite,
nativeIsNaN,
getNumberFromString,
getRandomIntInclusive,
getRandomStrByLength,
} from '../helpers';
/* eslint-disable max-len */
/**
* @scriptlet prevent-fetch
*
* @description
* Prevents `fetch` calls if **all** given parameters match.
*
* Related UBO scriptlet:
* https://github.com/gorhill/uBlock/wiki/Resources-Library#no-fetch-ifjs-
*
* ### Syntax
*
* ```text
* example.org#%#//scriptlet('prevent-fetch'[, propsToMatch[, responseBody[, responseType]]])
* ```
*
* - `propsToMatch` — optional, string of space-separated properties to match; possible props:
* - string or regular expression for matching the URL passed to fetch call;
* empty string, wildcard `*` or invalid regular expression will match all fetch calls
* - colon-separated pairs `name:value` where
* <!-- markdownlint-disable-next-line line-length -->
* - `name` is [`init` option name](https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/fetch#parameters)
* - `value` is string or regular expression for matching the value of the option passed to fetch call;
* invalid regular expression will cause any value matching
* - `responseBody` — optional, string for defining response body value,
* defaults to `emptyObj`. Possible values:
* - `emptyObj` — empty object
* - `emptyArr` — empty array
* - `emptyStr` — empty string
* - `true` — random alphanumeric string of 10 symbols
* - colon-separated pair `name:value` string value to customize `responseBody` where
* - `name` — only `length` supported for now
* - `value` — range on numbers, for example `100-300`, limited to 500000 characters
* - `responseType` — optional, string for defining response type,
* original response type is used if not specified. Possible values:
* - `basic`
* - `cors`
* - `opaque`
*
* > Usage with no arguments will log fetch calls to browser console;
* > it may be useful for debugging but it is not allowed for prod versions of filter lists.
*
* ### Examples
*
* 1. Log all fetch calls
*
* ```adblock
* example.org#%#//scriptlet('prevent-fetch')
* ```
*
* 1. Prevent all fetch calls
*
* ```adblock
* example.org#%#//scriptlet('prevent-fetch', '*')
* ! or
* example.org#%#//scriptlet('prevent-fetch', '')
* ```
*
* 1. Prevent fetch call for specific url
*
* ```adblock
* example.org#%#//scriptlet('prevent-fetch', '/url\\.part/')
* ```
*
* 1. Prevent fetch call for specific request method
*
* ```adblock
* example.org#%#//scriptlet('prevent-fetch', 'method:HEAD')
* ```
*
* 1. Prevent fetch call for specific url and request method
*
* ```adblock
* example.org#%#//scriptlet('prevent-fetch', '/specified_url_part/ method:/HEAD|GET/')
* ```
*
* 1. Prevent fetch call and specify response body value
*
* ```adblock
* ! Specify response body for fetch call to a specific url
* example.org#%#//scriptlet('prevent-fetch', '/specified_url_part/ method:/HEAD|GET/', 'emptyArr')
*
* ! Specify response body for all fetch calls
* example.org#%#//scriptlet('prevent-fetch', '', 'emptyArr')
*
* ! Specify response body to random alphanumeric string of 10 symbols for all fetch calls
* example.org#%#//scriptlet('prevent-fetch', '', 'true')
*
* ! Specify response body to random alphanumeric string with specific range for all fetch calls
* example.org#%#//scriptlet('prevent-fetch', '', 'length:100-300')
* ```
*
* 1. Prevent all fetch calls and specify response type value
*
* ```adblock
* example.org#%#//scriptlet('prevent-fetch', '*', '', 'opaque')
* ```
*
* @added v1.3.18.
*/
/* eslint-enable max-len */
// eslint-disable-next-line default-param-last
export function preventFetch(source, propsToMatch, responseBody = 'emptyObj', responseType) {
// do nothing if browser does not support fetch or Proxy (e.g. Internet Explorer)
// https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/fetch
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy
if (typeof fetch === 'undefined'
|| typeof Proxy === 'undefined'
|| typeof Response === 'undefined') {
return;
}
const nativeRequestClone = Request.prototype.clone;
let strResponseBody;
if (responseBody === '' || responseBody === 'emptyObj') {
strResponseBody = '{}';
} else if (responseBody === 'emptyArr') {
strResponseBody = '[]';
} else if (responseBody === 'emptyStr') {
strResponseBody = '';
} else if (responseBody === 'true' || responseBody.match(/^length:\d+-\d+$/)) {
strResponseBody = generateRandomResponse(responseBody);
} else {
logMessage(source, `Invalid responseBody parameter: '${responseBody}'`);
return;
}
const isResponseTypeSpecified = typeof responseType !== 'undefined';
const isResponseTypeSupported = (responseType) => {
const SUPPORTED_TYPES = [
'basic',
'cors',
'opaque',
];
return SUPPORTED_TYPES.includes(responseType);
};
// Skip disallowed response types,
// specified responseType has limited list of possible values
if (isResponseTypeSpecified
&& !isResponseTypeSupported(responseType)) {
logMessage(source, `Invalid responseType parameter: '${responseType}'`);
return;
}
/**
* Get the response type based on the given request object.
*
* @param {Request} request - The request object.
* @returns {string|undefined} The response type or undefined.
*/
const getResponseType = (request) => {
try {
const { mode } = request;
if (mode === undefined || mode === 'cors' || mode === 'no-cors') {
const fetchURL = new URL(request.url);
if (fetchURL.origin === document.location.origin) {
return 'basic';
}
return mode === 'no-cors' ? 'opaque' : 'cors';
}
} catch (error) {
logMessage(source, `Could not determine response type: ${error}`);
}
return undefined;
};
const handlerWrapper = async (target, thisArg, args) => {
let shouldPrevent = false;
const fetchData = getFetchData(args, nativeRequestClone);
if (typeof propsToMatch === 'undefined') {
logMessage(source, `fetch( ${objectToString(fetchData)} )`, true);
hit(source);
return Reflect.apply(target, thisArg, args);
}
shouldPrevent = matchRequestProps(source, propsToMatch, fetchData);
if (shouldPrevent) {
hit(source);
let finalResponseType;
try {
finalResponseType = responseType || getResponseType(fetchData);
const origResponse = await Reflect.apply(target, thisArg, args);
// In the case of apps, the blocked request has status 500
// and no error is thrown, so it's necessary to check response.ok
// https://github.com/AdguardTeam/Scriptlets/issues/334
if (!origResponse.ok) {
return noopPromiseResolve(strResponseBody, fetchData.url, finalResponseType);
}
return modifyResponse(
origResponse,
{
body: strResponseBody,
type: finalResponseType,
},
);
} catch (ex) {
// https://github.com/AdguardTeam/Scriptlets/issues/334
return noopPromiseResolve(strResponseBody, fetchData.url, finalResponseType);
}
}
return Reflect.apply(target, thisArg, args);
};
const fetchHandler = {
apply: handlerWrapper,
};
fetch = new Proxy(fetch, fetchHandler); // eslint-disable-line no-global-assign
}
export const preventFetchNames = [
'prevent-fetch',
// aliases are needed for matching the related scriptlet converted into our syntax
'prevent-fetch.js',
'ubo-prevent-fetch.js',
'ubo-prevent-fetch',
'no-fetch-if.js',
'ubo-no-fetch-if.js',
'ubo-no-fetch-if',
];
// eslint-disable-next-line prefer-destructuring
preventFetch.primaryName = preventFetchNames[0];
preventFetch.injections = [
hit,
getFetchData,
objectToString,
matchRequestProps,
logMessage,
noopPromiseResolve,
modifyResponse,
toRegExp,
isValidStrPattern,
escapeRegExp,
isEmptyObject,
getRequestData,
getRequestProps,
parseMatchProps,
isValidParsedData,
getMatchPropsData,
generateRandomResponse,
nativeIsFinite,
nativeIsNaN,
getNumberFromString,
getRandomIntInclusive,
getRandomStrByLength,
];