@whotracksme/reporting 5.1.17
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.editorconfig +12 -0
- package/.eslintignore +3 -0
- package/.eslintrc +16 -0
- package/.github/workflows/release.yml +34 -0
- package/.github/workflows/tests.yml +20 -0
- package/.prettierrc +9 -0
- package/.tool-versions +1 -0
- package/CHANGELOG.md +795 -0
- package/LICENSE +373 -0
- package/README.md +1 -0
- package/communication/README.md +11 -0
- package/communication/example/index.js +43 -0
- package/communication/example/manifest.json +16 -0
- package/communication/karma.conf.cjs +19 -0
- package/communication/package.json +52 -0
- package/communication/rollup.common-config.cjs +17 -0
- package/communication/rollup.config.cjs +10 -0
- package/communication/src/encoding.js +54 -0
- package/communication/src/errors.js +84 -0
- package/communication/src/index.js +76 -0
- package/communication/src/logger.js +41 -0
- package/communication/src/padding.js +60 -0
- package/communication/src/proxied-http.js +231 -0
- package/communication/src/server-public-key-accessor.js +123 -0
- package/communication/src/timestamps.js +37 -0
- package/communication/src/trusted-clock.js +58 -0
- package/communication/src/utils.js +28 -0
- package/communication/src/zlib.js +17 -0
- package/communication/test/helpers/in-memory-database.js +43 -0
- package/communication/test/server-public-key-accessor.spec.js +135 -0
- package/communication/test/utils.spec.js +43 -0
- package/package.json +50 -0
- package/reporting/TODO.md +2 -0
- package/reporting/assets/request/bloom_filter.dat +0 -0
- package/reporting/assets/request/update.json +1 -0
- package/reporting/example/content.js +11 -0
- package/reporting/example/index.js +132 -0
- package/reporting/example/inspector/index.html +17 -0
- package/reporting/example/inspector/index.js +27 -0
- package/reporting/example/manifests/chromium.json +37 -0
- package/reporting/example/manifests/firefox.json +35 -0
- package/reporting/example/rules.json +62 -0
- package/reporting/example/setup.js +1 -0
- package/reporting/example/tests/test1.html +10 -0
- package/reporting/karma.conf.cjs +22 -0
- package/reporting/package.json +63 -0
- package/reporting/rollup.common-config.cjs +19 -0
- package/reporting/rollup.config.cjs +20 -0
- package/reporting/src/LRU.js +149 -0
- package/reporting/src/activity-estimator.js +298 -0
- package/reporting/src/alive-check.js +139 -0
- package/reporting/src/alive-message-generator.js +142 -0
- package/reporting/src/bloom-filters.js +345 -0
- package/reporting/src/country-provider.js +295 -0
- package/reporting/src/cyrb53.js +32 -0
- package/reporting/src/digest.js +33 -0
- package/reporting/src/doublefetch-page-handler.js +548 -0
- package/reporting/src/duplicate-detector.js +233 -0
- package/reporting/src/errors.js +84 -0
- package/reporting/src/event-listener-queue.js +121 -0
- package/reporting/src/fixed-size-cache.js +63 -0
- package/reporting/src/hash-detector.js +1526 -0
- package/reporting/src/html-parser.js +17 -0
- package/reporting/src/http.js +265 -0
- package/reporting/src/index.js +14 -0
- package/reporting/src/job-scheduler.js +912 -0
- package/reporting/src/logger.js +121 -0
- package/reporting/src/md5.js +334 -0
- package/reporting/src/message-sender.js +51 -0
- package/reporting/src/network.js +140 -0
- package/reporting/src/new-page-approver.js +119 -0
- package/reporting/src/page-aggregator.js +185 -0
- package/reporting/src/page-quorum-check-handler.js +200 -0
- package/reporting/src/page-structure.js +136 -0
- package/reporting/src/pagedb.js +671 -0
- package/reporting/src/pages.js +1798 -0
- package/reporting/src/patterns-updater.js +310 -0
- package/reporting/src/patterns.js +416 -0
- package/reporting/src/persisted-bitarray.js +265 -0
- package/reporting/src/persisted-hashes.js +189 -0
- package/reporting/src/quorum-checker.js +327 -0
- package/reporting/src/random.js +39 -0
- package/reporting/src/reporting.js +290 -0
- package/reporting/src/request/config.js +116 -0
- package/reporting/src/request/content-script.js +77 -0
- package/reporting/src/request/database.js +147 -0
- package/reporting/src/request/dnt.js +24 -0
- package/reporting/src/request/hash.js +101 -0
- package/reporting/src/request/index.js +874 -0
- package/reporting/src/request/page-telemetry.js +42 -0
- package/reporting/src/request/qs-whitelist2.js +247 -0
- package/reporting/src/request/resources/prob.js +601 -0
- package/reporting/src/request/steps/block-rules.js +40 -0
- package/reporting/src/request/steps/check-context.js +37 -0
- package/reporting/src/request/steps/cookie-context.js +209 -0
- package/reporting/src/request/steps/oauth-detector.js +101 -0
- package/reporting/src/request/steps/page-logger.js +177 -0
- package/reporting/src/request/steps/redirect-tagger.js +75 -0
- package/reporting/src/request/steps/subdomain-check.js +34 -0
- package/reporting/src/request/steps/token-checker/index.js +189 -0
- package/reporting/src/request/steps/token-checker/token-domain.js +129 -0
- package/reporting/src/request/steps/token-examiner.js +182 -0
- package/reporting/src/request/steps/token-telemetry/cached-entry-pipeline.js +210 -0
- package/reporting/src/request/steps/token-telemetry/index.js +234 -0
- package/reporting/src/request/steps/token-telemetry/key-pipeline.js +109 -0
- package/reporting/src/request/steps/token-telemetry/token-pipeline.js +105 -0
- package/reporting/src/request/time.js +73 -0
- package/reporting/src/request/utils/bloom-filter-packed.js +107 -0
- package/reporting/src/request/utils/chrome-storage-map.js +282 -0
- package/reporting/src/request/utils/subject.js +37 -0
- package/reporting/src/request/utils/temp-set.js +56 -0
- package/reporting/src/request/utils/tlds.js +55 -0
- package/reporting/src/request/utils.js +41 -0
- package/reporting/src/request-reporter.js +111 -0
- package/reporting/src/sanitizer.js +519 -0
- package/reporting/src/search-extractor.js +338 -0
- package/reporting/src/self-check.js +105 -0
- package/reporting/src/seq-executor.js +43 -0
- package/reporting/src/session-storage.js +399 -0
- package/reporting/src/url-analyzer.js +161 -0
- package/reporting/src/url-cleaner.js +60 -0
- package/reporting/src/utils/pacemaker.js +279 -0
- package/reporting/src/utils/url.js +114 -0
- package/reporting/src/utils.js +345 -0
- package/reporting/src/webrequest-pipeline/cname-uncloak.js +110 -0
- package/reporting/src/webrequest-pipeline/index.js +287 -0
- package/reporting/src/webrequest-pipeline/logger.js +14 -0
- package/reporting/src/webrequest-pipeline/page-store.js +282 -0
- package/reporting/src/webrequest-pipeline/page.js +140 -0
- package/reporting/src/webrequest-pipeline/pipeline.js +249 -0
- package/reporting/src/webrequest-pipeline/utils/webrequest.js +113 -0
- package/reporting/src/webrequest-pipeline/webrequest-context.js +153 -0
- package/reporting/test/README.md +2 -0
- package/reporting/test/activity-estimator.spec.js +356 -0
- package/reporting/test/alive-check.spec.js +156 -0
- package/reporting/test/alive-message-generator.spec.js +186 -0
- package/reporting/test/country-provider.spec.js +263 -0
- package/reporting/test/doublefetch-page-handler.spec.js +818 -0
- package/reporting/test/duplicate-detector.spec.js +689 -0
- package/reporting/test/helpers/dom-parsers.js +41 -0
- package/reporting/test/helpers/fake-session-storage.js +69 -0
- package/reporting/test/helpers/fast-check-utils.js +28 -0
- package/reporting/test/helpers/fetch-mock.js +57 -0
- package/reporting/test/helpers/in-memory-database.js +14 -0
- package/reporting/test/helpers/memory-map.js +72 -0
- package/reporting/test/helpers/pagedb-mocks.js +41 -0
- package/reporting/test/index.js +47 -0
- package/reporting/test/job-scheduler.spec.js +691 -0
- package/reporting/test/network.spec.js +72 -0
- package/reporting/test/page-aggregator.spec.js +104 -0
- package/reporting/test/page-quorum-check-handler.spec.js +86 -0
- package/reporting/test/pagedb.spec.js +250 -0
- package/reporting/test/pages.spec.js +693 -0
- package/reporting/test/patterns-updater.spec.js +446 -0
- package/reporting/test/patterns.spec.js +751 -0
- package/reporting/test/persisted-hashes.spec.js +169 -0
- package/reporting/test/reporting.spec.js +205 -0
- package/reporting/test/request/database.spec.js +59 -0
- package/reporting/test/request/hash.spec.js +108 -0
- package/reporting/test/request/index.spec.js +378 -0
- package/reporting/test/request/qs-whitelist2.spec.js +189 -0
- package/reporting/test/request/steps/check-context.spec.js +51 -0
- package/reporting/test/request/steps/oauth-detector.spec.js +339 -0
- package/reporting/test/request/test-pages.js +1246 -0
- package/reporting/test/request/utils/bloom-filter-packed.spec.js +37 -0
- package/reporting/test/request/utils/chrome-storage-map.spec.js +28 -0
- package/reporting/test/request/utils/tldts.spec.js +62 -0
- package/reporting/test/request/utils.spec.js +168 -0
- package/reporting/test/sanitizer.spec.js +1087 -0
- package/reporting/test/search-extractor.spec.js +590 -0
- package/reporting/test/seq-executor.spec.js +158 -0
- package/reporting/test/session-storage.spec.js +400 -0
- package/reporting/test/setup.js +24 -0
- package/reporting/test/url-analyzer.spec.js +451 -0
- package/reporting/test/url-cleaner.spec.js +102 -0
- package/reporting/test/utils/pacemaker.spec.js +222 -0
- package/reporting/test/utils/url.spec.js +660 -0
- package/reporting/test/utils.spec.js +299 -0
- package/reporting/test/webrequest-pipeline/pipeline.spec.js +251 -0
|
@@ -0,0 +1,416 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* WhoTracks.Me
|
|
3
|
+
* https://whotracks.me/
|
|
4
|
+
*
|
|
5
|
+
* Copyright 2017-present Ghostery GmbH. All rights reserved.
|
|
6
|
+
*
|
|
7
|
+
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
8
|
+
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
9
|
+
* file, You can obtain one at http://mozilla.org/MPL/2.0
|
|
10
|
+
*/
|
|
11
|
+
|
|
12
|
+
import logger from './logger';
|
|
13
|
+
import { sanitizeUrl } from './sanitizer';
|
|
14
|
+
import { removeQueryParams } from './url-cleaner';
|
|
15
|
+
import { UnsupportedTransformationError } from './errors';
|
|
16
|
+
import SelfChecks from './self-check';
|
|
17
|
+
import {
|
|
18
|
+
requireString,
|
|
19
|
+
requireInt,
|
|
20
|
+
requireBoolean,
|
|
21
|
+
requireObject,
|
|
22
|
+
requireArrayOfStrings,
|
|
23
|
+
} from './utils';
|
|
24
|
+
|
|
25
|
+
/**
|
|
26
|
+
* A list of predefined string transformations that can be specified
|
|
27
|
+
* in the DSL in the "transforms" definition.
|
|
28
|
+
*
|
|
29
|
+
* Notes:
|
|
30
|
+
* - All transformations are stateless and must be free of side-effects.
|
|
31
|
+
* - If a single steps return "null", the following steps will
|
|
32
|
+
* not be executed.
|
|
33
|
+
* - The first argument is the current value (the accumulator),
|
|
34
|
+
* but extra parameters can be defined in the DSL; these will be
|
|
35
|
+
* passed to the function as additional arguments.
|
|
36
|
+
*
|
|
37
|
+
* Preventing remote code execution
|
|
38
|
+
* --------------------------------
|
|
39
|
+
*
|
|
40
|
+
* The predefined functions need to be carefully checked. To illustrate
|
|
41
|
+
* the threat model, let us look at a constructed example first:
|
|
42
|
+
*
|
|
43
|
+
* badIdea: (x, param) => eval(param)
|
|
44
|
+
*
|
|
45
|
+
* Now, if an attacker compromises the servers and gets control to push
|
|
46
|
+
* malicious pattern updates, the function could be exploited:
|
|
47
|
+
*
|
|
48
|
+
* ["badIdea", "<some code that the client will execute>"].
|
|
49
|
+
*
|
|
50
|
+
* Be careful not to introduce a function that allows an attack
|
|
51
|
+
* like that. That is why it is so important to keep the function free
|
|
52
|
+
* of side-effects!
|
|
53
|
+
*
|
|
54
|
+
* ----------------------------------------------------------------------
|
|
55
|
+
*
|
|
56
|
+
* Additional warnings:
|
|
57
|
+
*
|
|
58
|
+
* 1) Do not allow DoS (be careful when looping; if possible avoid any loops):
|
|
59
|
+
*
|
|
60
|
+
* As long as the functions are free of side-effects, the worst possible
|
|
61
|
+
* attack would be denial-of-service (in other words, someone could push a
|
|
62
|
+
* rule that results in an infinite loop). So, also be careful when using
|
|
63
|
+
* explicit loops - there should be no need for it anyway.
|
|
64
|
+
* Best keep the transformations simple.
|
|
65
|
+
*
|
|
66
|
+
* 2) Do not trust the parameters:
|
|
67
|
+
*
|
|
68
|
+
* Note that an attacker will be able to control the arguments passed
|
|
69
|
+
* into the function:
|
|
70
|
+
* - extra parameters are under direct control (as they are taken
|
|
71
|
+
* from the rule definitions)
|
|
72
|
+
* - the first parameter (the accumulator) is more difficult to
|
|
73
|
+
* control but expect that it is prudent to assume that it can
|
|
74
|
+
* be controlled as well (e.g., if a user can be tricked to visit
|
|
75
|
+
* any website where the attacker can control text)
|
|
76
|
+
*
|
|
77
|
+
* As long as you avoid side-effects and loops, critical exploits
|
|
78
|
+
* are not possible, but again there are DoS type attacks.
|
|
79
|
+
*
|
|
80
|
+
* For instance, if you are writing a rule with an parameter that will
|
|
81
|
+
* be used as a regular expression, be careful. What will happen if the
|
|
82
|
+
* attacker pushes a rule with a long regular expression that may lead
|
|
83
|
+
* to exponential backtracking? Think about these kind of attacks and
|
|
84
|
+
* about mitigations (e.g. reject overly long parameters).
|
|
85
|
+
* Again, it is best to keep the functions simple to avoid any surprises.
|
|
86
|
+
*
|
|
87
|
+
* ----------------------------------------------------------------------
|
|
88
|
+
*
|
|
89
|
+
* Error handling:
|
|
90
|
+
*
|
|
91
|
+
* 1) Throwing an exception is supported. In that case, expect the whole
|
|
92
|
+
* rule to be skipped (no message will be sent). In other words, reserve
|
|
93
|
+
* it for unexpected cases.
|
|
94
|
+
* 2) Returning "null"/"undefined" has the semantic of stopping the
|
|
95
|
+
* execution without an error. It is still possible that a
|
|
96
|
+
* message will be sent, but with a missing value.
|
|
97
|
+
*/
|
|
98
|
+
const TRANSFORMS = new Map(
|
|
99
|
+
Object.entries({
|
|
100
|
+
/**
|
|
101
|
+
* Extracts a given query parameter and decodes it.
|
|
102
|
+
*
|
|
103
|
+
* Example ["queryParam", "foo"]:
|
|
104
|
+
* - "https://example.test/path?foo=bar+baz" -> "bar baz"
|
|
105
|
+
* - "/example.test/path?foo=bar+baz" -> "bar baz"
|
|
106
|
+
* - "/example.test/path" -> null
|
|
107
|
+
* - "This is a string but not an URL" -> null
|
|
108
|
+
*/
|
|
109
|
+
queryParam: (url, queryParam) => {
|
|
110
|
+
requireString(url);
|
|
111
|
+
requireString(queryParam);
|
|
112
|
+
try {
|
|
113
|
+
// we only need the query parameter, but to handle relative
|
|
114
|
+
// URLs we have to pass a base URL (any domain will work)
|
|
115
|
+
return new URL(url, 'http://x').searchParams.get(queryParam);
|
|
116
|
+
} catch (e) {
|
|
117
|
+
return null;
|
|
118
|
+
}
|
|
119
|
+
},
|
|
120
|
+
|
|
121
|
+
/**
|
|
122
|
+
* Given a URL and a list of query parameters, it returns an equivalent
|
|
123
|
+
* URL, but with those query parameters removed.
|
|
124
|
+
*
|
|
125
|
+
* Notes:
|
|
126
|
+
* - If the parameter occurs multiple times, all of them will be removed.
|
|
127
|
+
* - If the URL is invalid, null is returned.
|
|
128
|
+
*
|
|
129
|
+
* Example ["removeParams", ["foo"]]:
|
|
130
|
+
* - "https://example.test/path?foo=remove&bar=keep" -> "https://example.test/path?bar=keep"
|
|
131
|
+
* - "This is a string but not an URL" -> null
|
|
132
|
+
* - "/example.test/path" -> null (relative URLs are not supported)
|
|
133
|
+
*
|
|
134
|
+
* Example ["removeParams", ["foo", "bar"]]:
|
|
135
|
+
* - "https://example.test/path?foo=1&bar=2" -> "https://example.test/path"
|
|
136
|
+
*/
|
|
137
|
+
removeParams: (url, queryParams) => {
|
|
138
|
+
requireString(url);
|
|
139
|
+
requireArrayOfStrings(queryParams);
|
|
140
|
+
if (URL.canParse(url)) {
|
|
141
|
+
return removeQueryParams(url, queryParams);
|
|
142
|
+
} else {
|
|
143
|
+
return null;
|
|
144
|
+
}
|
|
145
|
+
},
|
|
146
|
+
|
|
147
|
+
/**
|
|
148
|
+
* Given text, it will verify that it is a well-formed URL;
|
|
149
|
+
* otherwise, it will end the processing by "nulling" it out.
|
|
150
|
+
*/
|
|
151
|
+
requireURL: (url) => {
|
|
152
|
+
requireString(url);
|
|
153
|
+
return URL.canParse(url) ? url : null;
|
|
154
|
+
},
|
|
155
|
+
|
|
156
|
+
/**
|
|
157
|
+
* Given a URL, it runs a set of extra checks to filter out
|
|
158
|
+
* parts that may be sensitive (i.e. keeping only the hostname),
|
|
159
|
+
* or even drop it completely.
|
|
160
|
+
*/
|
|
161
|
+
maskU: (url) => {
|
|
162
|
+
requireString(url);
|
|
163
|
+
try {
|
|
164
|
+
return sanitizeUrl(url).safeUrl;
|
|
165
|
+
} catch (e) {
|
|
166
|
+
return null;
|
|
167
|
+
}
|
|
168
|
+
},
|
|
169
|
+
|
|
170
|
+
/**
|
|
171
|
+
* Like "maskU", but more conservative.
|
|
172
|
+
*
|
|
173
|
+
* Note: in general, "maskU" should be the best trade-off. But if you have
|
|
174
|
+
* URLs that can be dropped without causing much harm, using "strictMaskU"
|
|
175
|
+
* can be useful. However, it will drop many harmless URLs; in other words,
|
|
176
|
+
* expect a high number of false-positives.
|
|
177
|
+
*/
|
|
178
|
+
strictMaskU: (url) => {
|
|
179
|
+
requireString(url);
|
|
180
|
+
try {
|
|
181
|
+
return sanitizeUrl(url, { strict: true }).safeUrl;
|
|
182
|
+
} catch (e) {
|
|
183
|
+
return null;
|
|
184
|
+
}
|
|
185
|
+
},
|
|
186
|
+
|
|
187
|
+
/**
|
|
188
|
+
* Like "maskU", but tries to preserve the URL path when truncating.
|
|
189
|
+
*/
|
|
190
|
+
relaxedMaskU: (url) => {
|
|
191
|
+
requireString(url);
|
|
192
|
+
try {
|
|
193
|
+
return sanitizeUrl(url, { strict: false, tryPreservePath: true })
|
|
194
|
+
.safeUrl;
|
|
195
|
+
} catch (e) {
|
|
196
|
+
return null;
|
|
197
|
+
}
|
|
198
|
+
},
|
|
199
|
+
|
|
200
|
+
split: (text, splitON, arrPos) => {
|
|
201
|
+
requireString(text);
|
|
202
|
+
requireString(splitON);
|
|
203
|
+
requireInt(arrPos);
|
|
204
|
+
|
|
205
|
+
const parts = text.split(splitON);
|
|
206
|
+
if (parts.length === 1) {
|
|
207
|
+
return null;
|
|
208
|
+
}
|
|
209
|
+
return parts[arrPos] ?? null;
|
|
210
|
+
},
|
|
211
|
+
|
|
212
|
+
trySplit: (text, splitON, arrPos) => {
|
|
213
|
+
requireString(text);
|
|
214
|
+
requireString(splitON);
|
|
215
|
+
requireInt(arrPos);
|
|
216
|
+
|
|
217
|
+
return text.split(splitON)[arrPos] || text;
|
|
218
|
+
},
|
|
219
|
+
|
|
220
|
+
decodeURIComponent: (text) => {
|
|
221
|
+
requireString(text);
|
|
222
|
+
try {
|
|
223
|
+
return decodeURIComponent(text);
|
|
224
|
+
} catch (e) {
|
|
225
|
+
return null;
|
|
226
|
+
}
|
|
227
|
+
},
|
|
228
|
+
|
|
229
|
+
tryDecodeURIComponent: (text) => {
|
|
230
|
+
requireString(text);
|
|
231
|
+
try {
|
|
232
|
+
return decodeURIComponent(text);
|
|
233
|
+
} catch (e) {
|
|
234
|
+
return text;
|
|
235
|
+
}
|
|
236
|
+
},
|
|
237
|
+
|
|
238
|
+
/**
|
|
239
|
+
* Takes a JSON string object, parses it and extract the data under the
|
|
240
|
+
* given path. By default, it will only extract safe types (strings,
|
|
241
|
+
* numbers, booleans), mostly to prevent accidentally extracting
|
|
242
|
+
* more than intended.
|
|
243
|
+
*/
|
|
244
|
+
json: (text, path, extractObjects = false) => {
|
|
245
|
+
requireString(text);
|
|
246
|
+
requireString(path);
|
|
247
|
+
requireBoolean(extractObjects);
|
|
248
|
+
try {
|
|
249
|
+
let obj = JSON.parse(text);
|
|
250
|
+
for (const field of path.split('.')) {
|
|
251
|
+
obj = obj[field];
|
|
252
|
+
}
|
|
253
|
+
if (typeof obj === 'string') {
|
|
254
|
+
return obj;
|
|
255
|
+
}
|
|
256
|
+
if (typeof obj === 'number' || typeof obj === 'boolean') {
|
|
257
|
+
return obj.toString();
|
|
258
|
+
}
|
|
259
|
+
if (extractObjects && obj) {
|
|
260
|
+
return JSON.stringify(obj);
|
|
261
|
+
}
|
|
262
|
+
// prevent uncontrolled text extraction
|
|
263
|
+
return '';
|
|
264
|
+
} catch (e) {
|
|
265
|
+
return '';
|
|
266
|
+
}
|
|
267
|
+
},
|
|
268
|
+
}),
|
|
269
|
+
);
|
|
270
|
+
|
|
271
|
+
export function lookupBuiltinTransform(name) {
|
|
272
|
+
const transform = TRANSFORMS.get(name);
|
|
273
|
+
if (transform) {
|
|
274
|
+
return transform;
|
|
275
|
+
}
|
|
276
|
+
throw new UnsupportedTransformationError(`Unknown transformation: "${name}"`);
|
|
277
|
+
}
|
|
278
|
+
|
|
279
|
+
/**
|
|
280
|
+
* Defines the version of the engine that processes the patterns DSL
|
|
281
|
+
* (Domain Specific Language).
|
|
282
|
+
*
|
|
283
|
+
* It is always safe to increase it: neither will it lead to overhead,
|
|
284
|
+
* nor will it split the population. Its sole purpose is to be used
|
|
285
|
+
* to disable clients that do not meet the minimum requirements of the
|
|
286
|
+
* current patterns.
|
|
287
|
+
*/
|
|
288
|
+
const PATTERN_DSL_VERSION = 1;
|
|
289
|
+
|
|
290
|
+
/**
|
|
291
|
+
* "Magic" empty rule set, which exists only if patterns were loaded, but
|
|
292
|
+
* our engine is too old and does not supported them. Therefore, they are
|
|
293
|
+
* disabled. Although not a typical error, reaching this state should be
|
|
294
|
+
* avoided; the client will be dead from the perspective of the server.
|
|
295
|
+
*
|
|
296
|
+
* There are two to exit this state:
|
|
297
|
+
* 1) The client updates to a newer version (this is the preferred one)
|
|
298
|
+
* 2) The server can decide to serve a backward-compatible set of rules to
|
|
299
|
+
* restore support for older clients. It will restore the traffic since
|
|
300
|
+
* old clients will still poll for patterns.
|
|
301
|
+
*
|
|
302
|
+
* Note that option two will not be sustainable over a longer period. It
|
|
303
|
+
* also comes with the disadvantage that old clients will form their own
|
|
304
|
+
* group; anonymity will suffer if their population becomes too small.
|
|
305
|
+
*/
|
|
306
|
+
const RULES_REJECTED__ENGINE_TOO_OLD = {};
|
|
307
|
+
|
|
308
|
+
/**
|
|
309
|
+
* "Magic" empty rule set, which should exist only temporarily when
|
|
310
|
+
* the background page or service worker is starting up. It should
|
|
311
|
+
* get quickly replaces by a normal set of rules.
|
|
312
|
+
*/
|
|
313
|
+
const RULES_NOT_LOADED_YET = {};
|
|
314
|
+
|
|
315
|
+
/**
|
|
316
|
+
* "Magic" empty rule set, which exists only if patterns failed to load,
|
|
317
|
+
* because they were not well-formed.
|
|
318
|
+
*/
|
|
319
|
+
const RULES_REJECTED__CORRUPTED = {};
|
|
320
|
+
|
|
321
|
+
/**
|
|
322
|
+
* Represents the currently active rules.
|
|
323
|
+
*
|
|
324
|
+
* It is updated by the PatternsUpdater, which polls
|
|
325
|
+
* the server for updates.
|
|
326
|
+
*/
|
|
327
|
+
export default class Patterns {
|
|
328
|
+
constructor() {
|
|
329
|
+
this._rules = RULES_NOT_LOADED_YET;
|
|
330
|
+
}
|
|
331
|
+
|
|
332
|
+
updatePatterns(rules) {
|
|
333
|
+
this._rules = this._sanitizeRules(rules);
|
|
334
|
+
logger.info('Loaded patterns:', this._rules);
|
|
335
|
+
}
|
|
336
|
+
|
|
337
|
+
/**
|
|
338
|
+
* Grants access to the active patterns. It is guaranteed that the
|
|
339
|
+
* returned object will not be modified.
|
|
340
|
+
*
|
|
341
|
+
* If you plan to perform multiple operations, it is recommended
|
|
342
|
+
* to call this function one and then operate on this snapshot.
|
|
343
|
+
* Even though it is unlikely, patterns can change at any point
|
|
344
|
+
* in time. As long as you operate on the snapshot, you do not have
|
|
345
|
+
* to worry about it.
|
|
346
|
+
*/
|
|
347
|
+
getRulesSnapshot() {
|
|
348
|
+
return this._rules;
|
|
349
|
+
}
|
|
350
|
+
|
|
351
|
+
/**
|
|
352
|
+
* Constructs a "doublefetchRequest" object, which defines the doublefetch
|
|
353
|
+
* requests for the given URL.
|
|
354
|
+
*
|
|
355
|
+
* Example outputs:
|
|
356
|
+
* 1. { url: 'https://example.test/foo', followRedirects: true, headers: { Cookie: 'bar' } }
|
|
357
|
+
* - allow redirects and overwrite the "Cookie" HTTP headers (as 'Cookie: bar')
|
|
358
|
+
* 2. { url: 'https://example.test/foo' }
|
|
359
|
+
* - do not allow redirects and do not overwrite headers
|
|
360
|
+
*/
|
|
361
|
+
createDoublefetchRequest(msgType, url) {
|
|
362
|
+
if (!this._rules[msgType]) {
|
|
363
|
+
return null;
|
|
364
|
+
}
|
|
365
|
+
const doublefetchRequest = { url };
|
|
366
|
+
if (this._rules[msgType].doublefetch) {
|
|
367
|
+
const { headers, followRedirects } = this._rules[msgType].doublefetch;
|
|
368
|
+
if (followRedirects) {
|
|
369
|
+
doublefetchRequest.redirect = 'follow';
|
|
370
|
+
}
|
|
371
|
+
if (headers) {
|
|
372
|
+
doublefetchRequest.headers = headers;
|
|
373
|
+
}
|
|
374
|
+
}
|
|
375
|
+
return doublefetchRequest;
|
|
376
|
+
}
|
|
377
|
+
|
|
378
|
+
_sanitizeRules(rules) {
|
|
379
|
+
try {
|
|
380
|
+
requireObject(rules);
|
|
381
|
+
const minVersion = requireInt(rules._meta?.minVersion || 0);
|
|
382
|
+
if (minVersion > PATTERN_DSL_VERSION) {
|
|
383
|
+
logger.warn(
|
|
384
|
+
'Ignoring patterns, since our engine does not meet the minimum version:',
|
|
385
|
+
minVersion,
|
|
386
|
+
'>',
|
|
387
|
+
PATTERN_DSL_VERSION,
|
|
388
|
+
);
|
|
389
|
+
return RULES_REJECTED__ENGINE_TOO_OLD;
|
|
390
|
+
}
|
|
391
|
+
return rules;
|
|
392
|
+
} catch (e) {
|
|
393
|
+
logger.error(
|
|
394
|
+
'Unable to apply rules because they could not be parsed:',
|
|
395
|
+
rules,
|
|
396
|
+
e,
|
|
397
|
+
);
|
|
398
|
+
return RULES_REJECTED__CORRUPTED;
|
|
399
|
+
}
|
|
400
|
+
}
|
|
401
|
+
|
|
402
|
+
async selfChecks(check = new SelfChecks()) {
|
|
403
|
+
if (this._rules === RULES_REJECTED__ENGINE_TOO_OLD) {
|
|
404
|
+
check.warn('patterns rejected, because our engine is too old');
|
|
405
|
+
} else if (this._rules === RULES_REJECTED__CORRUPTED) {
|
|
406
|
+
check.error('patterns rejected, because the rules were corrupted');
|
|
407
|
+
} else if (this._rules === RULES_NOT_LOADED_YET) {
|
|
408
|
+
check.warn(
|
|
409
|
+
'patterns still not initialized (this should happen only at startup)',
|
|
410
|
+
);
|
|
411
|
+
} else {
|
|
412
|
+
check.pass('patterns loaded');
|
|
413
|
+
}
|
|
414
|
+
return check;
|
|
415
|
+
}
|
|
416
|
+
}
|
|
@@ -0,0 +1,265 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* WhoTracks.Me
|
|
3
|
+
* https://whotracks.me/
|
|
4
|
+
*
|
|
5
|
+
* Copyright 2017-present Ghostery GmbH. All rights reserved.
|
|
6
|
+
*
|
|
7
|
+
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
8
|
+
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
9
|
+
* file, You can obtain one at http://mozilla.org/MPL/2.0
|
|
10
|
+
*/
|
|
11
|
+
|
|
12
|
+
import logger from './logger';
|
|
13
|
+
import SelfCheck from './self-check';
|
|
14
|
+
|
|
15
|
+
const SECOND = 1000;
|
|
16
|
+
|
|
17
|
+
/**
|
|
18
|
+
* A bitarray that is backed on disk.
|
|
19
|
+
*
|
|
20
|
+
* It only provides weak guarantees, so only use it for
|
|
21
|
+
* data that can tolerate lost writes.
|
|
22
|
+
*/
|
|
23
|
+
export default class PersistedBitarray {
|
|
24
|
+
constructor({ database, size, name, prefix = '', shardConfig }) {
|
|
25
|
+
if (!database) {
|
|
26
|
+
throw new Error('Database expected');
|
|
27
|
+
}
|
|
28
|
+
if (size < 0) {
|
|
29
|
+
throw new Error(`Size must be negative (got ${size})`);
|
|
30
|
+
}
|
|
31
|
+
this.db = database;
|
|
32
|
+
this.size = size;
|
|
33
|
+
this.numBytes = Math.ceil(size / 8);
|
|
34
|
+
|
|
35
|
+
if (!name) {
|
|
36
|
+
throw new Error('Expected a name');
|
|
37
|
+
}
|
|
38
|
+
this.name = name;
|
|
39
|
+
|
|
40
|
+
const { numShards, shardSize, version } =
|
|
41
|
+
shardConfig || this._automaticallyChooseShardSize(size);
|
|
42
|
+
this.numShards = numShards;
|
|
43
|
+
this.shardSize = shardSize;
|
|
44
|
+
this.keyPrefix = `${prefix}arr|${name}|`;
|
|
45
|
+
this.keyPrefixWithVersion = `${this.keyPrefix}v${version}|`;
|
|
46
|
+
|
|
47
|
+
this.keys = Array(this.numShards);
|
|
48
|
+
for (let shard = 0; shard < this.numShards; shard += 1) {
|
|
49
|
+
this.keys[shard] = `${this.keyPrefixWithVersion}${shard}`;
|
|
50
|
+
}
|
|
51
|
+
this.dirtyShards = new Set();
|
|
52
|
+
this.lastSyncToDB = 0; // Unix epoch
|
|
53
|
+
this.pendingLoads = new Map();
|
|
54
|
+
|
|
55
|
+
const logPrefix = `[arr=<${name}>]`;
|
|
56
|
+
this._debug = logger.debug.bind(logger.debug, logPrefix);
|
|
57
|
+
this._info = logger.info.bind(logger.info, logPrefix);
|
|
58
|
+
this._warn = logger.warn.bind(logger.warn, logPrefix);
|
|
59
|
+
this._error = logger.error.bind(logger.error, logPrefix);
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
async ready() {
|
|
63
|
+
if (!this._ready) {
|
|
64
|
+
this._ready = (async () => {
|
|
65
|
+
const allKeys = await this.db.keys();
|
|
66
|
+
const ourKeys = allKeys.filter((key) => key.startsWith(this.keyPrefix));
|
|
67
|
+
const remainingKeys = new Set(ourKeys);
|
|
68
|
+
this.shards = new Array(this.numShards);
|
|
69
|
+
for (let shard = 0; shard < this.numShards; shard += 1) {
|
|
70
|
+
const found = remainingKeys.delete(this.keys[shard]);
|
|
71
|
+
if (found) {
|
|
72
|
+
this.shards[shard] = undefined; // to be loaded lazily
|
|
73
|
+
} else {
|
|
74
|
+
this.shards[shard] = null; // all-zero
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
if (remainingKeys.size > 0) {
|
|
78
|
+
const unmatchedKeys = [...remainingKeys];
|
|
79
|
+
this._warn(
|
|
80
|
+
'Found',
|
|
81
|
+
unmatchedKeys.size,
|
|
82
|
+
'unmatched keys (will be deleted):',
|
|
83
|
+
unmatchedKeys,
|
|
84
|
+
);
|
|
85
|
+
Promise.all(unmatchedKeys.map((key) => this.db.deleteKey(key)))
|
|
86
|
+
.then(() => this._info('Unmatched keys successfully removed'))
|
|
87
|
+
.catch((e) => this._warn('Failed to delete keys', e));
|
|
88
|
+
}
|
|
89
|
+
})();
|
|
90
|
+
}
|
|
91
|
+
await this._ready;
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
set(pos, val = true) {
|
|
95
|
+
return this.setMany([pos], val);
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
test(pos) {
|
|
99
|
+
return this.testMany([pos]);
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
async setMany(posArray, val = true) {
|
|
103
|
+
await this.ready();
|
|
104
|
+
return Promise.all(posArray.map((pos) => this._internalSetBit(pos, val)));
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
async testMany(posArray) {
|
|
108
|
+
await this.ready();
|
|
109
|
+
|
|
110
|
+
// First check the once that are already loaded in memory.
|
|
111
|
+
const notInMemory = [];
|
|
112
|
+
for (const pos of posArray) {
|
|
113
|
+
const idx = this._toIdx(pos);
|
|
114
|
+
if (this.shards[idx.shard] === null) {
|
|
115
|
+
return false; // the whole shard is 0
|
|
116
|
+
}
|
|
117
|
+
if (this.shards[idx.shard] !== undefined) {
|
|
118
|
+
const isSet = (this.shards[idx.shard][idx.bytePos] & idx.bitMask) !== 0;
|
|
119
|
+
if (!isSet) {
|
|
120
|
+
return false;
|
|
121
|
+
}
|
|
122
|
+
} else {
|
|
123
|
+
notInMemory.push(idx);
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
// Continue if the shards that need to be loaded in memory.
|
|
128
|
+
// Go one by one and only load them lazily.
|
|
129
|
+
for (const { shard, bytePos, bitMask } of notInMemory) {
|
|
130
|
+
await this._loadShard(shard);
|
|
131
|
+
const isSet = (this.shards[shard][bytePos] & bitMask) !== 0;
|
|
132
|
+
if (!isSet) {
|
|
133
|
+
return false;
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
return true;
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
_toIdx(pos) {
|
|
141
|
+
if (pos < 0 || pos > this.size) {
|
|
142
|
+
throw new Error(`Index out of bounds: pos=${pos}, size=${this.size}`);
|
|
143
|
+
}
|
|
144
|
+
const shard = Math.floor(pos / this.shardSize);
|
|
145
|
+
const bitPos = pos - shard * this.shardSize;
|
|
146
|
+
const bytePos = Math.floor(bitPos / 8);
|
|
147
|
+
const bitToSet = bitPos % 8;
|
|
148
|
+
const bitMask = 1 << bitToSet;
|
|
149
|
+
return { shard, bytePos, bitMask };
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
async _internalSetBit(pos, val) {
|
|
153
|
+
const { shard, bytePos, bitMask } = this._toIdx(pos);
|
|
154
|
+
await this._loadShard(shard);
|
|
155
|
+
|
|
156
|
+
const old = this.shards[shard][bytePos];
|
|
157
|
+
if (val) {
|
|
158
|
+
this.shards[shard][bytePos] |= bitMask;
|
|
159
|
+
} else {
|
|
160
|
+
this.shards[shard][bytePos] &= ~bitMask;
|
|
161
|
+
}
|
|
162
|
+
if (this.shards[shard][bytePos] !== old) {
|
|
163
|
+
this._markShardAsDirty(shard);
|
|
164
|
+
}
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
async _loadShard(shard) {
|
|
168
|
+
if (this.shards[shard] === null) {
|
|
169
|
+
this.shards[shard] = new Uint8Array(this.shardSize);
|
|
170
|
+
return;
|
|
171
|
+
}
|
|
172
|
+
if (this.shards[shard] !== undefined) {
|
|
173
|
+
return;
|
|
174
|
+
}
|
|
175
|
+
const existingLoad = this.pendingLoads.get(shard);
|
|
176
|
+
if (existingLoad) {
|
|
177
|
+
await existingLoad;
|
|
178
|
+
return;
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
const pendingLoad = (async () => {
|
|
182
|
+
const value = await this.db.get(this.keys[shard]);
|
|
183
|
+
if (this.shards[shard] === undefined) {
|
|
184
|
+
this.shards[shard] = value;
|
|
185
|
+
} else {
|
|
186
|
+
this._warn(
|
|
187
|
+
'Performance bug: shard was loaded more then one (should not be reachable)',
|
|
188
|
+
);
|
|
189
|
+
}
|
|
190
|
+
})();
|
|
191
|
+
|
|
192
|
+
this.pendingLoads.set(shard, pendingLoad);
|
|
193
|
+
try {
|
|
194
|
+
await pendingLoad;
|
|
195
|
+
} finally {
|
|
196
|
+
this.pendingLoads.delete(shard);
|
|
197
|
+
}
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
_markShardAsDirty(shard) {
|
|
201
|
+
this.dirtyShards.add(shard);
|
|
202
|
+
if (!this._autoFlushTimer) {
|
|
203
|
+
this._autoFlushTimer = setTimeout(() => {
|
|
204
|
+
this.flush().catch(logger.error);
|
|
205
|
+
}, 100); // TODO: reconsider
|
|
206
|
+
}
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
_clearAutoFlush() {
|
|
210
|
+
if (this._autoFlushTimer) {
|
|
211
|
+
clearTimeout(this._autoFlushTimer);
|
|
212
|
+
this._autoFlushTimer = null;
|
|
213
|
+
}
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
async flush() {
|
|
217
|
+
this._clearAutoFlush();
|
|
218
|
+
if (this.dirtyShards.size === 0) {
|
|
219
|
+
return;
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
const shards = [...this.dirtyShards];
|
|
223
|
+
this.dirtyShards.clear();
|
|
224
|
+
|
|
225
|
+
this._debug('flushing', shards.length, 'shards');
|
|
226
|
+
await Promise.all(
|
|
227
|
+
shards.map((shard) => this.db.set(this.keys[shard], this.shards[shard])),
|
|
228
|
+
);
|
|
229
|
+
this._debug(shards.length, 'shards successfully written');
|
|
230
|
+
this.lastSyncToDB = Date.now();
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
_automaticallyChooseShardSize(numBytes) {
|
|
234
|
+
// Increase the version if you change this function. It will force a reset
|
|
235
|
+
// on the client. As this data structure does not provide any consistency
|
|
236
|
+
// guarantees, users of the class should be anticipated to loss data.
|
|
237
|
+
//
|
|
238
|
+
// But if losing the old state is not an option, you can explicitly pass
|
|
239
|
+
// the configuration to the constructor to remain on the old configuration.
|
|
240
|
+
const version = 1;
|
|
241
|
+
const MIN_SHARD_SIZE = 4096;
|
|
242
|
+
const MAX_NUM_SHARDS = 128;
|
|
243
|
+
|
|
244
|
+
const numShards = Math.min(
|
|
245
|
+
Math.ceil(numBytes / MIN_SHARD_SIZE),
|
|
246
|
+
MAX_NUM_SHARDS,
|
|
247
|
+
);
|
|
248
|
+
const shardSize = Math.ceil(numBytes / numShards);
|
|
249
|
+
return { numShards, shardSize, version };
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
async selfChecks(check = new SelfCheck()) {
|
|
253
|
+
if (this.dirtyShards.size > 0) {
|
|
254
|
+
const now = Date.now();
|
|
255
|
+
if (this.lastSyncToDB + 5 * SECOND > now) {
|
|
256
|
+
check.fail('Unwritten changes for more than 5 seconds');
|
|
257
|
+
} else if (this.lastSyncToDB + 500 > now) {
|
|
258
|
+
check.warn('Unwritten changes for more than 500 ms');
|
|
259
|
+
}
|
|
260
|
+
} else {
|
|
261
|
+
check.pass('In sync with the database');
|
|
262
|
+
}
|
|
263
|
+
return check;
|
|
264
|
+
}
|
|
265
|
+
}
|