@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,189 @@
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 no-param-reassign: 'off' */
13
+
14
+ import md5, { truncatedHash } from '../../../md5';
15
+ import { tryDecodeURIComponent } from '../../../utils/url';
16
+ import TokenDomain from './token-domain';
17
+
18
+ function decodeToken(token) {
19
+ let decodedToken = tryDecodeURIComponent(token);
20
+ let doubleDecoded = tryDecodeURIComponent(decodedToken);
21
+ while (decodedToken !== doubleDecoded) {
22
+ decodedToken = doubleDecoded;
23
+ doubleDecoded = tryDecodeURIComponent(decodedToken);
24
+ }
25
+ return decodedToken;
26
+ }
27
+
28
+ /**
29
+ * This class checks url components for UIDs and exposes any 'badTokens' found.
30
+ *
31
+ * @class TokenChecker
32
+ * @namespace antitracking.steps
33
+ */
34
+ export default class TokenChecker {
35
+ constructor(qsWhitelist, privateValues, shouldCheckToken, config, db) {
36
+ this.qsWhitelist = qsWhitelist;
37
+ this.config = config;
38
+ this.debug = false;
39
+ this.privateValues = privateValues;
40
+ this.shouldCheckToken = shouldCheckToken;
41
+ this.tokenDomain = new TokenDomain(config, db);
42
+ }
43
+
44
+ init() {
45
+ // IMPORTANT: do NOT await
46
+ // TokenDomain requires async startup but we cannot wait for sake of
47
+ // assigning webRequest listeners
48
+ this.tokenDomain.init();
49
+ }
50
+
51
+ unload() {
52
+ this.tokenDomain.unload();
53
+ }
54
+
55
+ /**
56
+ * Checks for uids in the request url and adds them to the pipeline state `badTokens`
57
+ * attribute
58
+ * @param {Object} state Pipeline state object
59
+ * @return {Boolean} true
60
+ */
61
+ findBadTokens(state) {
62
+ const stats = {};
63
+ state.isTracker = this.qsWhitelist.shouldCheckDomainTokens(
64
+ truncatedHash(state.urlParts.generalDomain),
65
+ );
66
+ state.badTokens = this.checkTokens(
67
+ state.urlParts,
68
+ state.tabUrl,
69
+ stats,
70
+ state.tabUrlParts,
71
+ state.isTracker,
72
+ state.isPrivate,
73
+ );
74
+ // set stats
75
+ if (state.incrementStat) {
76
+ Object.keys(stats).forEach((key) => {
77
+ if (stats[key] > 0) {
78
+ state.incrementStat(`token.has_${key}`);
79
+ state.incrementStat(`token.${key}`, stats[key]);
80
+ }
81
+ });
82
+ if (state.badTokens.length > 0) {
83
+ state.incrementStat('bad_qs');
84
+ state.incrementStat('bad_tokens', state.badTokens.length);
85
+ }
86
+ }
87
+ return true;
88
+ }
89
+
90
+ /**
91
+ * Check all tokens of the url for uids.
92
+ *
93
+ * A token is a uid one of the following apply:
94
+ * - it matches the user's cookie for this page
95
+ * - it matches a private value from JS (from this.privateValues)
96
+ * - it is not on the global safe value list, and its key is not in local nor global
97
+ * safe key lists
98
+ *
99
+ * It must also meet that condition that the same value has been seen on multiple first
100
+ * party domains (this.config.tokenDomainCountThreshold).
101
+ *
102
+ * @param {Object} urlParts Parts of the request url, as parsed by parseURL
103
+ * @param {String} tabUrl The first party url for this request
104
+ A map of cookie values in the first party page - keys are values
105
+ * @param {Object} stats An object to write stats to
106
+ * @param {Object} tabUrlParts Parts of the source url, as parsed by parseURL
107
+ * @param {Boolean} tracker True if the request host is a tracker
108
+ Array of values which we think are uids and should be removed.
109
+ * @return {Array}
110
+ */
111
+ checkTokens(urlParts, tabUrl, stats, tabUrlParts, tracker, isPrivate) {
112
+ // This check is only done for trackers
113
+ if (!tracker) {
114
+ return [];
115
+ }
116
+
117
+ // if there are no query parameters, there is nothing to check
118
+ const keyTokens = urlParts.extractKeyValues().params;
119
+ if (keyTokens.length === 0) {
120
+ return [];
121
+ }
122
+
123
+ const trackerDomain = truncatedHash(urlParts.generalDomain);
124
+ const sourceDomain = truncatedHash(tabUrlParts.generalDomain);
125
+ const badTokens = [];
126
+
127
+ // check for each kv in the url
128
+ const tokenStatus = keyTokens.map((kv) => {
129
+ const key = kv[0];
130
+ const tok = kv[1];
131
+
132
+ // ignore values which don't look like identifiers
133
+ if (!this.shouldCheckToken(tok)) {
134
+ return 'no_check';
135
+ }
136
+
137
+ // if the value is in the main url, ignore
138
+ if (tabUrl.indexOf(tok) > -1) {
139
+ return 'sourceUrl';
140
+ }
141
+
142
+ // make different possible encodings of the token
143
+ if (!this.shouldCheckToken(decodeToken(tok))) {
144
+ return 'no_check_decoded';
145
+ }
146
+
147
+ // if we didn't already match a cookie or private value, do these steps
148
+ if (this.qsWhitelist.isSafeKey(trackerDomain, md5(key))) {
149
+ return 'safekey';
150
+ }
151
+
152
+ if (this.qsWhitelist.isSafeToken(trackerDomain, md5(tok))) {
153
+ return 'whitelisted';
154
+ }
155
+
156
+ const tokenType = 'qs';
157
+
158
+ // count thresholds for token values
159
+ if (!isPrivate) {
160
+ // increment that this token has been seen on this site
161
+ this.tokenDomain.addTokenOnFirstParty(md5(tok), sourceDomain);
162
+ }
163
+ // check if the threshold for cross-domain tokens has been reached
164
+ if (!this.tokenDomain.isTokenDomainThresholdReached(md5(tok))) {
165
+ return `${tokenType}_newToken`;
166
+ }
167
+
168
+ badTokens.push(tok);
169
+ return `${tokenType}_countThreshold`;
170
+ });
171
+
172
+ if (this.debug) {
173
+ // debug message: labeled key values
174
+ const tokenReport = keyTokens.map((kv, i) =>
175
+ Object.assign(kv, { class: tokenStatus[i] }),
176
+ );
177
+ console.log('tokens', urlParts.hostname, tokenReport);
178
+ }
179
+
180
+ tokenStatus.forEach((s) => {
181
+ if (!stats[s]) {
182
+ stats[s] = 0;
183
+ }
184
+ stats[s] += 1;
185
+ });
186
+
187
+ return badTokens;
188
+ }
189
+ }
@@ -0,0 +1,129 @@
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 * as datetime from '../../time';
13
+ import logger from '../../../logger';
14
+ import ChromeStorageMap from '../../utils/chrome-storage-map';
15
+
16
+ const DAYS_EXPIRE = 7;
17
+ const STAGED_TOKEN_EXPIRY = 1000 * 60 * 60 * 24 * 2; // 2 days
18
+
19
+ export default class TokenDomain {
20
+ constructor(config, db) {
21
+ this.config = config;
22
+ this.db = db;
23
+ this.blockedTokens = new Set();
24
+ this.stagedTokenDomain = new ChromeStorageMap({
25
+ storageKey: 'wtm-request-reporting:token-domain:staged-token-domain',
26
+ ttlInMs: STAGED_TOKEN_EXPIRY,
27
+ });
28
+ }
29
+
30
+ async init() {
31
+ // load current tokens over threshold
32
+ await this.stagedTokenDomain.isReady;
33
+ await this.db.ready;
34
+ await this.loadBlockedTokens();
35
+ }
36
+
37
+ unload() {}
38
+
39
+ loadBlockedTokens() {
40
+ // delete expired blocked tokens
41
+ return this.db.tokenBlocked.uniqueKeys().then((blockedTokens) => {
42
+ this.blockedTokens.clear();
43
+ blockedTokens.forEach((tok) => this.blockedTokens.add(tok));
44
+ });
45
+ }
46
+
47
+ /**
48
+ * Mark that the given token was seen on this firstParty. Optionally specify a past day to insert
49
+ * for, otherwise the current day is used
50
+ * @param {String} token token value
51
+ * @param {String} firstParty first party domain
52
+ * @param {String} day (optional) day string (YYYYMMDD format)
53
+ */
54
+ addTokenOnFirstParty(token, firstParty, day) {
55
+ const tokenDay = day || datetime.getCurrentDay();
56
+
57
+ this._addTokenOnFirstParty({
58
+ token,
59
+ firstParty,
60
+ day: tokenDay,
61
+ });
62
+ }
63
+
64
+ _addTokenOnFirstParty({ token, firstParty, day }) {
65
+ if (!this.stagedTokenDomain.has(token)) {
66
+ this.stagedTokenDomain.set(token, {});
67
+ }
68
+ const tokens = this.stagedTokenDomain.get(token);
69
+
70
+ tokens[firstParty] = day;
71
+ return this._checkThresholdReached(token, tokens);
72
+ }
73
+
74
+ _checkThresholdReached(token, tokens) {
75
+ if (Object.keys(tokens).length >= this.config.tokenDomainCountThreshold) {
76
+ this.addBlockedToken(token);
77
+ }
78
+ return this.blockedTokens.has(token);
79
+ }
80
+
81
+ async addBlockedToken(token) {
82
+ if (this.config.debugMode) {
83
+ logger.info('tokenDomain', 'will be blocked:', token);
84
+ }
85
+ const day = datetime.newUTCDate();
86
+ day.setDate(day.getDate() + DAYS_EXPIRE);
87
+ const expires = datetime.dateString(day);
88
+ this.blockedTokens.add(token);
89
+ await this.db.ready;
90
+ return this.db.tokenBlocked.put({
91
+ token,
92
+ expires,
93
+ });
94
+ }
95
+
96
+ isTokenDomainThresholdReached(token) {
97
+ return (
98
+ this.config.tokenDomainCountThreshold < 2 || this.blockedTokens.has(token)
99
+ );
100
+ }
101
+
102
+ clean() {
103
+ const day = datetime.newUTCDate();
104
+ day.setDate(day.getDate() - DAYS_EXPIRE);
105
+ const dayCutoff = datetime.dateString(day);
106
+
107
+ this.stagedTokenDomain.forEach((fps, token) => {
108
+ const toPrune = [];
109
+ Object.entries(fps).forEach(([fp, mtime]) => {
110
+ if (mtime < dayCutoff) {
111
+ toPrune.push(fp);
112
+ }
113
+ });
114
+ toPrune.forEach((fp) => {
115
+ delete fps[fp];
116
+ });
117
+ if (Object.keys(fps).length === 0) {
118
+ this.stagedTokenDomain.delete(token);
119
+ }
120
+ });
121
+ }
122
+
123
+ async clear() {
124
+ await this.db.ready;
125
+ this.blockedTokens.clear();
126
+ this.stagedTokenDomain.clear();
127
+ return this.db.tokenBlocked.clear();
128
+ }
129
+ }
@@ -0,0 +1,182 @@
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 no-param-reassign: 'off' */
13
+
14
+ import * as datetime from '../time';
15
+ import md5, { truncatedHash } from '../../md5';
16
+ import pacemaker from '../../utils/pacemaker';
17
+ import ChromeStorageMap from '../utils/chrome-storage-map';
18
+ import logger from '../../logger';
19
+
20
+ const SYNC_DB_INTERVAL = 20 * 1000;
21
+
22
+ /**
23
+ * Manages the local safekey list
24
+ */
25
+ export default class TokenExaminer {
26
+ constructor(qsWhitelist, config, shouldCheckToken) {
27
+ this.qsWhitelist = qsWhitelist;
28
+ this.config = config;
29
+ this.shouldCheckToken = shouldCheckToken;
30
+ this.hashTokens = true;
31
+ this.requestKeyValue = new ChromeStorageMap({
32
+ storageKey: 'wtm-request-reporting:token-examiner:request-key-value',
33
+ });
34
+ this._syncTimer = null;
35
+ this._lastPrune = null;
36
+ }
37
+
38
+ async init() {
39
+ await this.requestKeyValue.isReady;
40
+ }
41
+
42
+ unload() {
43
+ pacemaker.clearTimeout(this._syncTimer);
44
+ this._syncTimer = null;
45
+ }
46
+
47
+ clearCache() {
48
+ this.requestKeyValue.clear();
49
+ return Promise.resolve();
50
+ }
51
+
52
+ addRequestKeyValueEntry(tracker, key, tokens) {
53
+ if (!this.requestKeyValue.has(tracker)) {
54
+ this.requestKeyValue.set(tracker, {});
55
+ }
56
+ const trackerMap = this.requestKeyValue.get(tracker);
57
+ if (!trackerMap[key]) {
58
+ trackerMap[key] = {};
59
+ }
60
+ const toks = trackerMap[key];
61
+ Object.keys(tokens).forEach((tok) => {
62
+ toks.add(tok, tokens[tok]);
63
+ });
64
+ return toks;
65
+ }
66
+
67
+ removeRequestKeyValueEntry(tracker, key) {
68
+ const trackerMap = this.requestKeyValue.get(tracker);
69
+ if (trackerMap) {
70
+ delete trackerMap[key];
71
+ }
72
+ if (trackerMap && Object.keys(trackerMap).length === 0) {
73
+ this.requestKeyValue.delete(tracker);
74
+ }
75
+ }
76
+
77
+ examineTokens(state) {
78
+ // do not do anything for private tabs and non-tracker domains
79
+ if (
80
+ !state.isPrivate &&
81
+ this.qsWhitelist.isTrackerDomain(
82
+ truncatedHash(state.urlParts.generalDomain),
83
+ )
84
+ ) {
85
+ const today = datetime.getCurrentDay();
86
+
87
+ const tracker = truncatedHash(state.urlParts.generalDomain);
88
+
89
+ // create a Map of key => set(values) from the url data
90
+ const trackerMap = this.requestKeyValue.get(tracker) || {};
91
+ const reachedThreshold = new Set();
92
+ const newTrackerMap = state.urlParts
93
+ .extractKeyValues()
94
+ .params.reduce((hash, kv) => {
95
+ const [k, v] = kv;
96
+ if (!this.shouldCheckToken(v)) {
97
+ return hash;
98
+ }
99
+ const key = this.hashTokens ? md5(k) : k;
100
+ if (this.qsWhitelist.isSafeKey(tracker, key)) {
101
+ return hash;
102
+ }
103
+ const tok = this.hashTokens ? md5(v) : v;
104
+ if (!hash[key]) {
105
+ hash[key] = {};
106
+ }
107
+ hash[key][tok] = today;
108
+ // whitelist any keys which reached the threshold
109
+ if (
110
+ !reachedThreshold.has(key) &&
111
+ Object.keys(hash[key]).length > this.config.safekeyValuesThreshold
112
+ ) {
113
+ reachedThreshold.add(key);
114
+ if (this.config.debugMode) {
115
+ logger.info(
116
+ 'Add safekey',
117
+ state.urlParts.generalDomain,
118
+ key,
119
+ hash[key],
120
+ );
121
+ }
122
+ this.qsWhitelist.addSafeKey(
123
+ tracker,
124
+ this.hashTokens ? key : md5(key),
125
+ this.config.safekeyValuesThreshold,
126
+ );
127
+ }
128
+ return hash;
129
+ }, trackerMap);
130
+
131
+ // push updated cache
132
+ this.requestKeyValue.set(tracker, newTrackerMap);
133
+ this._scheduleSync(today !== this._lastPrune);
134
+ return true;
135
+ }
136
+ return true;
137
+ }
138
+
139
+ getPruneCutoff() {
140
+ const day = datetime.newUTCDate();
141
+ day.setDate(day.getDate() - this.config.safeKeyExpire);
142
+ return datetime.dateString(day);
143
+ }
144
+
145
+ _scheduleSync() {
146
+ if (this._syncTimer) {
147
+ return;
148
+ }
149
+ const syncDb = async () => {
150
+ try {
151
+ await this._syncDb();
152
+ } finally {
153
+ this._syncTimer = null;
154
+ }
155
+ };
156
+ this._syncTimer = pacemaker.setTimeout(syncDb, SYNC_DB_INTERVAL);
157
+ }
158
+
159
+ async _syncDb() {
160
+ const cutoff = this.getPruneCutoff();
161
+ this.requestKeyValue.forEach((trackerMap, tracker) => {
162
+ for (const [key, tokenSet] of Object.entries(trackerMap)) {
163
+ Object.entries(tokenSet).forEach(([value, day]) => {
164
+ if (day < cutoff) {
165
+ delete tokenSet[value];
166
+ }
167
+ });
168
+ if (
169
+ Object.keys(tokenSet).length > this.config.safekeyValuesThreshold &&
170
+ !this.qsWhitelist.isSafeKey(tracker, key)
171
+ ) {
172
+ this.qsWhitelist.addSafeKey(
173
+ tracker,
174
+ this.hashTokens ? key : md5(key),
175
+ Object.keys(tokenSet).length,
176
+ );
177
+ this.removeRequestKeyValueEntry(tracker, key);
178
+ }
179
+ }
180
+ });
181
+ }
182
+ }
@@ -0,0 +1,210 @@
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 Subject from '../../utils/subject';
14
+ import ChromeStorageMap from '../../utils/chrome-storage-map';
15
+
16
+ const CACHE_TTL = 2 * 24 * 60 * 60 * 1000; // 2 days
17
+
18
+ /**
19
+ * Abstract part of token/key processing logic.
20
+ */
21
+ export default class CachedEntryPipeline {
22
+ constructor({ name, db, trustedClock, primaryKey, options }) {
23
+ this.name = name;
24
+ this.db = db;
25
+ this.trustedClock = trustedClock;
26
+ this.cache = new ChromeStorageMap({
27
+ storageKey: `wtm-request-reporting:token-telemetry:${name}`,
28
+ ttlInMs: CACHE_TTL,
29
+ });
30
+ this.primaryKey = primaryKey;
31
+ this.options = options;
32
+ }
33
+
34
+ get(key) {
35
+ const entry = this.getFromCache(key);
36
+ entry.count += 1;
37
+ return entry;
38
+ }
39
+
40
+ /**
41
+ * Loads keys from the database into the map cache. Loading is done by merging with
42
+ * existing values, as defined by #updateCache
43
+ * @param keys
44
+ */
45
+ async loadBatchIntoCache(keys) {
46
+ const rows = await this.db.where({
47
+ primaryKey: this.primaryKey,
48
+ anyOf: keys,
49
+ });
50
+ rows
51
+ .filter((row) => keys.includes(row[this.primaryKey]))
52
+ .forEach((row) => this.updateCache(row));
53
+ }
54
+
55
+ getFromCache(key) {
56
+ let entry = this.cache.get(key);
57
+ if (!entry) {
58
+ entry = this.newEntry();
59
+ this.cache.set(key, entry);
60
+ }
61
+ return entry;
62
+ }
63
+
64
+ /**
65
+ * Saves the values from keys in the map cache to the database. Cached entries are serialised
66
+ * by #serialiseEntry
67
+ * @param keys
68
+ */
69
+ saveBatchToDb(keys) {
70
+ const rows = keys.map((key) => {
71
+ const entry = this.getFromCache(key);
72
+ entry.dirty = false;
73
+ return this.serialiseEntry(key, entry);
74
+ });
75
+ return this.db.bulkPut(rows);
76
+ }
77
+
78
+ /**
79
+ * Create an Rx pipeline to process a stream of tokens or keys at regular intervals
80
+ * and pushes generated messages to the outputSubject.
81
+ * @param inputObservable Observable input to the pipeline
82
+ * @param outputSubject Subject for outputed messages
83
+ * @param batchInterval how often to run batches
84
+ * @param batchLimit maximum messages per batch
85
+ */
86
+ async init(
87
+ inputObservable,
88
+ sendMessage,
89
+ batchInterval,
90
+ batchLimit,
91
+ overflowSubject,
92
+ ) {
93
+ await this.cache.isReady;
94
+ const pipeline = new Subject();
95
+ this.input = inputObservable;
96
+
97
+ let batch = [];
98
+ setInterval(() => {
99
+ pipeline.pub(batch);
100
+ batch = [];
101
+ }, batchInterval);
102
+
103
+ inputObservable.subscribe((token) => {
104
+ batch.push(token);
105
+ });
106
+
107
+ pipeline.subscribe(async (batch) => {
108
+ try {
109
+ // merge existing entries from DB
110
+ await this.loadBatchIntoCache(batch);
111
+ // extract message and clear
112
+ const today = this.trustedClock.getTimeAsYYYYMMDD();
113
+ const toBeSent = batch
114
+ .map((token) => [token, this.getFromCache(token)])
115
+ .filter(([, { lastSent }]) => lastSent !== today);
116
+
117
+ // generate the set of messages to be sent from the candiate list
118
+ const { messages, overflow } = this.createMessagePayloads(
119
+ toBeSent,
120
+ batchLimit,
121
+ );
122
+ // get the keys of the entries not being sent this time
123
+ const overflowKeys = new Set(overflow.map((tup) => tup[0]));
124
+
125
+ // update lastSent for sent messages
126
+ toBeSent
127
+ .filter((tup) => !overflowKeys.has(tup[0]))
128
+ .forEach(([, _entry]) => {
129
+ const entry = _entry;
130
+ entry.lastSent = this.trustedClock.getTimeAsYYYYMMDD();
131
+ });
132
+
133
+ await this.saveBatchToDb(batch);
134
+ // clear the distinct map
135
+ messages.forEach((msg) => {
136
+ sendMessage(msg);
137
+ });
138
+ // push overflowed entries back into the queue
139
+ overflowKeys.forEach((k) => overflowSubject.pub(k));
140
+ } catch (e) {
141
+ logger.error('Failed to initialize stream', e);
142
+ }
143
+ });
144
+ }
145
+
146
+ unload() {}
147
+
148
+ /**
149
+ * Periodic task to take unsent values from the database and push them to be sent,
150
+ * as well as cleaning and persisting the map cache.
151
+ */
152
+ async clean() {
153
+ const batchSize = 1000;
154
+ // max messages will will push from this clean - next clean will be triggered by the time
155
+ // the queue empties
156
+ const maxSending = Math.ceil(
157
+ (this.options.CLEAN_INTERVAL / this.options.TOKEN_BATCH_INTERVAL) *
158
+ (this.options.TOKEN_BATCH_SIZE * this.options.TOKEN_MESSAGE_SIZE),
159
+ );
160
+ // get values from the database which have not yet been sent today
161
+ const today = this.trustedClock.getTimeAsYYYYMMDD();
162
+ const now = Date.now();
163
+ const notSentToday = (await this.db.where({ primaryKey: 'lastSent' }))
164
+ .filter((token) => token.lastSent !== today)
165
+ .slice(0, batchSize)
166
+ .sort((a, b) => a.created > b.created)
167
+ .filter((row) => row.created < now - this.options.NEW_ENTRY_MIN_AGE);
168
+ // check if they have data to send, or are empty objects.
169
+ // - The former are pushed to the batch processing queue
170
+ // - The later can be discarded, as they were just markers for previously sent data
171
+ const toBeDeleted = [];
172
+ const queuedForSending = [];
173
+ const pruneCutoff = now - this.options.LOW_COUNT_DISCARD_AGE;
174
+ notSentToday.forEach((t) => {
175
+ const hasData = this.hasData(t);
176
+ const minCount = t.count > this.options.MIN_COUNT;
177
+ if (hasData && minCount) {
178
+ // this data should be sent
179
+ queuedForSending.push(t[this.primaryKey]);
180
+ } else if (!hasData || t.createdAt < pruneCutoff) {
181
+ // data has been sent, or this is old data that has not reached the threshold
182
+ toBeDeleted.push(t[this.primaryKey]);
183
+ }
184
+ });
185
+ // push first maxSending entries to input queue
186
+ queuedForSending.splice(maxSending);
187
+ queuedForSending.forEach((v) => this.input.pub(v));
188
+ // delete old entries
189
+ this.db.bulkDelete(toBeDeleted);
190
+ // check the cache for items to persist to the db.
191
+ // if we already sent the data, we can remove it from the cache.
192
+ const saveBatch = [];
193
+ this.cache.forEach((value, key) => {
194
+ if (value.dirty) {
195
+ saveBatch.push(key);
196
+ } else if (value.lastSent) {
197
+ this.cache.delete(key);
198
+ }
199
+ });
200
+ await this.saveBatchToDb(saveBatch);
201
+ }
202
+
203
+ createMessagePayloads(toBeSent, batchLimit) {
204
+ const overflow = batchLimit ? toBeSent.splice(batchLimit) : [];
205
+ return {
206
+ messages: toBeSent.map(this.createMessagePayload.bind(this)),
207
+ overflow,
208
+ };
209
+ }
210
+ }