@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,119 @@
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 { fastHash, roundUpToNextUTCMidnight } from './utils';
14
+ import SelfCheck from './self-check';
15
+
16
+ const SECOND = 1000;
17
+ const MINUTE = 60 * SECOND;
18
+ const HOUR = 60 * MINUTE;
19
+
20
+ /**
21
+ * Key to be stored in the bloom filter.
22
+ */
23
+ function privatePageKey(url) {
24
+ return `[private-url]${url}`;
25
+ }
26
+
27
+ /**
28
+ * Before we look at a page again, we should wait at least until the next day
29
+ * in UTC time. Since this may be in the middle of a day (e.g. in the US), the
30
+ * cooldown should make it likely that the aggregation of new page starts with
31
+ * a new day.
32
+ */
33
+ export function determineEndOfPageCooldown(createdAt = Date.now()) {
34
+ const utcMidnight = roundUpToNextUTCMidnight(createdAt);
35
+ const diff = utcMidnight - createdAt;
36
+ const minCooldown = Math.max(diff, 14 * HOUR);
37
+ const randomNoise = Math.random() * 2 * HOUR;
38
+ return Math.ceil(createdAt + minCooldown + randomNoise);
39
+ }
40
+
41
+ export default class NewPageApprover {
42
+ constructor(persistedHashes, privatePageBloomFilter) {
43
+ this.persistedHashes = persistedHashes;
44
+ this.privatePageBloomFilter = privatePageBloomFilter;
45
+
46
+ this.privatePagesWriteBuffer = new Set();
47
+ this.privatePagesWriteBufferLimit = 1000;
48
+ }
49
+
50
+ async allowCreation(url, now = Date.now()) {
51
+ function reject(reason) {
52
+ return { ok: false, reason };
53
+ }
54
+
55
+ const hash = fastHash(url, { truncate: true });
56
+ if (await this.persistedHashes.has(hash)) {
57
+ return reject('end of cooldown not reached yet');
58
+ }
59
+ if (await this.privatePageBloomFilter.mightContain(url)) {
60
+ return reject('page has been (possibly) marked as private before');
61
+ }
62
+
63
+ // Note: we do not need to use trustedClock here, since the timeout
64
+ // is randomized and should not be exploitable.
65
+ const expireAt = determineEndOfPageCooldown(now);
66
+ await this.persistedHashes.add(hash, expireAt);
67
+ return { ok: true };
68
+ }
69
+
70
+ async mightBeMarkedAsPrivate(url) {
71
+ return (
72
+ this.privatePagesWriteBuffer.has(url) ||
73
+ (await this.privatePageBloomFilter.mightContain(privatePageKey(url)))
74
+ );
75
+ }
76
+
77
+ async markAsPrivate(url) {
78
+ if (
79
+ this.privatePagesWriteBuffer.size >= this.privatePagesWriteBufferLimit
80
+ ) {
81
+ // Practically, this should be hard to reach. This code exists only to
82
+ // have a guarantee that the write buffer cannot grow infinitely.
83
+ logger.error(
84
+ 'Overrun detected in the private pages cache (limit=${this.privatePagesWriteBufferLimit}).',
85
+ 'Clear cache and continue...',
86
+ );
87
+ this.privatePagesWriteBuffer.clear();
88
+ }
89
+
90
+ this.privatePagesWriteBuffer.add(url);
91
+ try {
92
+ await this.privatePageBloomFilter.add(privatePageKey(url));
93
+ this.privatePagesWriteBuffer.delete(url);
94
+ } catch (e) {
95
+ logger.warn(
96
+ 'Failed to mark page as private on disk (only in memory):',
97
+ url,
98
+ );
99
+ throw e;
100
+ }
101
+ }
102
+
103
+ async selfChecks(check = new SelfCheck()) {
104
+ const numUrls = this.privatePagesWriteBuffer;
105
+ if (numUrls > this.privatePagesWriteBufferLimit) {
106
+ check.fail(
107
+ 'Overrun detected in write buffer (is there a problem with the bloom filter?):',
108
+ { numUrls: this.privatePagesWriteBuffer.size },
109
+ );
110
+ } else if (numUrls >= 2) {
111
+ const urls = [...this.privatePagesWriteBuffer];
112
+ check.warn(
113
+ 'Unflushed private pages detected (is there a problem with the bloom filter?):',
114
+ { numUrls, urls },
115
+ );
116
+ }
117
+ return check;
118
+ }
119
+ }
@@ -0,0 +1,185 @@
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 SeqExecutor from './seq-executor';
14
+
15
+ const SECOND = 1000;
16
+
17
+ const COOLDOWN_FOR_EXPIRED_PAGES_CHECK = 2 * SECOND;
18
+ const COOLDOWN_FOR_FORCING_A_FULL_SYNC = 90 * SECOND;
19
+
20
+ export default class PageAggregator {
21
+ constructor({ pages, pagedb, jobScheduler }) {
22
+ this.active = false;
23
+
24
+ this.pages = pages;
25
+ this.pagedb = pagedb;
26
+ this.jobScheduler = jobScheduler;
27
+
28
+ this._dbExecutor = new SeqExecutor();
29
+ this._lastFullSync = 0; // Unix epoch
30
+ this._lastExpiredPagesCheck = 0; // Unix epoch
31
+ }
32
+
33
+ async init() {
34
+ this.active = true;
35
+ }
36
+
37
+ unload() {
38
+ this.active = false;
39
+ this.pagedb.flush().catch(console.error);
40
+ }
41
+
42
+ onPageEvent(event) {
43
+ if (!this.active) {
44
+ return;
45
+ }
46
+
47
+ if (event.type === 'full-sync') {
48
+ this.fullSync();
49
+ } else if (event.type === 'lazy-init' || event.type === 'page-updated') {
50
+ // TODO: is there a down-side in increasing the cooldown?
51
+ // (especially, if there are many tabs open, it may become a problem)
52
+ if (Date.now() > this._lastFullSync + COOLDOWN_FOR_FORCING_A_FULL_SYNC) {
53
+ logger.debug('Forcing full sync');
54
+ this.fullSync();
55
+ } else {
56
+ const { tabId } = event;
57
+ this.syncTab(tabId);
58
+ }
59
+ } else if (event.type === 'activity-updated') {
60
+ const { urls, activityEstimator } = event;
61
+ this._dbExecutor
62
+ .run(async () => {
63
+ await this.pagedb.updateActivity(urls, activityEstimator);
64
+ })
65
+ .catch(console.error);
66
+ } else {
67
+ logger.warn('Unexpected signal:', event);
68
+ }
69
+ }
70
+
71
+ fullSync() {
72
+ const updateInfo = {
73
+ fetchPagesToUpdate: () => {
74
+ const { openTabs, activeTab } = this.pages.describe();
75
+ const openPages = Object.values(openTabs);
76
+ const activePage = activeTab?.tab;
77
+ return { openPages, activePage };
78
+ },
79
+ isFullSync: true,
80
+ };
81
+
82
+ this._lastFullSync = Date.now();
83
+ this._syncToDB(updateInfo).catch(logger.error);
84
+ }
85
+
86
+ syncTab(tabId) {
87
+ const updateInfo = {
88
+ fetchPagesToUpdate: () => {
89
+ const page = this.pages.describeTab(tabId);
90
+ if (!page) {
91
+ return { openPages: [], activePage: null };
92
+ }
93
+ const activeTabId = this.pages.getActiveTabId();
94
+ const activePage = activeTabId === tabId ? page : null;
95
+ return { openPages: [page], activePage };
96
+ },
97
+ isFullSync: false,
98
+ };
99
+
100
+ this._syncToDB(updateInfo).catch(logger.error);
101
+ }
102
+
103
+ async _syncToDB(updateInfo) {
104
+ await this._dbExecutor.run(async () => {
105
+ const { openPages, activePage } = updateInfo.fetchPagesToUpdate();
106
+ await this.pagedb.updatePages(openPages, activePage, {
107
+ isFullSync: updateInfo.isFullSync,
108
+ });
109
+ });
110
+ this._expirePagesInBackground();
111
+ }
112
+
113
+ /**
114
+ * For options, see PageDB#acquireExpiredPages
115
+ */
116
+ async checkExpiredPages(options = {}) {
117
+ if (!this.active) {
118
+ logger.warn('checkExpiredPages ignored since the module is not active');
119
+ return { numJobsCreated: 0 };
120
+ }
121
+
122
+ const now = Date.now();
123
+ if (
124
+ now < this._lastExpiredPagesCheck + COOLDOWN_FOR_EXPIRED_PAGES_CHECK &&
125
+ !options.forceExpiration
126
+ ) {
127
+ return { numJobsCreated: 0 };
128
+ }
129
+
130
+ // The default batch size is a trade-off. For performance, bigger should
131
+ // be better; but smaller sizes release the pagedb locks in-between
132
+ // (needed for updates) and it also reduces the risk of losing jobs
133
+ // (if the cannot be registered, but where already taken out of pagedb).
134
+ const defaultBatchSize = 20;
135
+ const maxSteps = 100;
136
+
137
+ options = { maxEntriesToCheck: defaultBatchSize, ...options };
138
+ let numJobsCreated = 0;
139
+ let step;
140
+ for (step = 0; step < maxSteps; step += 1) {
141
+ this._lastExpiredPagesCheck = now;
142
+ const expiredPages = await this.pagedb.acquireExpiredPages(options);
143
+ if (expiredPages.length === 0) {
144
+ break;
145
+ }
146
+
147
+ const jobs = expiredPages.map((page) => ({
148
+ type: 'doublefetch-page',
149
+ args: { page },
150
+ }));
151
+ try {
152
+ logger.debug('Creating', jobs.length, 'jobs for expired pages:', jobs);
153
+ await this.jobScheduler.registerJobs(jobs);
154
+ numJobsCreated += expiredPages.length;
155
+ } catch (e) {
156
+ logger.error('Failed to register jobs:', jobs.length, 'jobs were lost');
157
+ logger.debug('Lost jobs:', jobs);
158
+ return { numJobsCreated };
159
+ }
160
+ }
161
+
162
+ if (step === maxSteps) {
163
+ logger.warn(
164
+ 'Exceeded the iteration cap of',
165
+ maxSteps,
166
+ 'steps (no error, but highly unexpected)',
167
+ );
168
+ }
169
+
170
+ if (numJobsCreated > 0) {
171
+ logger.info(numJobsCreated, 'jobs created for expired pages');
172
+ }
173
+ return { numJobsCreated };
174
+ }
175
+
176
+ _expirePagesInBackground() {
177
+ (async () => {
178
+ try {
179
+ await this.checkExpiredPages();
180
+ } catch (e) {
181
+ logger.error('Unexpected error while expiring pages', e);
182
+ }
183
+ })();
184
+ }
185
+ }
@@ -0,0 +1,200 @@
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 { BadJobError } from './errors';
14
+ import random from './random';
15
+
16
+ function createPageMessage(safePage, ctry) {
17
+ const { url, title, ref = null, redirects = null, search, lang } = safePage;
18
+ const { activity } = safePage.aggregator;
19
+
20
+ const payload = {
21
+ url,
22
+ t: title,
23
+ ref,
24
+ redirects,
25
+ lang,
26
+ ctry,
27
+ activity,
28
+ };
29
+ if (search) {
30
+ // note: if the query failed the sanitizer checks, it will be omitted here
31
+ payload.qr = {
32
+ q: search.query,
33
+ t: search.category,
34
+ d: search.depth,
35
+ };
36
+ }
37
+
38
+ // consider page messages as duplicates if "payload.url" is identical
39
+ const deduplicateBy = 'url';
40
+
41
+ const body = {
42
+ action: 'wtm.page',
43
+ payload,
44
+ ver: 3, // Note: no need to keep this number in sync among messages
45
+ 'anti-duplicates': Math.floor(random() * 10000000),
46
+ };
47
+ return { body, deduplicateBy };
48
+ }
49
+
50
+ // Abstraction layer to avoid making multiple quorum checks for the same URL
51
+ // (mostly because of redirects). Not intended as a permanent cache, but it is
52
+ // limited to the processing of one message.
53
+ class CachedQuorumChecker {
54
+ constructor(quorumChecker) {
55
+ this.quorumChecker = quorumChecker;
56
+ this.cached = new Map();
57
+ }
58
+
59
+ async isQuorumReached(url) {
60
+ const cacheHit = this.cached.get(url);
61
+ if (cacheHit) {
62
+ return cacheHit;
63
+ }
64
+
65
+ const pending = this.quorumChecker.checkQuorumConsent({ text: url });
66
+ this.cached.set(url, pending);
67
+ pending.catch((e) => {
68
+ logger.warn('Quorum check for URL', url, 'failed', e);
69
+ });
70
+ return pending;
71
+ }
72
+ }
73
+
74
+ export default class PageQuorumCheckHandler {
75
+ constructor({ jobScheduler, quorumChecker, countryProvider }) {
76
+ this.quorumChecker = quorumChecker;
77
+ this.countryProvider = countryProvider;
78
+
79
+ jobScheduler.registerHandler('page-quorum-check', async (job) => {
80
+ const message = await this.runJob(job.args.safePage);
81
+ if (!message) {
82
+ return [];
83
+ }
84
+ logger.debug('Page message ready:', message);
85
+ return [{ type: 'send-message', args: message }];
86
+ });
87
+ }
88
+
89
+ async runJob(safePage) {
90
+ if (!safePage) {
91
+ throw new BadJobError('page information missing');
92
+ }
93
+ const { url } = safePage;
94
+ if (!url) {
95
+ throw new BadJobError('url missing');
96
+ }
97
+
98
+ // Phase 1: Quorum voting
99
+ //
100
+ // Try to vote for all URLs (only the ones that have been already voted for will be skipped).
101
+ // Note that we will not necessarily do a quorum check all URLs in phase 2. If the original URL
102
+ // fails, we can exit early because the whole message will be dropped anyway. But voting is still
103
+ // useful, since it helps the system to learn about safe URLs. That is why we also vote even
104
+ // for pages that came from a search engine (and thus are public). Why? Because voting will help
105
+ // other clients that reach the identical page but not directly from a search engine.
106
+ const uniqueUrlsToInc = new Set([url]);
107
+ if (safePage.ref) {
108
+ uniqueUrlsToInc.add(safePage.ref);
109
+ }
110
+ if (safePage.redirects) {
111
+ for (const { from, to } of safePage.redirects) {
112
+ uniqueUrlsToInc.add(from);
113
+
114
+ // ignore the magic '...' marker
115
+ // (used to break long redirect chains from misconfigured servers)
116
+ if (to !== '...') {
117
+ uniqueUrlsToInc.add(to);
118
+ }
119
+ }
120
+ }
121
+ const urlsToInc = [...uniqueUrlsToInc];
122
+ const parsedUrls = new Map(
123
+ urlsToInc.map((url) => {
124
+ const postfix = ' (PROTECTED)';
125
+ const normalizedUrl = url.endsWith(postfix)
126
+ ? url.slice(0, -postfix.length)
127
+ : url;
128
+ try {
129
+ return [url, new URL(normalizedUrl)];
130
+ } catch (e) {
131
+ throw new BadJobError(
132
+ `Failed to parse URL (url=${url}, normalizedUrl=${normalizedUrl})`,
133
+ );
134
+ }
135
+ }),
136
+ );
137
+ const isPureDomain = (url) => {
138
+ const { pathname, search, hash } = parsedUrls.get(url);
139
+ return pathname === '/' && !search && !hash;
140
+ };
141
+ for (const urlToInc of urlsToInc) {
142
+ if (!isPureDomain(urlToInc)) {
143
+ await this.quorumChecker.sendQuorumIncrement({ text: urlToInc });
144
+ }
145
+ }
146
+
147
+ // Phase 2: Now run quorum checks to find out which URLs are popular even to be shared.
148
+ // First, setup a locally cached quorum checker to eliminate multiple calls for the
149
+ // same URLs (e.g., if there are redirects).
150
+ const cachedQuorumChecker = new CachedQuorumChecker(this.quorumChecker);
151
+
152
+ // If the main URL does not meet quorum, we drop the whole message.
153
+ // An exception are pages that have been indexed by a public search engine;
154
+ // those are already public, so they should be safe to share.
155
+ const isIndexed = safePage.search && safePage.search.depth === 1;
156
+ if (
157
+ !isIndexed &&
158
+ !isPureDomain(url) &&
159
+ !(await cachedQuorumChecker.isQuorumReached(url))
160
+ ) {
161
+ logger.info('Dropping page', url, 'since it failed to reach quorum');
162
+ return null;
163
+ }
164
+
165
+ const protectUrlIfNeeded = async (url) => {
166
+ if (isPureDomain(url) || url === '...') {
167
+ return url;
168
+ }
169
+ if (await cachedQuorumChecker.isQuorumReached(url)) {
170
+ return url;
171
+ }
172
+ const parsedUrl = parsedUrls.get(url);
173
+ return `${parsedUrl.protocol}//${parsedUrl.hostname}/ (PROTECTED)`;
174
+ };
175
+
176
+ if (safePage.ref) {
177
+ safePage = { ...safePage };
178
+ safePage.ref = await protectUrlIfNeeded(safePage.ref);
179
+ }
180
+
181
+ const { redirects } = safePage;
182
+ if (redirects) {
183
+ safePage = { ...safePage };
184
+ safePage.redirects = await Promise.all(
185
+ redirects.map(async (redirect) => {
186
+ const from = await protectUrlIfNeeded(redirect.from);
187
+ const to = await protectUrlIfNeeded(redirect.to);
188
+ return {
189
+ from,
190
+ to,
191
+ statusCode: redirect.statusCode,
192
+ };
193
+ }),
194
+ );
195
+ }
196
+
197
+ const ctry = this.countryProvider.getSafeCountryCode();
198
+ return createPageMessage(safePage, ctry);
199
+ }
200
+ }
@@ -0,0 +1,136 @@
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
+ // Note: is expected to be used as input of chrome.scripting.executeScript.
13
+ // It must not depend on no external functions (only the DOM API is safe to use).
14
+ // Also, it should work on all supported browsers.
15
+ export async function analyzePageStructure(doc) {
16
+ function getTitle(doc) {
17
+ if (doc.title) {
18
+ return doc.title;
19
+ }
20
+ const elem = doc.querySelector('html > head > meta[name="title"]');
21
+ if (elem) {
22
+ return elem.getAttribute('content') || '';
23
+ }
24
+ return '';
25
+ }
26
+
27
+ function getCanonicalUrl(doc) {
28
+ const elem = doc.querySelector('html > head > link[rel="canonical"]');
29
+ return elem ? elem.href : null;
30
+ }
31
+
32
+ /**
33
+ * Parse the robots meta tag. By default, the standard treats pages
34
+ * do not opt-out ("noindex") as indexable. But explicitly opt-in
35
+ * (e.g. "index") may still be a clue that a page wants to be indexed.
36
+ */
37
+ function parseMetaRobotTags(doc) {
38
+ let requestedIndex = false;
39
+ for (const elem of doc.querySelectorAll(
40
+ 'html > head > meta[name="robots"]',
41
+ )) {
42
+ const attr = elem.getAttribute('content');
43
+ if (attr) {
44
+ const tags = attr.split(',').map((x) => x.trim());
45
+ if (tags.includes('noindex') || tags.includes('none')) {
46
+ return { noindex: true, requestedIndex: false };
47
+ }
48
+
49
+ // Detect some tags that typically are only added to websites
50
+ // that want to be found. The presence of such tags does not
51
+ // prove anything, but it increases the chance that a page
52
+ // is free of private information.
53
+ requestedIndex =
54
+ requestedIndex ||
55
+ tags.includes('all') ||
56
+ tags.includes('index') ||
57
+ tags.includes('index') ||
58
+ tags.includes('max-image-preview:large') ||
59
+ tags.includes('max-image-preview:standard') ||
60
+ tags.includes('max-video-preview:-1');
61
+ }
62
+ }
63
+ return { noindex: false, requestedIndex };
64
+ }
65
+
66
+ function sanitizeLanguage(lang) {
67
+ if (lang) {
68
+ const lang_ = lang.trim();
69
+ if (lang_.length <= 10) {
70
+ return lang_;
71
+ }
72
+ }
73
+ return null;
74
+ }
75
+
76
+ function parseHtmlLangAttribute(doc) {
77
+ return sanitizeLanguage(doc.documentElement.getAttribute('lang'));
78
+ }
79
+
80
+ function parseOpenGraphMetaTags(doc) {
81
+ const og = {};
82
+ for (const tag of ['title', 'url', 'image', 'video']) {
83
+ const elem = doc.querySelector(
84
+ `html > head > meta[property="og:${tag}"]`,
85
+ );
86
+ if (elem) {
87
+ const content = elem.getAttribute('content');
88
+ if (content) {
89
+ og[tag] = content;
90
+ }
91
+ }
92
+ }
93
+ return og;
94
+ }
95
+
96
+ doc = doc || document;
97
+
98
+ try {
99
+ const { noindex, requestedIndex } = parseMetaRobotTags(doc);
100
+ if (noindex) {
101
+ return {
102
+ noindex: true,
103
+ };
104
+ }
105
+
106
+ const title = getTitle(doc);
107
+ const url = doc.URL;
108
+
109
+ // Meta information (be aware that for single-page applications,
110
+ // these values can to be unreliable. After navigations, the
111
+ // canonical URL may become outdated.
112
+ const canonicalUrl = getCanonicalUrl(doc);
113
+ const contentType = doc.contentType || null;
114
+ const language = parseHtmlLangAttribute(doc);
115
+ const og = parseOpenGraphMetaTags(doc);
116
+
117
+ return {
118
+ title,
119
+ url,
120
+ meta: {
121
+ canonicalUrl,
122
+ language,
123
+ contentType,
124
+ og,
125
+ },
126
+ noindex: false,
127
+ requestedIndex,
128
+ };
129
+ } catch (e) {
130
+ return {
131
+ error: true,
132
+ details: (e.stack || e).toString(),
133
+ noindex: true,
134
+ };
135
+ }
136
+ }