@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,290 @@
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 Patterns from './patterns';
13
+ import PatternsUpdater from './patterns-updater';
14
+ import CountryProvider from './country-provider';
15
+ import Sanitizer from './sanitizer';
16
+ import UrlAnalyzer from './url-analyzer';
17
+ import Pages from './pages';
18
+ import PageAggregator from './page-aggregator';
19
+ import PageDB from './pagedb';
20
+ import NewPageApprover from './new-page-approver';
21
+ import MessageSender from './message-sender';
22
+ import DuplicateDetector from './duplicate-detector';
23
+ import DoublefetchPageHandler from './doublefetch-page-handler';
24
+ import PageQuorumCheckHandler from './page-quorum-check-handler';
25
+ import QuorumChecker from './quorum-checker';
26
+ import SearchExtractor from './search-extractor';
27
+ import JobScheduler from './job-scheduler';
28
+ import PersistedHashes from './persisted-hashes';
29
+ import AliveCheck from './alive-check';
30
+ import AliveMessageGenerator from './alive-message-generator';
31
+ import SessionStorageWrapper from './session-storage';
32
+ import logger from './logger';
33
+ import SelfCheck from './self-check';
34
+ import { BloomFilter } from './bloom-filters';
35
+
36
+ const SECOND = 1000;
37
+
38
+ export default class Reporting {
39
+ constructor({
40
+ config,
41
+ storage,
42
+ communication,
43
+ connectDatabase,
44
+ browserInfoProvider,
45
+ }) {
46
+ // Defines whether Reporting is fully initialized and has permission
47
+ // to collect data.
48
+ this.isActive = false;
49
+ this._pendingInits = Promise.resolve();
50
+ this._numPendingInits = 0;
51
+ this.communication = communication;
52
+
53
+ this.jobScheduler = new JobScheduler({
54
+ storage,
55
+ storageKey: 'scheduled_jobs',
56
+ });
57
+ this.persistedHashes = new PersistedHashes({
58
+ storage,
59
+ storageKey: 'deduplication_hashes',
60
+ });
61
+ this.bloomFilter = new BloomFilter({
62
+ database: connectDatabase('urlreporter_bloom_filter'),
63
+ name: 'private_pages',
64
+ partitions: [333323, 333331, 333337], // ~ 1 million entries
65
+ });
66
+
67
+ this.newPageApprover = new NewPageApprover(
68
+ this.persistedHashes,
69
+ this.bloomFilter,
70
+ );
71
+ this.pagedb = new PageDB({
72
+ database: connectDatabase('pagedb'),
73
+ newPageApprover: this.newPageApprover,
74
+ });
75
+
76
+ this.patterns = new Patterns();
77
+ this.patternsUpdater = new PatternsUpdater({
78
+ config,
79
+ patterns: this.patterns,
80
+ storage,
81
+ storageKey: 'patterns',
82
+ });
83
+ this.countryProvider = new CountryProvider({
84
+ config,
85
+ storage,
86
+ storageKey: 'ctry',
87
+ });
88
+ this.sanitizer = new Sanitizer(this.countryProvider);
89
+ this.urlAnalyzer = new UrlAnalyzer(this.patterns);
90
+
91
+ this.pageSessionStore = new SessionStorageWrapper({
92
+ namespace: 'wtm::reporting::page',
93
+ });
94
+ this.pages = new Pages({
95
+ config,
96
+ urlAnalyzer: this.urlAnalyzer,
97
+ newPageApprover: this.newPageApprover,
98
+ pageSessionStore: this.pageSessionStore,
99
+ });
100
+ this.pageAggregator = new PageAggregator({
101
+ pages: this.pages,
102
+ pagedb: this.pagedb,
103
+ jobScheduler: this.jobScheduler,
104
+ });
105
+ this.pages.addObserver(
106
+ this.pageAggregator.onPageEvent.bind(this.pageAggregator),
107
+ );
108
+
109
+ this.doublefetchPageHandler = new DoublefetchPageHandler({
110
+ jobScheduler: this.jobScheduler,
111
+ sanitizer: this.sanitizer,
112
+ newPageApprover: this.newPageApprover,
113
+ });
114
+ this.quorumChecker = new QuorumChecker({
115
+ config,
116
+ storage,
117
+ storageKey: 'quorum_check',
118
+ bloomFilter: this.bloomFilter,
119
+ communication,
120
+ });
121
+ this.pageQuorumCheckHandler = new PageQuorumCheckHandler({
122
+ jobScheduler: this.jobScheduler,
123
+ quorumChecker: this.quorumChecker,
124
+ countryProvider: this.countryProvider,
125
+ });
126
+
127
+ this.duplicateDetector = new DuplicateDetector(this.persistedHashes);
128
+ this.messageSender = new MessageSender({
129
+ duplicateDetector: this.duplicateDetector,
130
+ communication,
131
+ jobScheduler: this.jobScheduler,
132
+ });
133
+ this.searchExtractor = new SearchExtractor({
134
+ config,
135
+ patterns: this.patterns,
136
+ sanitizer: this.sanitizer,
137
+ persistedHashes: this.persistedHashes,
138
+ jobScheduler: this.jobScheduler,
139
+ });
140
+
141
+ const aliveMessageGenerator = new AliveMessageGenerator({
142
+ browserInfoProvider,
143
+ quorumChecker: this.quorumChecker,
144
+ storage,
145
+ storageKey: 'alive_config',
146
+ });
147
+ this.aliveCheck = new AliveCheck({
148
+ communication,
149
+ countryProvider: this.countryProvider,
150
+ trustedClock: this.communication.trustedClock,
151
+ aliveMessageGenerator,
152
+ storage,
153
+ storageKey: 'alive_check',
154
+ });
155
+ }
156
+
157
+ async init() {
158
+ this._numPendingInits += 1;
159
+ this._pendingInits = this._pendingInits
160
+ .catch(logger.debug)
161
+ .then(() => this._init())
162
+ .finally(() => {
163
+ this._numPendingInits -= 1;
164
+ });
165
+ return this._pendingInits;
166
+ }
167
+
168
+ unload() {
169
+ const startingUp = this._numPendingInits > 0;
170
+ this._unload();
171
+
172
+ if (startingUp) {
173
+ logger.warn('Trying to unload a module while it is still starting up...');
174
+ this._pendingInits
175
+ .catch(() => {})
176
+ .then(() => {
177
+ logger.warn('Repeating unload to ensure that it remains inactive.');
178
+ this._unload();
179
+ });
180
+ }
181
+ }
182
+
183
+ // Must never be called directly. Always use "init" instead.
184
+ async _init() {
185
+ if (this.isActive) {
186
+ logger.debug('Already initialized');
187
+ return;
188
+ }
189
+ await Promise.all([
190
+ this.pages.init(),
191
+ this.pageAggregator.init(),
192
+ this.duplicateDetector.init(),
193
+ this.patternsUpdater.init(),
194
+ this.countryProvider.init(),
195
+ this.jobScheduler.init(),
196
+ ]);
197
+
198
+ logger.debug('Fully initialized and ready');
199
+ this.isActive = true;
200
+ }
201
+
202
+ // Must never be called directly. Always use "unload" instead.
203
+ _unload() {
204
+ this.isActive = false;
205
+ try {
206
+ this.duplicateDetector.unload();
207
+ this.pages.unload();
208
+ this.pageAggregator.unload();
209
+ this.jobScheduler.unload();
210
+
211
+ // Attempt to finish all pending changes, though it would not
212
+ // be critical if we lose them. Important operations should
213
+ // already have triggered a write operation.
214
+ this.persistedHashes.flush().catch(logger.warn);
215
+ this.pagedb.flush().catch(logger.warn);
216
+ } catch (e) {
217
+ logger.error('Unexpected error during unload. This is likely a bug.', e);
218
+ }
219
+ }
220
+
221
+ /**
222
+ * Should be called when the user navigates to a new page.
223
+ *
224
+ * Calling this function alone should not have a noticable
225
+ * performance impact (both in terms of CPU or network).
226
+ *
227
+ * @return true iff new jobs were registered
228
+ */
229
+ async analyzeUrl(url) {
230
+ if (!this.isActive) {
231
+ return false;
232
+ }
233
+ this.aliveCheck.ping();
234
+ await this._ensurePatternsAreUpToDate();
235
+
236
+ const { isSupported, category, query, doublefetchRequest } =
237
+ this.urlAnalyzer.parseSearchLinks(url);
238
+ if (!isSupported) {
239
+ return false;
240
+ }
241
+
242
+ logger.debug('Potential report found on URL:', url);
243
+ await this.jobScheduler.registerJob({
244
+ type: 'doublefetch-query',
245
+ args: {
246
+ query,
247
+ category,
248
+ doublefetchRequest,
249
+ },
250
+ config: {
251
+ readyIn: { min: 2 * SECOND, max: 8 * SECOND },
252
+ },
253
+ });
254
+ return true;
255
+ }
256
+
257
+ async processPendingJobs() {
258
+ await this._ensurePatternsAreUpToDate();
259
+ return this.jobScheduler.processPendingJobs();
260
+ }
261
+
262
+ async _ensurePatternsAreUpToDate() {
263
+ // Currently, the PatternsUpdater needs to be externally triggered.
264
+ // This implementation detail could be avoided, if the PatternsUpdater
265
+ // could use a browser API like timers in persistent background pages
266
+ // or the Alert API (Manifest V3).
267
+ // The "update" function is a quick operation unless for the rare
268
+ // situation that the patterns are outdated and need to be fetched.
269
+ // Thus, there should be no harm in calling it here.
270
+ await this.patternsUpdater.update();
271
+ }
272
+
273
+ async selfChecks(check = new SelfCheck()) {
274
+ if (!this.isActive) {
275
+ check.warn('reporting is not enabled');
276
+ }
277
+ await Promise.all([
278
+ this.pages.selfChecks(check.for('pages')),
279
+ this.pagedb.selfChecks(check.for('pagedb')),
280
+ this.patterns.selfChecks(check.for('patterns')),
281
+ this.patternsUpdater.selfChecks(check.for('patternsUpdater')),
282
+ this.bloomFilter.selfChecks(check.for('bloomFilter')),
283
+ this.jobScheduler.selfChecks(check.for('jobScheduler')),
284
+ this.quorumChecker.selfChecks(check.for('quorumChecker')),
285
+ this.newPageApprover.selfChecks(check.for('newPageApprover')),
286
+ this.pageSessionStore.selfChecks(check.for('pageSessionStore')),
287
+ ]);
288
+ return check;
289
+ }
290
+ }
@@ -0,0 +1,116 @@
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 pacemaker from '../utils/pacemaker';
13
+ import logger from '../logger';
14
+
15
+ const RETRY_TIMEOUT = 30 * 1000;
16
+
17
+ export const VERSION = '0.103';
18
+
19
+ export const COOKIE_MODE = {
20
+ THIRD_PARTY: 'thirdparty',
21
+ TRACKERS: 'trackers',
22
+ };
23
+
24
+ export const DEFAULTS = {
25
+ safekeyValuesThreshold: 4,
26
+ shortTokenLength: 6,
27
+ placeHolder: 'ghostery',
28
+ cliqzHeader: 'Ghostery-AntiTracking',
29
+ cookieEnabled: true,
30
+ qsEnabled: true,
31
+ sendAntiTrackingHeader: true,
32
+ // tpDomainDepth: 2,
33
+ cookieMode: COOKIE_MODE.THIRD_PARTY,
34
+ };
35
+
36
+ /**
37
+ * These are attributes which are loaded from the remote CONFIG_URL
38
+ * @type {Array}
39
+ */
40
+ const REMOTELY_CONFIGURED = [
41
+ 'blockRules',
42
+ 'cookieWhitelist',
43
+ 'subdomainRewriteRules',
44
+ 'compatibilityList',
45
+ ];
46
+
47
+ export default class Config {
48
+ constructor(
49
+ { defaults = DEFAULTS, configUrl, remoteWhitelistUrl, localWhitelistUrl },
50
+ { db, trustedClock },
51
+ ) {
52
+ this.db = db;
53
+ this.trustedClock = trustedClock;
54
+ this.debugMode = false;
55
+
56
+ if (!configUrl) {
57
+ throw new Error('Config requires configUrl');
58
+ }
59
+ this.configUrl = configUrl;
60
+
61
+ if (!remoteWhitelistUrl) {
62
+ throw new Error('Config requires remoteWhitelistUrl');
63
+ }
64
+ this.remoteWhitelistUrl = remoteWhitelistUrl;
65
+
66
+ if (!localWhitelistUrl) {
67
+ throw new Error('Config requires localWhitelistUrl');
68
+ }
69
+ this.localWhitelistUrl = localWhitelistUrl;
70
+
71
+ this.tokenDomainCountThreshold = 2;
72
+ this.safeKeyExpire = 7;
73
+
74
+ Object.assign(this, defaults);
75
+
76
+ this.paused = false;
77
+ }
78
+
79
+ async init() {
80
+ await this._loadConfig();
81
+ }
82
+
83
+ unload() {}
84
+
85
+ async _loadConfig() {
86
+ await this.db.ready;
87
+ const lastUpdate = (await this.db.get('config')) || {};
88
+ const day = this.trustedClock.getTimeAsYYYYMMDD();
89
+ // use stored config if it was already updated today
90
+ if (lastUpdate['config'] && lastUpdate['lastUpdate'] === day) {
91
+ this._updateConfig(lastUpdate['config']);
92
+ return;
93
+ }
94
+ try {
95
+ const response = await fetch(this.configUrl);
96
+ if (!response.ok) {
97
+ throw new Error(response.text());
98
+ }
99
+ const conf = await response.json();
100
+ this._updateConfig(conf);
101
+ await this.db.set('config', {
102
+ lastUpdate: day,
103
+ config: conf,
104
+ });
105
+ } catch (e) {
106
+ logger.error('could not load request config', e);
107
+ pacemaker.setTimeout(this._loadConfig.bind(this), RETRY_TIMEOUT);
108
+ }
109
+ }
110
+
111
+ _updateConfig(conf) {
112
+ REMOTELY_CONFIGURED.forEach((key) => {
113
+ this[key] = conf[key];
114
+ });
115
+ }
116
+ }
@@ -0,0 +1,77 @@
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
+ export function recordMouseDown(ev) {
13
+ function getContextHTML(ev) {
14
+ let target = ev.target;
15
+ let html;
16
+
17
+ try {
18
+ for (let count = 0; count < 5; count += 1) {
19
+ html = target.innerHTML;
20
+
21
+ if (html.indexOf('http://') !== -1 || html.indexOf('https://') !== -1) {
22
+ return html;
23
+ }
24
+
25
+ target = target.parentNode;
26
+
27
+ count += 1;
28
+ }
29
+ } catch (ee) {
30
+ console.warn('WTM Reporting: failed to record context from mousedown');
31
+ }
32
+
33
+ return undefined;
34
+ }
35
+
36
+ const linksSrc = [];
37
+ if (window.parent !== window) {
38
+ // collect srcipt links only for frames
39
+ if (window.document && window.document.scripts) {
40
+ for (let i = 0; i < window.document.scripts.length; i += 1) {
41
+ const src = window.document.scripts[i].src;
42
+ if (src.startsWith('http')) {
43
+ linksSrc.push(src);
44
+ }
45
+ }
46
+ }
47
+ }
48
+
49
+ let node = ev.target;
50
+ if (node.nodeType !== 1) {
51
+ node = node.parentNode;
52
+ }
53
+
54
+ let href = null;
55
+
56
+ if (node.closest('a[href]')) {
57
+ href = node.closest('a[href]').getAttribute('href');
58
+ }
59
+
60
+ const event = {
61
+ target: {
62
+ baseURI: ev.target.baseURI,
63
+ value: ev.target.value,
64
+ href: ev.target.href,
65
+ parentNode: {
66
+ href: ev.target.parentNode ? ev.target.parentNode.href : null,
67
+ },
68
+ linksSrc,
69
+ },
70
+ };
71
+
72
+ return {
73
+ event,
74
+ context: getContextHTML(ev),
75
+ href,
76
+ };
77
+ }
@@ -0,0 +1,147 @@
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 IDB from 'idb';
13
+
14
+ class IDBWrapper {
15
+ constructor(db, tableName, primaryKey) {
16
+ this.db = db;
17
+ this.tableName = tableName;
18
+ this.primaryKey = primaryKey;
19
+ }
20
+
21
+ async put(value) {
22
+ await this.db.put(this.tableName, value);
23
+ }
24
+
25
+ async clear() {
26
+ await this.db.clear(this.tableName);
27
+ }
28
+
29
+ async uniqueKeys() {
30
+ return this.db.getAllKeys(this.tableName);
31
+ }
32
+
33
+ async count() {
34
+ return this.db.count(this.tableName);
35
+ }
36
+
37
+ async bulkPut(rows) {
38
+ if (rows.length === 0) {
39
+ return;
40
+ }
41
+ const tx = this.db.transaction(this.tableName, 'readwrite');
42
+ await Promise.all(rows.map((row) => tx.store.put(row)));
43
+ await tx.done;
44
+ }
45
+
46
+ async bulkDelete(keys) {
47
+ if (keys.length === 0) {
48
+ return;
49
+ }
50
+ const tx = this.db.transaction(this.tableName, 'readwrite');
51
+ await Promise.all(keys.map((key) => tx.store.delete(key)));
52
+ await tx.done;
53
+ }
54
+
55
+ async where({ primaryKey }) {
56
+ if (primaryKey === this.primaryKey) {
57
+ return await this.db.getAll(this.tableName);
58
+ } else {
59
+ return await this.db.getAllFromIndex(this.tableName, primaryKey);
60
+ }
61
+ }
62
+ }
63
+
64
+ export default class AttrackDatabase {
65
+ constructor() {
66
+ this.tableName = 'antitracking';
67
+ this.db = null;
68
+ this._ready = null;
69
+ }
70
+
71
+ async init() {
72
+ let resolver;
73
+ this._ready = new Promise((resolve) => {
74
+ resolver = resolve;
75
+ });
76
+ this.db = await IDB.openDB(this.tableName, 21, {
77
+ async upgrade(db, oldVersion, newVersion) {
78
+ if (oldVersion < 1) {
79
+ const tokenBlockedStore = db.createObjectStore('tokenBlocked', {
80
+ keyPath: 'token',
81
+ });
82
+ tokenBlockedStore.createIndex('token', 'token');
83
+ tokenBlockedStore.createIndex('expires', 'expires');
84
+
85
+ const tokensStore = db.createObjectStore('tokens', {
86
+ keyPath: 'token',
87
+ });
88
+ tokensStore.createIndex('lastSent', 'lastSent');
89
+ tokensStore.createIndex('created', 'created');
90
+
91
+ const keysStore = db.createObjectStore('keys', { keyPath: 'hash' });
92
+ keysStore.createIndex('lastSent', 'lastSent');
93
+ keysStore.createIndex('created', 'created');
94
+ }
95
+
96
+ if (newVersion >= 21) {
97
+ db.createObjectStore('keyval');
98
+ }
99
+
100
+ if (db.objectStoreNames.contains('tokenDomain')) {
101
+ db.deleteObjectStore('tokenDomain');
102
+ }
103
+
104
+ if (db.objectStoreNames.contains('requestKeyValue')) {
105
+ db.deleteObjectStore('requestKeyValue');
106
+ }
107
+ },
108
+ });
109
+ resolver();
110
+ }
111
+
112
+ unload() {
113
+ if (this.db !== null) {
114
+ this.db.close();
115
+ this.db = null;
116
+ }
117
+ }
118
+
119
+ get ready() {
120
+ if (this._ready === null) {
121
+ return Promise.reject(new Error('init not called'));
122
+ }
123
+ return this._ready;
124
+ }
125
+
126
+ get tokenBlocked() {
127
+ return new IDBWrapper(this.db, 'tokenBlocked', 'token');
128
+ }
129
+
130
+ get tokens() {
131
+ return new IDBWrapper(this.db, 'tokens', 'token');
132
+ }
133
+
134
+ get keys() {
135
+ return new IDBWrapper(this.db, 'keys', 'hash');
136
+ }
137
+
138
+ async get(key) {
139
+ await this._ready;
140
+ return this.db.get('keyval', key);
141
+ }
142
+
143
+ async set(key, val) {
144
+ await this._ready;
145
+ return this.db.put('keyval', val, key);
146
+ }
147
+ }
@@ -0,0 +1,24 @@
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
+ * Extacts values from the DNT Tk header, given a list of response headers for a request
14
+ * https://www.w3.org/TR/tracking-dnt/#dfn-tk
15
+ * @param responseHeaders
16
+ */
17
+ export default function getTrackingStatus(state) {
18
+ const status = state.getResponseHeader('tk');
19
+ if (status) {
20
+ const [value, statusId] = status.split(';');
21
+ return { value, statusId };
22
+ }
23
+ return null;
24
+ }