Repository navigation
Expand file tree
/
Copy pathtrusted-suppress-native-method.ts
More file actions
260 lines (240 loc) · 9.07 KB
/
Copy pathtrusted-suppress-native-method.ts
File metadata and controls
260 lines (240 loc) · 9.07 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
import {
hit,
logMessage,
getPropertyInChain,
getMethodOwner,
inferValue,
isValueMatched,
getAbortFunc,
matchStackTrace,
addStackTraceMessageLine,
getErrorMessage,
getThrownValueMessage,
shouldAbortInlineOrInjectedScript,
getNativeRegexpTest,
toRegExp,
nativeIsNaN,
randomId,
createOnErrorHandler,
isEmptyObject,
isArbitraryObject,
isStringMatched,
isArrayMatched,
isObjectMatched,
backupRegExpValues,
restoreRegExpValues,
splitByPipeRespectingRegex,
getFunctionProxyProperty,
} from '../helpers';
import { type Source } from './scriptlets';
/* eslint-disable max-len */
/**
* @trustedScriptlet trusted-suppress-native-method
*
* @description
* Prevents a call of a given native method, matching the call by incoming arguments.
*
* ### Syntax
*
* ```text
* example.org#%#//scriptlet('trusted-suppress-native-method', methodPath, signatureStr[, how[, stack]])
* ```
*
* <!-- markdownlint-disable line-length -->
*
* - `methodPath` – required, string path to a native method (joined with `.` if needed). The property must be attached to `window`.
* - `signatureStr` – required, string of `|`-separated argument matchers.
* Supported value types with corresponding matchers:
*
* - string – exact string, part of the string or regexp pattern. Empty string `""` to match an empty string. Regexp patterns inside object matchers are not supported.
* - number, boolean, null, undefined – exact value,
*
* - object – partial of the object with the values as mentioned above, i.e by another object, that includes property names and values to be matched,
* - array – partial of the array with the values to be included in the incoming array, without considering the order of values.
*
* To ignore specific argument, explicitly use whitespace as a matcher, e.g `' | |{"prop":"val"}'` to skip matching first and second arguments.
*
* <!-- markdownlint-enable line-length -->
*
* - `how` – optional, string, one of the following:
* - `abort` – default, aborts the call by throwing an error,
* - `prevent` – replaces the method call with the call of an empty function.
* - `stack` — optional, string or regular expression that must match the current function call stack trace.
*
* ### Examples
* <!-- markdownlint-disable-next-line line-length -->
* 1. Prevent `localStorage.setItem('test-key', 'test-value')` call matching first argument by regexp pattern and the second one by substring:
*
* ```adblock
* example.org#%#//scriptlet('trusted-suppress-native-method', 'localStorage.setItem', '/key/|"value"', 'prevent')
* ```
*
* 1. Abort `obj.hasOwnProperty('test')` call matching the first argument:
*
* ```adblock
* example.org#%#//scriptlet('trusted-suppress-native-method', 'Object.prototype.hasOwnProperty', '"test"')
* ```
*
* 1. Prevent `Node.prototype.appendChild` call on element with the id `test-id` by object matcher:
*
* ```adblock
* example.org#%#//scriptlet('trusted-suppress-native-method', 'Node.prototype.appendChild', '{"id":"str"}', 'prevent')
* ```
*
* 1. Abort all `document.querySelectorAll` calls with `div` as the first argument:
*
* ```adblock
* example.org#%#//scriptlet('trusted-suppress-native-method', 'Document.prototype.querySelectorAll', '"div"')
* ```
*
* 1. Abort `Array.prototype.concat([1, 'str', true, null])` calls by matching array argument contents:
*
* ```adblock
* example.org#%#//scriptlet('trusted-suppress-native-method', 'Array.prototype.concat', '[1, "str", true]')
* ```
*
* 1. Use `stack` argument to match by the call, while also matching the second argument:
*
* <!-- markdownlint-disable line-length -->
*
* ```adblock
* example.org#%#//scriptlet('trusted-suppress-native-method', 'sessionStorage.setItem', ' |"item-value"', 'abort', 'someFuncName')
* ```
*
* <!-- markdownlint-enable line-length -->
*
* @added v1.10.25.
*/
/* eslint-enable max-len */
export function trustedSuppressNativeMethod(
source: Source,
methodPath: string,
signatureStr: string,
how = 'abort',
stack = '',
) {
if (!methodPath || !signatureStr) {
return;
}
const IGNORE_ARG_SYMBOL = ' ';
const suppress = how === 'abort'
? getAbortFunc()
: () => {};
let signatureMatcher: unknown[];
try {
signatureMatcher = splitByPipeRespectingRegex(signatureStr).map((value) => {
return value === IGNORE_ARG_SYMBOL ? value : inferValue(value);
});
} catch (e) {
logMessage(source, `Could not parse the signature matcher: ${getErrorMessage(e)}`);
return;
}
/**
* getPropertyInChain's return type `ChainBase` only makes sense
* while traversing the chain, but not to outside receivers.
*
* This is done as the least invasive way to make the typings work,
* compared to @ts-ignore or scattered assertions.
*/
const getPathParts = getPropertyInChain as unknown as (base: Window, chain: string) => {
base: Record<string, unknown>;
prop: string;
chain?: string;
};
const { base, chain, prop } = getPathParts(window, methodPath);
// Undefined `chain` indicates successful reaching the end prop.
if (typeof chain !== 'undefined') {
logMessage(source, `Could not reach the end of the prop chain: ${methodPath}`);
return;
}
// Method of a storage is replaced in `Storage.prototype`, so only its calls on `base` are processed
const methodOwner = getMethodOwner(base, prop);
const nativeMethod = methodOwner[prop];
if (!nativeMethod || typeof nativeMethod !== 'function') {
logMessage(source, `Could not retrieve the method: ${methodPath}`);
return;
}
/**
* Matches the incoming arguments with the signature matcher.
*
* @param nativeArguments original arguments of the native method call
* @param matchArguments matcher to match against the native argument
* @returns true, if each of the signature matchers match their corresponding argument.
*/
function matchMethodCall(
nativeArguments: unknown[],
matchArguments: unknown[],
): boolean {
return matchArguments.every((matcher, i) => {
if (matcher === IGNORE_ARG_SYMBOL) {
return true;
}
const argument = nativeArguments[i];
return isValueMatched(argument, matcher);
});
}
// This flag allows to prevent infinite loops when trapping props that are used by scriptlet's own code.
let isMatchingSuspended = false;
function apply(target: Function, thisArg: any, argumentsList: unknown[]) {
if (isMatchingSuspended || (methodOwner !== base && thisArg !== base)) {
return Reflect.apply(target, thisArg, argumentsList);
}
let isMatching = false;
isMatchingSuspended = true;
try {
// Error message line is added to the stack trace created here, in the wrapper called by the page,
// as Firefox and Safari do not have it, so `matchStackTrace()` keeps the frame of the caller
isMatching = (!stack || matchStackTrace(stack, addStackTraceMessageLine(String(new Error().stack || ''))))
&& matchMethodCall(argumentsList, signatureMatcher);
} catch (e) {
// e.g. a getter of an argument which throws, so the call is not suppressed.
// Error is not converted to get its message, as it may call the page again, e.g. its `toJSON()`,
// and the error may be a primitive thrown by the page, e.g. by `Error` replaced by it
logMessage(source, `Could not match the call: ${getThrownValueMessage(e)}`);
} finally {
// Matching is resumed on every return path, as the next calls would not be processed otherwise
isMatchingSuspended = false;
}
if (isMatching) {
hit(source);
return suppress();
}
return Reflect.apply(target, thisArg, argumentsList);
}
methodOwner[prop] = new Proxy(nativeMethod, { apply, get: getFunctionProxyProperty });
}
export const trustedSuppressNativeMethodNames = [
'trusted-suppress-native-method',
];
// eslint-disable-next-line prefer-destructuring
trustedSuppressNativeMethod.primaryName = trustedSuppressNativeMethodNames[0];
trustedSuppressNativeMethod.injections = [
hit,
logMessage,
getPropertyInChain,
getMethodOwner,
inferValue,
isValueMatched,
getAbortFunc,
matchStackTrace,
addStackTraceMessageLine,
getErrorMessage,
getThrownValueMessage,
splitByPipeRespectingRegex,
getFunctionProxyProperty,
// following helpers should be imported and injected
// because they are used by helpers above
shouldAbortInlineOrInjectedScript,
getNativeRegexpTest,
toRegExp,
nativeIsNaN,
randomId,
createOnErrorHandler,
isEmptyObject,
isArbitraryObject,
isStringMatched,
isArrayMatched,
isObjectMatched,
backupRegExpValues,
restoreRegExpValues,
];