@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,234 @@
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 md5, { truncatedHash } from '../../../md5';
13
+ import Subject from '../../utils/subject';
14
+ import KeyPipeline, { getSiteTokensMap } from './key-pipeline';
15
+ import TokenPipeline from './token-pipeline';
16
+
17
+ const DEFAULT_CONFIG = {
18
+ // token batchs, max 720 messages/hour
19
+ TOKEN_BATCH_INTERVAL: 50 * 1000,
20
+ TOKEN_BATCH_SIZE: 2,
21
+ TOKEN_MESSAGE_SIZE: 10,
22
+ // key batches, max 450 messages/hour
23
+ KEY_BATCH_INTERVAL: 80 * 1000,
24
+ KEY_BATCH_SIZE: 10,
25
+ // clean every 4 mins (activity triggered)
26
+ CLEAN_INTERVAL: 4 * 60 * 1000,
27
+ // batch size of incoming tokens
28
+ TOKEN_BUFFER_TIME: 10 * 1000,
29
+ // minium time to wait before a new token can be sent
30
+ NEW_ENTRY_MIN_AGE: 60 * 60 * 1000,
31
+ // criteria for not sending data
32
+ MIN_COUNT: 1,
33
+ LOW_COUNT_DISCARD_AGE: 1000 * 60 * 60 * 24 * 3, // 3 days
34
+ };
35
+
36
+ /**
37
+ * Token telemetry: Takes a stream of (tracker, key, value) tuples and generates telemetry in
38
+ * the form:
39
+ * - (value, n_sites, n_trackers, safe?), with each value sent max once per calendar day
40
+ * - (key, tracker, site, [values]), with each (key, tracker) tuple sent max once per calendar day
41
+ *
42
+ * The pipeline is constructed as follows:
43
+ * 1. Data comes in from the webrequest-pipeline to #extractKeyTokens
44
+ * 2. Tuples are emitted to #subjectTokens.
45
+ * 3. #_tokenSubscription subscribes to #subjectTokens, groups and batches it, and stores data
46
+ * for each `value` and (tracker, key) tuple in Maps.
47
+ * 4. If entries in the Map caches reach a threshold (not sent today and cross site, or older
48
+ * than NEW_ENTRY_MIN_AGE), they are pushed to the respective send pipelines for tokens or keys.
49
+ * 5. The send pipelines (implemented by CachedEntryPipeline), take a stream of keys from their
50
+ * map cache, and check the conditions for sending, given value this entry may have in the
51
+ * database. Values which pass this check are pushed to the message sending queue.
52
+ *
53
+ * The send pipeline also check their cache and database states periodically to trigger data
54
+ * persistence, or load old data.
55
+ */
56
+ export default class TokenTelemetry {
57
+ constructor(
58
+ telemetry,
59
+ qsWhitelist,
60
+ config,
61
+ database,
62
+ shouldCheckToken,
63
+ options,
64
+ trustedClock,
65
+ ) {
66
+ const opts = { ...DEFAULT_CONFIG, ...options };
67
+ Object.keys(DEFAULT_CONFIG).forEach((confKey) => {
68
+ this[confKey] = opts[confKey];
69
+ });
70
+ this.telemetry = telemetry;
71
+ this.qsWhitelist = qsWhitelist;
72
+ this.config = config;
73
+ this.trustedClock = trustedClock;
74
+ this.shouldCheckToken = shouldCheckToken;
75
+ this.subjectTokens = new Subject();
76
+ this.tokenSendQueue = new Subject();
77
+ this.keySendQueue = new Subject();
78
+
79
+ this.tokens = new TokenPipeline({
80
+ name: 'tokens',
81
+ db: database.tokens,
82
+ trustedClock,
83
+ options: opts,
84
+ });
85
+ this.keys = new KeyPipeline({
86
+ name: 'keys',
87
+ db: database.keys,
88
+ trustedClock,
89
+ options: opts,
90
+ });
91
+ }
92
+
93
+ async init() {
94
+ await this.tokens.isReady;
95
+ await this.keys.isReady;
96
+ let filteredTokensBatch = [];
97
+ const filteredTokens = new Subject();
98
+ setInterval(() => {
99
+ filteredTokens.pub(filteredTokensBatch);
100
+ filteredTokensBatch = [];
101
+ }, this.TOKEN_BUFFER_TIME);
102
+
103
+ this.subjectTokens.subscribe((token) => {
104
+ filteredTokensBatch.push(token);
105
+ });
106
+
107
+ // token subscription pipeline takes batches of tokens (grouped by value)
108
+ // caches their state, and pushes values for sending once they reach a sending
109
+ // threshold.
110
+ const today = this.trustedClock.getTimeAsYYYYMMDD();
111
+ filteredTokens.subscribe((batch) => {
112
+ if (batch.length === 0) {
113
+ return;
114
+ }
115
+ // process a batch of entries for a specific token
116
+ const token = batch[0].token;
117
+
118
+ const tokenStats = this.tokens.get(token);
119
+ const entryCutoff = Date.now() - this.NEW_ENTRY_MIN_AGE;
120
+ tokenStats.dirty = true;
121
+
122
+ batch.forEach((entry) => {
123
+ if (!tokenStats.sites.includes(entry.fp)) {
124
+ tokenStats.sites.push(entry.fp);
125
+ }
126
+ if (!tokenStats.trackers.includes(entry.tp)) {
127
+ tokenStats.trackers.push(entry.tp);
128
+ }
129
+ tokenStats.safe = tokenStats.safe && entry.safe;
130
+
131
+ const keyKey = `${entry.tp}:${entry.key}`;
132
+ const keyStats = this.keys.get(keyKey);
133
+ keyStats.key = entry.key;
134
+ keyStats.tracker = entry.tp;
135
+ keyStats.dirty = true;
136
+ const siteTokens = getSiteTokensMap(keyStats.sitesTokens, entry.fp);
137
+ siteTokens[entry.token] = entry.safe;
138
+
139
+ if (
140
+ keyStats.lastSent !== today &&
141
+ (Object.keys(keyStats.sitesTokens).length > 1 ||
142
+ (keyStats.count > this.MIN_COUNT && keyStats.created < entryCutoff))
143
+ ) {
144
+ this.keySendQueue.pub(keyKey);
145
+ }
146
+ });
147
+ if (
148
+ tokenStats.lastSent !== today &&
149
+ (tokenStats.sites.length > 1 ||
150
+ (tokenStats.count > this.MIN_COUNT &&
151
+ tokenStats.created < entryCutoff))
152
+ ) {
153
+ this.tokenSendQueue.pub(token);
154
+ }
155
+ });
156
+
157
+ this.tokens.init(
158
+ this.tokenSendQueue,
159
+ (payload) => this.telemetry({ action: 'wtm.attrack.tokensv2', payload }),
160
+ this.TOKEN_BATCH_INTERVAL,
161
+ this.TOKEN_BATCH_SIZE,
162
+ this.subjectTokens,
163
+ );
164
+ this.keys.init(
165
+ this.keySendQueue,
166
+ (payload) => this.telemetry({ action: 'wtm.attrack.keysv2', payload }),
167
+ this.KEY_BATCH_INTERVAL,
168
+ this.KEY_BATCH_SIZE,
169
+ this.subjectTokens,
170
+ );
171
+
172
+ // run every x minutes while there is activity
173
+ setInterval(async () => {
174
+ await this.tokens.clean();
175
+ await this.keys.clean();
176
+ }, this.CLEAN_INTERVAL);
177
+ }
178
+
179
+ unload() {
180
+ this.tokens.unload();
181
+ this.keys.unload();
182
+ }
183
+
184
+ extractKeyTokens(state) {
185
+ // ignore private requests
186
+ if (state.isPrivate) return true;
187
+
188
+ const keyTokens = state.urlParts.extractKeyValues().params;
189
+ if (keyTokens.length > 0) {
190
+ // const truncatedDomain = truncateDomain(state.urlParts.host, this.config.tpDomainDepth);
191
+ // const domain = md5(truncatedDomain).substr(0, 16);
192
+ const firstParty = truncatedHash(state.tabUrlParts.generalDomain);
193
+ const generalDomain = truncatedHash(state.urlParts.generalDomain);
194
+ this._saveKeyTokens({
195
+ // thirdParty: truncatedDomain,
196
+ kv: keyTokens,
197
+ firstParty,
198
+ thirdPartyGeneralDomain: generalDomain,
199
+ });
200
+ }
201
+ return true;
202
+ }
203
+
204
+ _saveKeyTokens({ kv, firstParty, thirdPartyGeneralDomain }) {
205
+ // anything here should already be hash
206
+ const isTracker = this.qsWhitelist.isTrackerDomain(thirdPartyGeneralDomain);
207
+
208
+ /* eslint camelcase: 'off' */
209
+ kv.forEach(([k, v]) => {
210
+ if (!this.shouldCheckToken(v)) {
211
+ return;
212
+ }
213
+ const token = md5(v);
214
+ const key = md5(k);
215
+
216
+ // put token in safe bucket if: value is short, domain is not a tracker,
217
+ // or key or value is whitelisted
218
+ const safe =
219
+ !isTracker ||
220
+ this.qsWhitelist.isSafeKey(thirdPartyGeneralDomain, key) ||
221
+ this.qsWhitelist.isSafeToken(thirdPartyGeneralDomain, token);
222
+
223
+ this.subjectTokens.pub({
224
+ day: this.trustedClock.getTimeAsYYYYMMDD(),
225
+ key,
226
+ token,
227
+ tp: thirdPartyGeneralDomain,
228
+ fp: firstParty,
229
+ safe,
230
+ isTracker,
231
+ });
232
+ });
233
+ }
234
+ }
@@ -0,0 +1,109 @@
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 CachedEntryPipeline from './cached-entry-pipeline';
13
+
14
+ export function getSiteTokensMap(siteTokens, key) {
15
+ let siteTokensMap = siteTokens[key];
16
+ if (!siteTokensMap) {
17
+ siteTokensMap = {};
18
+ siteTokens[key] = siteTokensMap;
19
+ }
20
+ return siteTokensMap;
21
+ }
22
+
23
+ export default class KeyPipeline extends CachedEntryPipeline {
24
+ constructor({ db, trustedClock, name, options }) {
25
+ super({ db, trustedClock, name, options, primaryKey: 'hash' });
26
+ }
27
+
28
+ newEntry() {
29
+ return {
30
+ created: Date.now(),
31
+ dirty: true,
32
+ sitesTokens: {},
33
+ count: 0,
34
+ };
35
+ }
36
+
37
+ updateCache({ hash, lastSent, key, tracker, created, sitesTokens, count }) {
38
+ const stats = this.getFromCache(hash);
39
+ if (stats.lastSent === undefined || lastSent > stats.lastSent) {
40
+ stats.lastSent = lastSent;
41
+ }
42
+ stats.key = key;
43
+ stats.tracker = tracker;
44
+ stats.created = Math.min(stats.created, created);
45
+ Object.keys(sitesTokens).forEach((site) => {
46
+ const tokenMap = sitesTokens[site];
47
+ const st = getSiteTokensMap(stats.sitesTokens, site);
48
+ Object.entries(tokenMap).forEach(([token, safe]) => {
49
+ st[token] = safe;
50
+ });
51
+ });
52
+ stats.count = Math.max(stats.count, count);
53
+ }
54
+
55
+ serialiseEntry(hash, stats) {
56
+ const { created, lastSent, key, tracker, sitesTokens, count } = stats;
57
+ return {
58
+ hash,
59
+ key,
60
+ tracker,
61
+ created,
62
+ lastSent: lastSent || '',
63
+ sitesTokens,
64
+ count,
65
+ };
66
+ }
67
+
68
+ createMessagePayloads(toBeSent, batchLimit) {
69
+ // grouping of key messages per site, up to batchLimit
70
+ const groupedMessages = new Map();
71
+ const overflow = [];
72
+ toBeSent.forEach((tuple) => {
73
+ const [, stats] = tuple;
74
+ if (groupedMessages.size >= batchLimit) {
75
+ overflow.push(tuple);
76
+ } else {
77
+ Object.entries(stats.sitesTokens).forEach(([site, tokens]) => {
78
+ // if there are unsafe tokens in the group, make sure this entry is not grouped
79
+ const unsafe = Object.values(tokens).some((t) => t === false);
80
+ const extraKey = unsafe ? `${stats.tracker}:${stats.key}` : '';
81
+ let entry = groupedMessages.get(`${site}${extraKey}`);
82
+ if (!entry) {
83
+ entry = [];
84
+ groupedMessages.set(`${site}${extraKey}`, entry);
85
+ }
86
+ entry.push({
87
+ ts: this.trustedClock.getTimeAsYYYYMMDD(),
88
+ tracker: stats.tracker,
89
+ key: stats.key,
90
+ site,
91
+ tokens: Object.entries(tokens),
92
+ });
93
+ });
94
+ Object.keys(stats.sitesTokens).forEach(
95
+ (key) => delete stats.sitesTokens[key],
96
+ );
97
+ stats.count = 0;
98
+ }
99
+ });
100
+ return {
101
+ messages: [...groupedMessages.values()],
102
+ overflow,
103
+ };
104
+ }
105
+
106
+ hasData(entry) {
107
+ return Object.keys(entry.sitesTokens).length > 0;
108
+ }
109
+ }
@@ -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 CachedEntryPipeline from './cached-entry-pipeline';
13
+
14
+ export default class TokenPipeline extends CachedEntryPipeline {
15
+ constructor({ db, trustedClock, options, name }) {
16
+ super({ db, trustedClock, name, options, primaryKey: 'token' });
17
+ }
18
+
19
+ newEntry() {
20
+ return {
21
+ created: Date.now(),
22
+ sites: [],
23
+ trackers: [],
24
+ safe: true,
25
+ dirty: true,
26
+ count: 0,
27
+ };
28
+ }
29
+
30
+ updateCache({ token, lastSent, safe, created, sites, trackers, count }) {
31
+ const stats = this.getFromCache(token);
32
+ if (stats.lastSent === undefined || lastSent > stats.lastSent) {
33
+ stats.lastSent = lastSent;
34
+ }
35
+ stats.safe = safe;
36
+ stats.created = Math.min(stats.created, created);
37
+ sites.forEach((site) => {
38
+ if (!stats.sites.includes(site)) {
39
+ stats.sites.push(site);
40
+ }
41
+ });
42
+ trackers.forEach((tracker) => {
43
+ if (!stats.trackers.includes(tracker)) {
44
+ stats.trackers.push(tracker);
45
+ }
46
+ });
47
+ stats.count = Math.max(stats.count, count);
48
+ }
49
+
50
+ serialiseEntry(key, tok) {
51
+ const { created, safe, lastSent, sites, trackers, count } = tok;
52
+ return {
53
+ token: key,
54
+ created,
55
+ safe,
56
+ lastSent: lastSent || '',
57
+ sites,
58
+ trackers,
59
+ count,
60
+ };
61
+ }
62
+
63
+ createMessagePayloads(toBeSent, batchLimit) {
64
+ const overflow = batchLimit
65
+ ? toBeSent.splice(batchLimit * this.options.TOKEN_MESSAGE_SIZE)
66
+ : [];
67
+ // group into batchs of size TOKEN_MESSAGE_SIZE
68
+ const nMessages = Math.ceil(
69
+ toBeSent.length / this.options.TOKEN_MESSAGE_SIZE,
70
+ );
71
+ const messages = [...new Array(nMessages)]
72
+ .map((_, i) => {
73
+ const baseIndex = i * this.options.TOKEN_MESSAGE_SIZE;
74
+ return toBeSent.slice(
75
+ baseIndex,
76
+ baseIndex + this.options.TOKEN_MESSAGE_SIZE,
77
+ );
78
+ })
79
+ .map((batch) => batch.map(this.createMessagePayload.bind(this)));
80
+ return {
81
+ messages,
82
+ overflow,
83
+ };
84
+ }
85
+
86
+ createMessagePayload([token, stats]) {
87
+ const msg = {
88
+ ts: this.trustedClock.getTimeAsYYYYMMDD(),
89
+ token,
90
+ safe: stats.safe,
91
+ sites: stats.sites.length,
92
+ trackers: stats.trackers.length,
93
+ };
94
+ // clear
95
+ stats.sites.splice(0, stats.sites.length);
96
+ stats.trackers.splice(0, stats.trackers.length);
97
+ /* eslint no-param-reassign: 'off' */
98
+ stats.count = 0;
99
+ return msg;
100
+ }
101
+
102
+ hasData(entry) {
103
+ return entry.sites.length > 0 && entry.trackers.length > 0;
104
+ }
105
+ }
@@ -0,0 +1,73 @@
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 prefer-template: 'off' */
13
+
14
+ // this is the sanitised timestamp retrieved from humanweb.
15
+ let hwTs = null;
16
+
17
+ /** Get datetime string of the current hour in the format YYYYMMDDHH
18
+ */
19
+ export function getTime() {
20
+ const date = new Date();
21
+ const ts = hwTs;
22
+ let _ts;
23
+ let h = null;
24
+ if (!ts) {
25
+ let d = null;
26
+ let m = null;
27
+ let y = null;
28
+ d = (date.getDate() < 10 ? '0' : '') + date.getDate();
29
+ m = (date.getMonth() < 9 ? '0' : '') + parseInt(date.getMonth() + 1, 10);
30
+ h = (date.getUTCHours() < 10 ? '0' : '') + date.getUTCHours();
31
+ y = date.getFullYear();
32
+ _ts = y + '' + m + '' + d + '' + h;
33
+ } else {
34
+ h = (date.getUTCHours() < 10 ? '0' : '') + date.getUTCHours();
35
+ _ts = ts + '' + h;
36
+ }
37
+ return _ts;
38
+ }
39
+
40
+ export function newUTCDate() {
41
+ const dayHour = getTime();
42
+ return new Date(
43
+ Date.UTC(
44
+ dayHour.substring(0, 4),
45
+ parseInt(dayHour.substring(4, 6), 10) - 1,
46
+ dayHour.substring(6, 8),
47
+ dayHour.substring(8, 10),
48
+ ),
49
+ );
50
+ }
51
+
52
+ export function dateString(date) {
53
+ const yyyy = date.getFullYear().toString();
54
+ const mm = (date.getMonth() + 1).toString(); // getMonth() is zero-based
55
+ const dd = date.getDate().toString();
56
+ return yyyy + (mm[1] ? mm : `0${mm[0]}`) + (dd[1] ? dd : `0${dd[0]}`); // padding
57
+ }
58
+
59
+ export function hourString(date) {
60
+ const hour = date.getUTCHours().toString();
61
+ return dateString(date) + (hour[1] ? hour : `0${hour[0]}`);
62
+ }
63
+
64
+ export function getCurrentDay() {
65
+ if (!getCurrentDay._currentDay || Date.now() > getCurrentDay._nextDayCheck) {
66
+ const day = getTime().substr(0, 8);
67
+ if (day !== getCurrentDay._currentDay) {
68
+ getCurrentDay._nextDayCheck = Date.now() + 60 * 60 * 1000;
69
+ }
70
+ getCurrentDay._currentDay = day;
71
+ }
72
+ return getCurrentDay._currentDay;
73
+ }
@@ -0,0 +1,107 @@
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-bitwise: 'off' */
13
+ import md5 from '../../md5';
14
+
15
+ /**
16
+ * Re-implementation of core/bloom-filter using a packed ArrayBuffer to hold
17
+ * buckets. This prevents the need to copy buckets when the bloom filter is
18
+ * created.
19
+ */
20
+ export default class PackedBloomFilter {
21
+ constructor(buff) {
22
+ this.data = new DataView(buff);
23
+ this.n = this.data.getUint32(0, false);
24
+ this.k = this.data.getUint8(4, false);
25
+ this.m = this.n * 32;
26
+
27
+ const kbytes =
28
+ 1 <<
29
+ Math.ceil(
30
+ Math.log(Math.ceil(Math.log(this.m) / Math.LN2 / 8)) / Math.LN2,
31
+ );
32
+ let Array;
33
+ if (kbytes === 1) {
34
+ Array = Uint8Array;
35
+ } else if (kbytes === 2) {
36
+ Array = Uint16Array;
37
+ } else {
38
+ Array = Uint32Array;
39
+ }
40
+ this._locations = new Array(this.k);
41
+ }
42
+
43
+ getBucket(i) {
44
+ return this.data.getUint32(5 + i * 4, false);
45
+ }
46
+
47
+ locations(a, b) {
48
+ const ai = parseInt(a, 16);
49
+ const bi = parseInt(b, 16);
50
+ let x = ai % this.m;
51
+ for (let i = 0; i < this.k; i += 1) {
52
+ this._locations[i] = x < 0 ? x + this.m : x;
53
+ x = (x + bi) % this.m;
54
+ }
55
+ return this._locations;
56
+ }
57
+
58
+ test(a, b) {
59
+ const l = this.locations(a, b);
60
+ for (let i = 0; i < this.k; i += 1) {
61
+ const bk = l[i];
62
+ if ((this.getBucket(Math.floor(bk / 32)) & (1 << bk % 32)) === 0) {
63
+ return false;
64
+ }
65
+ }
66
+ return true;
67
+ }
68
+
69
+ testSingle(x) {
70
+ const md5Hex = md5(x);
71
+ const a = md5Hex.substring(0, 8);
72
+ const b = md5Hex.substring(8, 16);
73
+ return this.test(a, b);
74
+ }
75
+
76
+ add(a, b) {
77
+ const l = this.locations(a, b);
78
+ for (let i = 0; i < this.k; i += 1) {
79
+ const bk = Math.floor(l[i] / 32);
80
+ const offset = 5 + bk * 4;
81
+ const newValue = this.data.getUint32(offset, false) | (1 << l[i] % 32);
82
+ this.data.setUint32(offset, newValue, false);
83
+ }
84
+ }
85
+
86
+ addSingle(x) {
87
+ const md5Hex = md5(x);
88
+ const a = md5Hex.substring(0, 8);
89
+ const b = md5Hex.substring(8, 16);
90
+ return this.add(a, b);
91
+ }
92
+
93
+ update(buff) {
94
+ const diff = new PackedBloomFilter(buff);
95
+ if (diff.n !== this.n && diff.k !== this.k) {
96
+ throw new Error('Bloom filter can only be updated with same length');
97
+ }
98
+ for (let i = 0; i < this.n; i += 1) {
99
+ const offset = 5 + i * 4;
100
+ this.data.setUint32(
101
+ offset,
102
+ this.data.getUint32(offset) | diff.getBucket(i),
103
+ false,
104
+ );
105
+ }
106
+ }
107
+ }