@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,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
|
+
}
|