@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.
Files changed (179) hide show
  1. package/.editorconfig +12 -0
  2. package/.eslintignore +3 -0
  3. package/.eslintrc +16 -0
  4. package/.github/workflows/release.yml +34 -0
  5. package/.github/workflows/tests.yml +20 -0
  6. package/.prettierrc +9 -0
  7. package/.tool-versions +1 -0
  8. package/CHANGELOG.md +795 -0
  9. package/LICENSE +373 -0
  10. package/README.md +1 -0
  11. package/communication/README.md +11 -0
  12. package/communication/example/index.js +43 -0
  13. package/communication/example/manifest.json +16 -0
  14. package/communication/karma.conf.cjs +19 -0
  15. package/communication/package.json +52 -0
  16. package/communication/rollup.common-config.cjs +17 -0
  17. package/communication/rollup.config.cjs +10 -0
  18. package/communication/src/encoding.js +54 -0
  19. package/communication/src/errors.js +84 -0
  20. package/communication/src/index.js +76 -0
  21. package/communication/src/logger.js +41 -0
  22. package/communication/src/padding.js +60 -0
  23. package/communication/src/proxied-http.js +231 -0
  24. package/communication/src/server-public-key-accessor.js +123 -0
  25. package/communication/src/timestamps.js +37 -0
  26. package/communication/src/trusted-clock.js +58 -0
  27. package/communication/src/utils.js +28 -0
  28. package/communication/src/zlib.js +17 -0
  29. package/communication/test/helpers/in-memory-database.js +43 -0
  30. package/communication/test/server-public-key-accessor.spec.js +135 -0
  31. package/communication/test/utils.spec.js +43 -0
  32. package/package.json +50 -0
  33. package/reporting/TODO.md +2 -0
  34. package/reporting/assets/request/bloom_filter.dat +0 -0
  35. package/reporting/assets/request/update.json +1 -0
  36. package/reporting/example/content.js +11 -0
  37. package/reporting/example/index.js +132 -0
  38. package/reporting/example/inspector/index.html +17 -0
  39. package/reporting/example/inspector/index.js +27 -0
  40. package/reporting/example/manifests/chromium.json +37 -0
  41. package/reporting/example/manifests/firefox.json +35 -0
  42. package/reporting/example/rules.json +62 -0
  43. package/reporting/example/setup.js +1 -0
  44. package/reporting/example/tests/test1.html +10 -0
  45. package/reporting/karma.conf.cjs +22 -0
  46. package/reporting/package.json +63 -0
  47. package/reporting/rollup.common-config.cjs +19 -0
  48. package/reporting/rollup.config.cjs +20 -0
  49. package/reporting/src/LRU.js +149 -0
  50. package/reporting/src/activity-estimator.js +298 -0
  51. package/reporting/src/alive-check.js +139 -0
  52. package/reporting/src/alive-message-generator.js +142 -0
  53. package/reporting/src/bloom-filters.js +345 -0
  54. package/reporting/src/country-provider.js +295 -0
  55. package/reporting/src/cyrb53.js +32 -0
  56. package/reporting/src/digest.js +33 -0
  57. package/reporting/src/doublefetch-page-handler.js +548 -0
  58. package/reporting/src/duplicate-detector.js +233 -0
  59. package/reporting/src/errors.js +84 -0
  60. package/reporting/src/event-listener-queue.js +121 -0
  61. package/reporting/src/fixed-size-cache.js +63 -0
  62. package/reporting/src/hash-detector.js +1526 -0
  63. package/reporting/src/html-parser.js +17 -0
  64. package/reporting/src/http.js +265 -0
  65. package/reporting/src/index.js +14 -0
  66. package/reporting/src/job-scheduler.js +912 -0
  67. package/reporting/src/logger.js +121 -0
  68. package/reporting/src/md5.js +334 -0
  69. package/reporting/src/message-sender.js +51 -0
  70. package/reporting/src/network.js +140 -0
  71. package/reporting/src/new-page-approver.js +119 -0
  72. package/reporting/src/page-aggregator.js +185 -0
  73. package/reporting/src/page-quorum-check-handler.js +200 -0
  74. package/reporting/src/page-structure.js +136 -0
  75. package/reporting/src/pagedb.js +671 -0
  76. package/reporting/src/pages.js +1798 -0
  77. package/reporting/src/patterns-updater.js +310 -0
  78. package/reporting/src/patterns.js +416 -0
  79. package/reporting/src/persisted-bitarray.js +265 -0
  80. package/reporting/src/persisted-hashes.js +189 -0
  81. package/reporting/src/quorum-checker.js +327 -0
  82. package/reporting/src/random.js +39 -0
  83. package/reporting/src/reporting.js +290 -0
  84. package/reporting/src/request/config.js +116 -0
  85. package/reporting/src/request/content-script.js +77 -0
  86. package/reporting/src/request/database.js +147 -0
  87. package/reporting/src/request/dnt.js +24 -0
  88. package/reporting/src/request/hash.js +101 -0
  89. package/reporting/src/request/index.js +874 -0
  90. package/reporting/src/request/page-telemetry.js +42 -0
  91. package/reporting/src/request/qs-whitelist2.js +247 -0
  92. package/reporting/src/request/resources/prob.js +601 -0
  93. package/reporting/src/request/steps/block-rules.js +40 -0
  94. package/reporting/src/request/steps/check-context.js +37 -0
  95. package/reporting/src/request/steps/cookie-context.js +209 -0
  96. package/reporting/src/request/steps/oauth-detector.js +101 -0
  97. package/reporting/src/request/steps/page-logger.js +177 -0
  98. package/reporting/src/request/steps/redirect-tagger.js +75 -0
  99. package/reporting/src/request/steps/subdomain-check.js +34 -0
  100. package/reporting/src/request/steps/token-checker/index.js +189 -0
  101. package/reporting/src/request/steps/token-checker/token-domain.js +129 -0
  102. package/reporting/src/request/steps/token-examiner.js +182 -0
  103. package/reporting/src/request/steps/token-telemetry/cached-entry-pipeline.js +210 -0
  104. package/reporting/src/request/steps/token-telemetry/index.js +234 -0
  105. package/reporting/src/request/steps/token-telemetry/key-pipeline.js +109 -0
  106. package/reporting/src/request/steps/token-telemetry/token-pipeline.js +105 -0
  107. package/reporting/src/request/time.js +73 -0
  108. package/reporting/src/request/utils/bloom-filter-packed.js +107 -0
  109. package/reporting/src/request/utils/chrome-storage-map.js +282 -0
  110. package/reporting/src/request/utils/subject.js +37 -0
  111. package/reporting/src/request/utils/temp-set.js +56 -0
  112. package/reporting/src/request/utils/tlds.js +55 -0
  113. package/reporting/src/request/utils.js +41 -0
  114. package/reporting/src/request-reporter.js +111 -0
  115. package/reporting/src/sanitizer.js +519 -0
  116. package/reporting/src/search-extractor.js +338 -0
  117. package/reporting/src/self-check.js +105 -0
  118. package/reporting/src/seq-executor.js +43 -0
  119. package/reporting/src/session-storage.js +399 -0
  120. package/reporting/src/url-analyzer.js +161 -0
  121. package/reporting/src/url-cleaner.js +60 -0
  122. package/reporting/src/utils/pacemaker.js +279 -0
  123. package/reporting/src/utils/url.js +114 -0
  124. package/reporting/src/utils.js +345 -0
  125. package/reporting/src/webrequest-pipeline/cname-uncloak.js +110 -0
  126. package/reporting/src/webrequest-pipeline/index.js +287 -0
  127. package/reporting/src/webrequest-pipeline/logger.js +14 -0
  128. package/reporting/src/webrequest-pipeline/page-store.js +282 -0
  129. package/reporting/src/webrequest-pipeline/page.js +140 -0
  130. package/reporting/src/webrequest-pipeline/pipeline.js +249 -0
  131. package/reporting/src/webrequest-pipeline/utils/webrequest.js +113 -0
  132. package/reporting/src/webrequest-pipeline/webrequest-context.js +153 -0
  133. package/reporting/test/README.md +2 -0
  134. package/reporting/test/activity-estimator.spec.js +356 -0
  135. package/reporting/test/alive-check.spec.js +156 -0
  136. package/reporting/test/alive-message-generator.spec.js +186 -0
  137. package/reporting/test/country-provider.spec.js +263 -0
  138. package/reporting/test/doublefetch-page-handler.spec.js +818 -0
  139. package/reporting/test/duplicate-detector.spec.js +689 -0
  140. package/reporting/test/helpers/dom-parsers.js +41 -0
  141. package/reporting/test/helpers/fake-session-storage.js +69 -0
  142. package/reporting/test/helpers/fast-check-utils.js +28 -0
  143. package/reporting/test/helpers/fetch-mock.js +57 -0
  144. package/reporting/test/helpers/in-memory-database.js +14 -0
  145. package/reporting/test/helpers/memory-map.js +72 -0
  146. package/reporting/test/helpers/pagedb-mocks.js +41 -0
  147. package/reporting/test/index.js +47 -0
  148. package/reporting/test/job-scheduler.spec.js +691 -0
  149. package/reporting/test/network.spec.js +72 -0
  150. package/reporting/test/page-aggregator.spec.js +104 -0
  151. package/reporting/test/page-quorum-check-handler.spec.js +86 -0
  152. package/reporting/test/pagedb.spec.js +250 -0
  153. package/reporting/test/pages.spec.js +693 -0
  154. package/reporting/test/patterns-updater.spec.js +446 -0
  155. package/reporting/test/patterns.spec.js +751 -0
  156. package/reporting/test/persisted-hashes.spec.js +169 -0
  157. package/reporting/test/reporting.spec.js +205 -0
  158. package/reporting/test/request/database.spec.js +59 -0
  159. package/reporting/test/request/hash.spec.js +108 -0
  160. package/reporting/test/request/index.spec.js +378 -0
  161. package/reporting/test/request/qs-whitelist2.spec.js +189 -0
  162. package/reporting/test/request/steps/check-context.spec.js +51 -0
  163. package/reporting/test/request/steps/oauth-detector.spec.js +339 -0
  164. package/reporting/test/request/test-pages.js +1246 -0
  165. package/reporting/test/request/utils/bloom-filter-packed.spec.js +37 -0
  166. package/reporting/test/request/utils/chrome-storage-map.spec.js +28 -0
  167. package/reporting/test/request/utils/tldts.spec.js +62 -0
  168. package/reporting/test/request/utils.spec.js +168 -0
  169. package/reporting/test/sanitizer.spec.js +1087 -0
  170. package/reporting/test/search-extractor.spec.js +590 -0
  171. package/reporting/test/seq-executor.spec.js +158 -0
  172. package/reporting/test/session-storage.spec.js +400 -0
  173. package/reporting/test/setup.js +24 -0
  174. package/reporting/test/url-analyzer.spec.js +451 -0
  175. package/reporting/test/url-cleaner.spec.js +102 -0
  176. package/reporting/test/utils/pacemaker.spec.js +222 -0
  177. package/reporting/test/utils/url.spec.js +660 -0
  178. package/reporting/test/utils.spec.js +299 -0
  179. package/reporting/test/webrequest-pipeline/pipeline.spec.js +251 -0
@@ -0,0 +1,338 @@
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
+ /* eslint-disable no-continue */
13
+
14
+ import logger from './logger';
15
+ import parseHtml from './html-parser';
16
+ import { fastHash } from './utils';
17
+ import random from './random';
18
+ import { anonymousHttpGet } from './http';
19
+ import { lookupBuiltinTransform } from './patterns';
20
+ import { BadPatternError } from './errors';
21
+
22
+ function doublefetchQueryHash(query, category) {
23
+ // defines a cooldown to avoid performing unnecessary
24
+ // doublefetch requests in short order
25
+ return fastHash(`dfq:${category}:${query.trim()}`, { truncate: true });
26
+ }
27
+
28
+ const HOUR = 60 * 60 * 1000;
29
+
30
+ /**
31
+ * Minimum delay before repeating doublefetch attempts
32
+ * for queries (only counting successful attempts).
33
+ * Waiting for next start of day (in UTC time) is recommended,
34
+ * as trying to send messages earlier is a waste of resources.
35
+ *
36
+ * In addition, enforce a minimum cooldown, intended for people
37
+ * living in timezones like US west coast where UTC midnight
38
+ * happens during the day. Without a minimum cooldown, there is
39
+ * the risk of introducing bias in the collected data, as we
40
+ * would include repeated searches with higher likelihood than
41
+ * in other parts of the world (e.g. Europe).
42
+ */
43
+ function chooseExpiration() {
44
+ const minCooldown = 8 * HOUR;
45
+ const tillNextUtcDay = new Date().setUTCHours(23, 59, 59, 999) + 1;
46
+ const tillCooldown = Date.now() + minCooldown;
47
+ const randomNoise = Math.ceil(random() * 2 * HOUR);
48
+
49
+ return Math.max(tillCooldown, tillNextUtcDay) + randomNoise;
50
+ }
51
+
52
+ function runSelector(item, selector, attr, baseURI) {
53
+ const elem = selector ? item.querySelector(selector) : item;
54
+ if (elem) {
55
+ if (attr === 'textContent') {
56
+ return elem.textContent;
57
+ }
58
+ if (attr === 'href') {
59
+ // Going throw the attribute "href" avoids some of the problems of using
60
+ // directly "elem.href". For relative links the DOMParser cannot
61
+ // accidentally fill in the extension ID as the base. Another advantage
62
+ // (also for absolute links) is that it avoids a double-encoding problem
63
+ // in certain DOM parser (doesn't seem to affect Firefox, but linkedom).
64
+ //
65
+ // Since this part may dependent on the DOMParse implementation, two
66
+ // notes about the intended semantic:
67
+ // * links should be as close to the original page as possible
68
+ // * extensions IDs must not leak into the output
69
+ const rawLink = elem.getAttribute('href');
70
+ return rawLink ? new URL(rawLink, baseURI).href : null;
71
+ }
72
+ if (elem.hasAttribute(attr)) {
73
+ return elem.getAttribute(attr);
74
+ }
75
+ }
76
+ return null;
77
+ }
78
+
79
+ function runTransforms(value, transformSteps = []) {
80
+ if (!Array.isArray(transformSteps)) {
81
+ throw new BadPatternError('Transform definitions must be array.');
82
+ }
83
+ if (value === undefined || value === null) {
84
+ return null;
85
+ }
86
+ let tmpValue = value;
87
+ for (const step of transformSteps) {
88
+ const [name, ...args] = step;
89
+ const transform = lookupBuiltinTransform(name);
90
+ tmpValue = transform(tmpValue, ...args);
91
+ }
92
+ return tmpValue ?? null;
93
+ }
94
+
95
+ function findFirstMatch(rootItem, selectorDef, baseURI) {
96
+ // special case: allows to define multiple rules (first matching rule wins)
97
+ if (selectorDef.firstMatch) {
98
+ for (const { select, attr, transform = [] } of selectorDef.firstMatch) {
99
+ const match = runSelector(rootItem, select, attr, baseURI) ?? null;
100
+ if (match !== null) {
101
+ return runTransforms(match, transform);
102
+ }
103
+ }
104
+ return null;
105
+ }
106
+
107
+ // default case: only one rule
108
+ return (
109
+ runSelector(rootItem, selectorDef.select, selectorDef.attr, baseURI) ?? null
110
+ );
111
+ }
112
+
113
+ export default class SearchExtractor {
114
+ constructor({ patterns, sanitizer, persistedHashes, jobScheduler }) {
115
+ this.patterns = patterns;
116
+ this.sanitizer = sanitizer;
117
+ this.persistedHashes = persistedHashes;
118
+
119
+ jobScheduler.registerHandler('doublefetch-query', async (job) => {
120
+ const { messages } = await this.runJob(job.args);
121
+ return messages.map((message) => ({
122
+ type: 'send-message',
123
+ args: message,
124
+ }));
125
+ });
126
+ }
127
+
128
+ async runJob({ query, category, doublefetchRequest }) {
129
+ function discard(reason = '') {
130
+ logger.debug('No messages found for query:', query, 'Reason:', reason);
131
+ return {
132
+ messages: [],
133
+ reason,
134
+ };
135
+ }
136
+
137
+ const queryCheck = this.sanitizer.checkSuspiciousQuery(query);
138
+ if (!queryCheck.accept) {
139
+ return discard(
140
+ `Dropping suspicious query before double-fetch (${queryCheck.reason})`,
141
+ );
142
+ }
143
+
144
+ const queryHash = doublefetchQueryHash(query, category);
145
+ const expireAt = chooseExpiration();
146
+ const wasAdded = await this.persistedHashes.add(queryHash, expireAt);
147
+ if (!wasAdded) {
148
+ return discard('Query has been recently seen.');
149
+ }
150
+
151
+ let doc;
152
+ try {
153
+ const html = await anonymousHttpGet(doublefetchRequest.url, {
154
+ headers: doublefetchRequest.headers,
155
+ redirect: doublefetchRequest.redirect,
156
+ treat429AsPermanentError: true,
157
+ });
158
+ doc = await parseHtml(html);
159
+ } catch (e) {
160
+ // unblock the hash to allow retries later
161
+ // (at this point, the error could be caused by a network error,
162
+ // so it is still possible that a retry later could work.)
163
+ logger.info('Failed to fetch query:', doublefetchRequest.url, e);
164
+ await this.persistedHashes.delete(queryHash).catch(() => {});
165
+ throw e;
166
+ }
167
+ try {
168
+ const messages = this.extractMessages({
169
+ doc,
170
+ query,
171
+ category,
172
+ doublefetchRequest,
173
+ });
174
+ if (messages.length === 0) {
175
+ return discard('No content found.');
176
+ }
177
+ return { messages };
178
+ } catch (e) {
179
+ // There are two ways to reach it:
180
+ // - The pattern is not supported or there is a logical bug. In both
181
+ // cases, retrying the job does not make sense. Note that unsupported
182
+ // pattern will become more likely on clients that never update.
183
+ // - Doublefetch hit a rate limit (possible but unlikely). On a
184
+ // first glance, retrying looks like a valid strategy, but it may
185
+ // harm the user experience. Thus, it is best to give up at this point.
186
+ logger.warn('Processing failed:', e);
187
+ return discard(`Unsupported pattern: ${e}`);
188
+ }
189
+ }
190
+
191
+ // Note: "doc" may be changed as a side-effect of preprocessing
192
+ extractMessages({ doc, query, category, doublefetchRequest }) {
193
+ const rules = this.patterns.getRulesSnapshot();
194
+ if (!rules[category]) {
195
+ return [];
196
+ }
197
+
198
+ const found = {};
199
+ const baseURI = doublefetchRequest.url;
200
+
201
+ const { preprocess = {}, input = {}, output = {} } = rules[category];
202
+ for (const rule of preprocess.prune || []) {
203
+ if (rule?.first) {
204
+ doc.querySelector(rule.first)?.remove();
205
+ } else if (rule?.all) {
206
+ for (const elem of doc.querySelectorAll(rule.all) || []) {
207
+ elem.remove();
208
+ }
209
+ } else {
210
+ throw new BadPatternError('Bad prune rule (expected "first" or "all")');
211
+ }
212
+ }
213
+
214
+ for (const [selector, selectorDef] of Object.entries(input)) {
215
+ found[selector] = found[selector] || {};
216
+ if (selectorDef.first) {
217
+ const item = doc.querySelector(selector);
218
+ if (item) {
219
+ for (const [key, def] of Object.entries(selectorDef.first)) {
220
+ const value = findFirstMatch(item, def, baseURI);
221
+ found[selector][key] = runTransforms(value, def.transform);
222
+ }
223
+ }
224
+ } else if (selectorDef.all) {
225
+ const rootItems = doc.querySelectorAll(selector);
226
+ if (rootItems) {
227
+ found[selector] = found[selector] || {};
228
+ for (const [key, def] of Object.entries(selectorDef.all)) {
229
+ found[selector][key] = [];
230
+ for (const rootItem of rootItems) {
231
+ const item = findFirstMatch(rootItem, def, baseURI);
232
+ found[selector][key].push(runTransforms(item, def.transform));
233
+ }
234
+ }
235
+ }
236
+ } else {
237
+ throw new BadPatternError('Bad selector (expected "first" or "all")');
238
+ }
239
+ }
240
+
241
+ // meta fields, which are provided instead of being extracted
242
+ const context = {
243
+ q: query ?? null,
244
+ qurl: doublefetchRequest.url,
245
+ ctry: this.sanitizer.getSafeCountryCode(),
246
+ };
247
+ const isPresent = (x) => x !== null && x !== undefined && x !== '';
248
+
249
+ // Now combine the results to build the messages as specified
250
+ // in the "output" section of the patterns.
251
+ //
252
+ // Message payload
253
+ // ---------------
254
+ // There are three origins of the data:
255
+ // 1) a single keys
256
+ // (extracted from an input with a "first" section)
257
+ // 2) array entries that need to be merged
258
+ // (extracted from an input with an "all" section)
259
+ // 3) special entries provided in the context
260
+ //
261
+ // Filtering:
262
+ // ----------
263
+ // By default, all keys of a message have to be present (where empty arrays
264
+ // and empty strings are considered to absent). The default behaviour can be
265
+ // overwritten by setting the "optional" property of a field. Also, the merging
266
+ // of arrays can allow entries with missing values by overwriting the
267
+ // "requiredKeys" property. If not specified, all keys of the array entry need
268
+ // to be present; otherwise, the entry will be skipped.
269
+ const messages = [];
270
+ // eslint-disable-line no-labels, no-restricted-syntax
271
+ nextaction: for (const [action, schema] of Object.entries(output)) {
272
+ const payload = {};
273
+ for (const {
274
+ key,
275
+ source,
276
+ requiredKeys,
277
+ optional = false,
278
+ } of schema.fields) {
279
+ if (source) {
280
+ if (!input[source]) {
281
+ throw new BadPatternError(
282
+ `Output rule for action=${action} references invalid input source=${source}`,
283
+ );
284
+ }
285
+ if (input[source].first) {
286
+ // case 1: single extracted value
287
+ if (!optional && !isPresent(found[source][key])) {
288
+ continue nextaction; // eslint-disable-line no-labels
289
+ }
290
+ payload[key] = found[source][key] ?? null;
291
+ } else if (input[source].all) {
292
+ // case 2: merge the fields from an array of previously extracted values
293
+ const results = [];
294
+ const innerKeys = Object.keys(input[source].all);
295
+ for (const innerKey of innerKeys) {
296
+ found[source][innerKey].forEach((value, idx) => {
297
+ results[idx] = results[idx] || {};
298
+ results[idx][innerKey] = value ?? null;
299
+ });
300
+ }
301
+
302
+ // check if all required data was found
303
+ // (by default, all keys in the fields need to be present)
304
+ const required = requiredKeys || innerKeys;
305
+ const allFieldsPresent = (entry) =>
306
+ required.every((x) => isPresent(entry[x]));
307
+ const cleanedResults = results.filter(allFieldsPresent);
308
+ if (cleanedResults.length === 0 && !optional) {
309
+ continue nextaction; // eslint-disable-line no-labels
310
+ }
311
+ payload[key] = { ...cleanedResults };
312
+ } else {
313
+ throw new BadPatternError(
314
+ `Output rule for action=${action} does not match input key=${key}`,
315
+ );
316
+ }
317
+ } else {
318
+ // case 3: access special keys from the context
319
+ if (!optional && !isPresent(context[key])) {
320
+ continue;
321
+ }
322
+ payload[key] = context[key] ?? null;
323
+ }
324
+ }
325
+
326
+ const { deduplicateBy } = schema;
327
+ const body = {
328
+ action,
329
+ payload,
330
+ ver: 3, // Note: no need to keep this number in sync among messages
331
+ 'anti-duplicates': Math.floor(random() * 10000000),
332
+ };
333
+ messages.push({ body, deduplicateBy });
334
+ }
335
+ logger.debug('Found the following messages:', messages);
336
+ return messages;
337
+ }
338
+ }
@@ -0,0 +1,105 @@
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
+
14
+ /**
15
+ * Provides a standard way to gather diagnostics to display them in
16
+ * a human-readable way. Subcomponents can be nested (with ".for(...)").
17
+ *
18
+ * Self-checks are not expected to run regularly in production.
19
+ * Thus, adding expensive checks is possible.
20
+ */
21
+ export default class SelfCheck {
22
+ fail(...details) {
23
+ logger.warn('[SelfCheck::FAIL]:', ...details);
24
+ this._log('failures', details);
25
+ }
26
+
27
+ warn(...details) {
28
+ logger.warn('[SelfCheck::WARN]:', ...details);
29
+ this._log('warnings', details);
30
+ }
31
+
32
+ pass(...details) {
33
+ this._log('passed', details);
34
+ }
35
+
36
+ skip(...details) {
37
+ this._log('skipped', details);
38
+ }
39
+
40
+ _log(type, details) {
41
+ this.checks = this.checks || {};
42
+ this.checks[type] = this.checks[type] || [];
43
+ this.checks[type].push(details);
44
+ }
45
+
46
+ for(name) {
47
+ if (name === 'checks') {
48
+ throw new Error('"checks" is a reserved name');
49
+ }
50
+ this[name] = this[name] || new SelfCheck();
51
+ return this[name];
52
+ }
53
+
54
+ /**
55
+ * Output:
56
+ * - status: PASSED|WARN|FAILED
57
+ * - overview: total counts by category (failures, warnings, passed, skipped)
58
+ * - log: provides access to the full logs
59
+ */
60
+ report() {
61
+ const types = ['failures', 'warnings', 'passed', 'skipped'];
62
+ const result = {
63
+ overview: Object.fromEntries(
64
+ types.map((x) => [x, this.checks?.[x]?.length || 0]),
65
+ ),
66
+ log: {},
67
+ };
68
+ if (result.overview.failures > 0) {
69
+ result.status = 'FAILED';
70
+ } else if (result.overview.warnings > 0) {
71
+ result.status = 'WARN';
72
+ } else {
73
+ result.status = 'PASSED';
74
+ }
75
+ types.forEach((type) => {
76
+ if (this.checks?.[type]?.length > 0) {
77
+ result.log[type] = { _: this.checks?.[type] };
78
+ } else {
79
+ result.log[type] = {};
80
+ }
81
+ });
82
+ Object.keys(this)
83
+ .filter((x) => x != 'checks')
84
+ .map((x) => [x, this[x].report()])
85
+ .forEach(([x, subresult]) => {
86
+ types.forEach((type) => {
87
+ result.overview[type] += subresult.overview[type];
88
+ if (Object.keys(subresult.log[type]).length > 0) {
89
+ result.log[type][x] = subresult.log[type];
90
+ }
91
+ if (
92
+ result.status !== 'FAILED' &&
93
+ ['FAILED', 'WARN'].includes(subresult.status)
94
+ ) {
95
+ result.status = subresult.status;
96
+ }
97
+ });
98
+ });
99
+ return result;
100
+ }
101
+
102
+ allPassed() {
103
+ return this.report().status === 'PASSED';
104
+ }
105
+ }
@@ -0,0 +1,43 @@
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
+ /**
13
+ * Allows to run async operations one by one (FIFO, first-in first-out).
14
+ * The execution of function will only be started once all previously
15
+ * scheduled functions have resolved (either successfully or by an exception).
16
+ */
17
+ export default class SeqExecutor {
18
+ constructor() {
19
+ this.pending = Promise.resolve();
20
+ }
21
+
22
+ async run(func) {
23
+ let result;
24
+ let failed = false;
25
+ this.pending = this.pending.then(async () => {
26
+ try {
27
+ result = await func();
28
+ } catch (e) {
29
+ failed = true;
30
+ result = e;
31
+ }
32
+ });
33
+ await this.pending;
34
+ if (failed) {
35
+ throw result;
36
+ }
37
+ return result;
38
+ }
39
+
40
+ async waitForAll() {
41
+ await this.pending;
42
+ }
43
+ }