-
Notifications
You must be signed in to change notification settings - Fork 33
Expand file tree
/
Copy pathtrusted-json-set-xhr-response.ts
More file actions
495 lines (445 loc) · 17.1 KB
/
trusted-json-set-xhr-response.ts
File metadata and controls
495 lines (445 loc) · 17.1 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
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
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
import {
logMessage,
getPrunePath,
objectToString,
matchRequestProps,
jsonPath,
getXhrData,
type XMLHttpRequestSharedRequestData,
jsonSetter,
matchStackTrace,
getMatchPropsData,
getRequestProps,
isValidParsedData,
parseMatchProps,
isValidStrPattern,
escapeRegExp,
isEmptyObject,
getWildcardPropertyInChain,
shouldAbortInlineOrInjectedScript,
getNativeRegexpTest,
backupRegExpValues,
restoreRegExpValues,
isKeyInObject,
noopArray,
noopObject,
noopCallbackFunc,
noopFunc,
trueFunc,
falseFunc,
throwFunc,
noopPromiseReject,
noopPromiseResolve,
nativeIsNaN,
extractRegexAndReplacement,
getJsonSetValue,
jsonLineEdit,
hit,
isPruningNeeded,
parseJsonSetArgumentValue,
toRegExp,
resolveJsonSyntaxMode,
buildJsonPathExpression,
} from '../helpers';
import { type Source } from './scriptlets';
/* eslint-disable max-len */
/**
* @trustedScriptlet trusted-json-set-xhr-response
*
* @description
* Sets a property at the given path in the JSON response of an XMLHttpRequest call.
* If the path does not exist, it is created together with any missing intermediate objects.
*
* ### Syntax
*
* <!-- markdownlint-disable line-length -->
*
* ```text
* example.org#%#//scriptlet('trusted-json-set-xhr-response', propsPath, argumentValue[, requiredInitialProps[, propsToMatch[, stack[, mode[, verbose]]]]])
* ```
*
* <!-- markdownlint-enable line-length -->
*
* - `propsPath` — required, dot-separated path to the property to set.
* Supports wildcards `*` and `[]`, and value filtering with `.[=].value`.
* In `jsonpath` mode only single JSONPath prune expression is supported.
* - `argumentValue` — required, value to write at the target path.
* Supports the same constants, `json:{...}`, and `replace:/regex/replacement/` syntax as `trusted-json-set`.
* In `jsonpath` mode this argument may be omitted when `propsPath` already includes
* an inline mutation suffix such as `=` or `+=`.
* - `requiredInitialProps` — optional, space-separated list of property paths
* which must all be present for the modification to occur.
* - `propsToMatch` — optional, string of space-separated properties to match for extra condition.
* - `stack` — optional, string or regular expression that must match the current function call stack trace.
* - `mode` — optional, syntax mode selector.
* Supported values:
* - `legacy` — force the existing legacy path syntax
* - `jsonpath` — force JSONPath syntax
* If omitted, the scriptlet detects JSONPath automatically for clearly JSONPath-shaped expressions.
* - `verbose` — optional, if set to `true`, the scriptlet will log the original and modified JSON content.
*
* > Scriptlet does nothing if response body cannot be converted to JSON.
* > If the response is line-delimited JSON, each JSON line is processed independently.
*
* ### Example
*
* <!-- markdownlint-disable line-length -->
*
* 1. Sets `foo` property to `{"a":{"test":1},"b":{"c":1}}` in the JSON response of any XMLHttpRequest call:
*
* ```adblock
* example.org#%#//scriptlet('trusted-json-set-xhr-response', 'foo', 'json:{"a":{"test":1},"b":{"c":1}}')
* ```
*
* or `JSONPath` syntax:
*
* ```adblock
* example.org#%#//scriptlet('trusted-json-set-xhr-response', '$.foo', 'json:{"a":{"test":1},"b":{"c":1}}')
* ```
*
* 1. Creates `config.flags.blocked` path in matching XMLHttpRequest responses
*
* ```adblock
* example.org#%#//scriptlet('trusted-json-set-xhr-response', 'config.flags.blocked', 'true', '', 'api/config')
* ```
*
* or `JSONPath` syntax:
*
* ```adblock
* example.org#%#//scriptlet('trusted-json-set-xhr-response', '$.+={"config":{"flags":{"blocked":true}}}', '', '', 'api/config')
* ```
*
* 1. Replaces a value in the JSON response using a regular expression
*
* ```adblock
* example.org#%#//scriptlet('trusted-json-set-xhr-response', 'foo', 'replace:/advertisement/article/')
* ```
*
* or `JSONPath` syntax:
*
* ```adblock
* example.org#%#//scriptlet('trusted-json-set-xhr-response', '$.foo=replace({"regex":"advertisement","replacement":"article"})')
* ```
*
* <!-- markdownlint-enable line-length -->
*
* @added v2.3.0.
*/
/* eslint-enable max-len */
export function trustedJsonSetXhrResponse(
source: Source,
propsPath: string,
argumentValue: any,
requiredInitialProps = '',
propsToMatch = '',
stack = '',
mode = '',
verbose = '',
) {
const syntaxModeDetails = resolveJsonSyntaxMode(propsPath, mode);
const jsonPathExpression = syntaxModeDetails.mode === 'jsonpath'
? buildJsonPathExpression(propsPath, argumentValue)
: '';
if (!propsPath) {
return;
}
if (typeof Proxy === 'undefined') {
return;
}
if (syntaxModeDetails.mode === 'legacy' && argumentValue === undefined) {
return;
}
if (syntaxModeDetails.mode === 'jsonpath' && jsonPathExpression === '') {
logMessage(source, 'JSONPath mode requires argumentValue unless propsPath already contains an inline mutation');
return;
}
const shouldLogContent = verbose === 'true';
const parsedArgumentValue = syntaxModeDetails.mode === 'legacy'
? parseJsonSetArgumentValue(source, argumentValue, window.JSON.parse)
: null;
if (syntaxModeDetails.mode === 'legacy' && !parsedArgumentValue) {
return;
}
const parsedSetPaths = syntaxModeDetails.mode === 'legacy' ? getPrunePath(propsPath) : [];
const setPathObj = parsedSetPaths[0];
const requiredPaths = syntaxModeDetails.mode === 'legacy' ? getPrunePath(requiredInitialProps) : [];
const nativeObjects = {
nativeParse: window.JSON.parse,
nativeStringify: window.JSON.stringify,
};
const nativeOpen = window.XMLHttpRequest.prototype.open;
const nativeSend = window.XMLHttpRequest.prototype.send;
const matchedXhrRequests = new Map<XMLHttpRequest, XMLHttpRequestSharedRequestData<any>>();
const xhrRequestHeaders = new Map<XMLHttpRequest, any[]>();
const getValueToSet = (currentValue: any): any => {
if (!parsedArgumentValue) {
return currentValue;
}
return getJsonSetValue(currentValue, parsedArgumentValue);
};
const applyJsonMutation = (jsonValue: Record<string, any>) => {
if (syntaxModeDetails.mode === 'jsonpath') {
return jsonPath(source, jsonValue, jsonPathExpression, nativeObjects, () => hit(source), '');
}
return jsonSetter(
source,
jsonValue,
setPathObj?.path || '',
setPathObj?.value,
getValueToSet,
requiredPaths,
'',
nativeObjects,
);
};
const setRequestHeaderWrapper = (
setRequestHeader: typeof XMLHttpRequest.prototype.setRequestHeader,
thisArgument: XMLHttpRequest,
argsList: any,
): void => {
const headers = xhrRequestHeaders.get(thisArgument);
if (headers) {
headers.push(argsList);
}
return Reflect.apply(setRequestHeader, thisArgument, argsList);
};
const setRequestHeaderHandler = {
apply: setRequestHeaderWrapper,
};
// TODO: Consider to move all wrappers to helper and share it with json-prune-xhr-response scriptlet
const openWrapper = (
target: typeof XMLHttpRequest.prototype.open,
thisArg: XMLHttpRequest,
args: [
method: string,
url: string,
async?: boolean,
user?: string,
password?: string,
],
): void => {
// eslint-disable-next-line prefer-spread
const xhrData: XMLHttpRequestSharedRequestData<any> = getXhrData.apply(null, args);
if (matchRequestProps(source, propsToMatch, xhrData)) {
matchedXhrRequests.set(thisArg, xhrData);
}
if (matchedXhrRequests.has(thisArg) && !xhrRequestHeaders.has(thisArg)) {
xhrRequestHeaders.set(thisArg, []);
thisArg.setRequestHeader = new Proxy(thisArg.setRequestHeader, setRequestHeaderHandler);
}
return Reflect.apply(target, thisArg, args);
};
const sendWrapper = (
target: typeof XMLHttpRequest.prototype.send,
thisArg: XMLHttpRequest,
args: any,
): void => {
if (!matchedXhrRequests.has(thisArg)) {
return Reflect.apply(target, thisArg, args);
}
const stackTrace = new Error().stack || '';
if (stack && !matchStackTrace(stack, stackTrace)) {
xhrRequestHeaders.delete(thisArg);
matchedXhrRequests.delete(thisArg);
return Reflect.apply(target, thisArg, args);
}
const xhrData = matchedXhrRequests.get(thisArg);
if (!xhrData) {
xhrRequestHeaders.delete(thisArg);
matchedXhrRequests.delete(thisArg);
return Reflect.apply(target, thisArg, args);
}
const forgedRequest = new XMLHttpRequest();
forgedRequest.withCredentials = thisArg.withCredentials;
forgedRequest.addEventListener('readystatechange', () => {
if (forgedRequest.readyState !== 4) {
return;
}
const {
readyState,
response,
responseText,
responseURL,
responseXML,
status,
statusText,
} = forgedRequest;
const content = responseText || response;
if (typeof content !== 'string' && typeof content !== 'object') {
return;
}
let modifiedContent = content;
if (typeof content === 'string') {
let jsonContent;
let parseFailed = false;
try {
jsonContent = nativeObjects.nativeParse(content);
} catch {
parseFailed = true;
}
if (parseFailed) {
try {
const lineEditResult = jsonLineEdit(
(parsedLine) => applyJsonMutation(parsedLine),
nativeObjects,
content,
);
if (lineEditResult.hasJsonLines) {
modifiedContent = lineEditResult.text;
if (shouldLogContent) {
// eslint-disable-next-line max-len
logMessage(source, `Original content:\n${window.location.hostname}\n${content}\nStack trace:\n${stackTrace}`, true);
// eslint-disable-next-line max-len
logMessage(source, `Modified content:\n${window.location.hostname}\n${modifiedContent}\nStack trace:\n${stackTrace}`, true);
}
try {
const { responseType } = thisArg;
switch (responseType) {
case 'arraybuffer':
modifiedContent = new TextEncoder().encode(modifiedContent).buffer;
break;
case 'blob':
modifiedContent = new Blob([modifiedContent]);
break;
default:
break;
}
} catch {
modifiedContent = content;
}
} else {
const message = `Response body cannot be converted to json: '${content}'`;
logMessage(source, message);
modifiedContent = content;
}
} catch {
const message = `Response body cannot be converted to json: '${content}'`;
logMessage(source, message);
modifiedContent = content;
}
} else {
if (shouldLogContent) {
// eslint-disable-next-line max-len
logMessage(source, `Original content:\n${window.location.hostname}\n${nativeObjects.nativeStringify(jsonContent, null, 2)}\nStack trace:\n${stackTrace}`, true);
logMessage(source, jsonContent, true, false);
}
modifiedContent = applyJsonMutation(jsonContent);
if (shouldLogContent) {
// eslint-disable-next-line max-len
logMessage(source, `Modified content:\n${window.location.hostname}\n${nativeObjects.nativeStringify(modifiedContent, null, 2)}\nStack trace:\n${stackTrace}`, true);
logMessage(source, modifiedContent, true, false);
}
try {
const { responseType } = thisArg;
switch (responseType) {
case '':
case 'text':
modifiedContent = nativeObjects.nativeStringify(modifiedContent);
break;
case 'arraybuffer':
modifiedContent = new TextEncoder()
.encode(nativeObjects.nativeStringify(modifiedContent))
.buffer;
break;
case 'blob':
modifiedContent = new Blob([nativeObjects.nativeStringify(modifiedContent)]);
break;
default:
break;
}
} catch {
modifiedContent = content;
}
}
} else if (content !== null) {
modifiedContent = applyJsonMutation(content);
}
Object.defineProperties(thisArg, {
readyState: { value: readyState, writable: false },
responseURL: { value: responseURL, writable: false },
responseXML: { value: responseXML, writable: false },
status: { value: status, writable: false },
statusText: { value: statusText, writable: false },
response: { value: modifiedContent, writable: false },
responseText: { value: modifiedContent, writable: false },
});
setTimeout(() => {
const stateEvent = new Event('readystatechange');
thisArg.dispatchEvent(stateEvent);
const loadEvent = new Event('load');
thisArg.dispatchEvent(loadEvent);
const loadEndEvent = new Event('loadend');
thisArg.dispatchEvent(loadEndEvent);
}, 1);
});
nativeOpen.apply(forgedRequest, [xhrData.method, xhrData.url, Boolean(xhrData.async)]);
const collectedHeaders = xhrRequestHeaders.get(thisArg) || [];
collectedHeaders.forEach((header) => {
forgedRequest.setRequestHeader(header[0], header[1]);
});
xhrRequestHeaders.delete(thisArg);
matchedXhrRequests.delete(thisArg);
try {
Reflect.apply(nativeSend, forgedRequest, args);
} catch {
return Reflect.apply(target, thisArg, args);
}
return undefined;
};
const openHandler = {
apply: openWrapper,
};
const sendHandler = {
apply: sendWrapper,
};
XMLHttpRequest.prototype.open = new Proxy(XMLHttpRequest.prototype.open, openHandler);
XMLHttpRequest.prototype.send = new Proxy(XMLHttpRequest.prototype.send, sendHandler);
}
export const trustedJsonSetXhrResponseNames = [
'trusted-json-set-xhr-response',
// trusted scriptlets support no aliases
];
// eslint-disable-next-line prefer-destructuring
trustedJsonSetXhrResponse.primaryName = trustedJsonSetXhrResponseNames[0];
trustedJsonSetXhrResponse.injections = [
logMessage,
getPrunePath,
objectToString,
matchRequestProps,
getXhrData,
jsonPath,
jsonSetter,
matchStackTrace,
resolveJsonSyntaxMode,
buildJsonPathExpression,
getMatchPropsData,
getRequestProps,
isValidParsedData,
parseMatchProps,
isValidStrPattern,
escapeRegExp,
isEmptyObject,
getWildcardPropertyInChain,
shouldAbortInlineOrInjectedScript,
getNativeRegexpTest,
backupRegExpValues,
restoreRegExpValues,
isKeyInObject,
noopArray,
noopObject,
noopCallbackFunc,
noopFunc,
trueFunc,
falseFunc,
throwFunc,
noopPromiseReject,
noopPromiseResolve,
nativeIsNaN,
extractRegexAndReplacement,
getJsonSetValue,
jsonLineEdit,
hit,
isPruningNeeded,
parseJsonSetArgumentValue,
toRegExp,
];