Repository navigation
Expand file tree
/
Copy pathtrusted-json-set-xhr-response.ts
More file actions
400 lines (371 loc) · 13.3 KB
/
Copy pathtrusted-json-set-xhr-response.ts
File metadata and controls
400 lines (371 loc) · 13.3 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
import {
logMessage,
getPrunePath,
objectToString,
matchRequestProps,
jsonPath,
getXhrData,
interceptXhrResponses,
getFunctionProxyProperty,
jsonSetter,
matchStackTrace,
addStackTraceMessageLine,
getMatchPropsData,
getRequestProps,
isValidParsedData,
parseMatchProps,
isValidStrPattern,
isEmptyObject,
getWildcardPropertyInChain,
shouldAbortInlineOrInjectedScript,
getNativeRegexpTest,
backupRegExpValues,
restoreRegExpValues,
isKeyInObject,
noopArray,
noopObject,
noopCallbackFunc,
noopFunc,
trueFunc,
falseFunc,
throwFunc,
noopPromiseReject,
noopPromiseResolve,
nativeIsNaN,
extractRegexAndReplacement,
getJsonSetValue,
jsonLineEdit,
hit,
isPruningNeeded,
parseJsonSetArgumentValue,
parseKeywordValue,
resolveJsonSetTimeKeywords,
toRegExp,
resolveJsonSyntaxMode,
buildJsonPathExpression,
getThrownValueMessage,
logJsonContent,
} 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`,
* including `$now$`, `$currentDate$`, and `$currentISODate$` time keywords
* which may be used in any part of the value, e.g. `json:{"count":1,"firstTime":$now$}`.
* 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,
};
// Value which is used for all the nodes matched in the intercepted payload.
// Time keywords in it are resolved before every payload is mutated
// https://github.com/AdguardTeam/Scriptlets/issues/573
let resolvedArgumentValue = parsedArgumentValue;
const getValueToSet = (currentValue: any): any => {
if (!resolvedArgumentValue) {
return currentValue;
}
return getJsonSetValue(currentValue, resolvedArgumentValue);
};
const applyJsonMutation = (jsonValue: Record<string, any>) => {
if (syntaxModeDetails.mode === 'jsonpath') {
return jsonPath(source, jsonValue, jsonPathExpression, nativeObjects, () => hit(source), '');
}
resolvedArgumentValue = resolveJsonSetTimeKeywords(
source,
argumentValue,
nativeObjects.nativeParse,
parsedArgumentValue,
);
return jsonSetter(
source,
jsonValue,
setPathObj?.path || '',
setPathObj?.value,
getValueToSet,
requiredPaths,
'',
nativeObjects,
);
};
/**
* Returns the content of the response for the request of the page, modified,
* converted to its response type.
*
* @param content text of the forged response
* @param xhr object of the page
* @param stackTrace stack trace of `send()` for logs
* @returns content of the response
*/
const modifyResponse = (content: any, xhr: XMLHttpRequest, stackTrace: string) => {
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 } = xhr;
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 {
// Content which cannot be serialized to be logged, e.g. too deeply nested, is logged only
// as an object, so the response is still modified
if (shouldLogContent) {
logJsonContent(source, jsonContent, nativeObjects.nativeStringify, stackTrace, 'Original content');
}
modifiedContent = applyJsonMutation(jsonContent);
if (shouldLogContent) {
logJsonContent(
source,
modifiedContent,
nativeObjects.nativeStringify,
stackTrace,
'Modified content',
);
}
try {
const { responseType } = xhr;
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);
}
return modifiedContent;
};
interceptXhrResponses(
source,
stack,
shouldLogContent,
(xhrData) => matchRequestProps(source, propsToMatch, xhrData),
modifyResponse,
);
}
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,
interceptXhrResponses,
getFunctionProxyProperty,
jsonPath,
jsonSetter,
matchStackTrace,
addStackTraceMessageLine,
resolveJsonSyntaxMode,
buildJsonPathExpression,
getMatchPropsData,
getRequestProps,
isValidParsedData,
parseMatchProps,
isValidStrPattern,
isEmptyObject,
getWildcardPropertyInChain,
shouldAbortInlineOrInjectedScript,
getNativeRegexpTest,
backupRegExpValues,
restoreRegExpValues,
isKeyInObject,
noopArray,
noopObject,
noopCallbackFunc,
noopFunc,
trueFunc,
falseFunc,
throwFunc,
noopPromiseReject,
noopPromiseResolve,
nativeIsNaN,
extractRegexAndReplacement,
getJsonSetValue,
jsonLineEdit,
hit,
isPruningNeeded,
parseJsonSetArgumentValue,
parseKeywordValue,
resolveJsonSetTimeKeywords,
toRegExp,
getThrownValueMessage,
logJsonContent,
];