@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,345 @@
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 cyrb53 from './cyrb53';
14
+ import SeqExecutor from './seq-executor';
15
+
16
+ export function isNil(x) {
17
+ return x === undefined || x === null;
18
+ }
19
+
20
+ export function requireParam(x, name) {
21
+ if (isNil(x)) {
22
+ throw new Error(
23
+ name
24
+ ? `Required parameter "${name}" is missing`
25
+ : 'Required parameter is missing',
26
+ );
27
+ }
28
+ return x;
29
+ }
30
+
31
+ export function requireInt(value, name) {
32
+ if (!Number.isInteger(value)) {
33
+ throw new Error(
34
+ name
35
+ ? `${name} should be integer, but got: <${value}>`
36
+ : `Parameter should be integer, but got: <${value}>`,
37
+ );
38
+ }
39
+ return value;
40
+ }
41
+
42
+ export function requireIntOrNull(value, name) {
43
+ if (value !== null && !Number.isInteger(value)) {
44
+ throw new Error(
45
+ name
46
+ ? `${name} should be integer or null, but got: <${value}>`
47
+ : `Parameter should be integer or null, but got: <${value}>`,
48
+ );
49
+ }
50
+ return value;
51
+ }
52
+
53
+ export function requireString(value, name) {
54
+ if (typeof value !== 'string') {
55
+ throw new Error(
56
+ name
57
+ ? `${name} should be string, but got: <${value}>`
58
+ : `Parameter should be string, but got: <${value}>`,
59
+ );
60
+ }
61
+ return value;
62
+ }
63
+
64
+ export function requireStringOrNull(value, name) {
65
+ if (value !== null && typeof value !== 'string') {
66
+ throw new Error(
67
+ name
68
+ ? `${name} should be string or null, but got: <${value}>`
69
+ : `Parameter should be string or null, but got: <${value}>`,
70
+ );
71
+ }
72
+ return value;
73
+ }
74
+
75
+ export function requireArrayOfStrings(value, name) {
76
+ if (!Array.isArray(value)) {
77
+ throw new Error(
78
+ name
79
+ ? `${name} should be an array of strings, but got: ${value}`
80
+ : `Paramter should be an array of strings, but got: ${value}`,
81
+ );
82
+ }
83
+ value.forEach((x, idx) => {
84
+ if (typeof x !== 'string') {
85
+ throw new Error(
86
+ name
87
+ ? `${name} should be an array of string, but got: ${value} (stopped at pos #${idx}: ${x})`
88
+ : `Parameter should be an array of string, but got: ${value} (stopped at pos #${idx}: ${x})`,
89
+ );
90
+ }
91
+ });
92
+ return value;
93
+ }
94
+
95
+ export function requireBoolean(value, name) {
96
+ if (value !== true && value !== false) {
97
+ throw new Error(
98
+ name
99
+ ? `${name} should be boolean, but got: ${value}`
100
+ : `Parameter should be boolean, but got: ${value}`,
101
+ );
102
+ }
103
+ return value;
104
+ }
105
+
106
+ /**
107
+ * This is a narrow definition of object (i.e. something like {}).
108
+ */
109
+ export function requireObject(value, name) {
110
+ if (isNil(value) || Array.isArray(value) || typeof value !== 'object') {
111
+ throw new Error(
112
+ name
113
+ ? `${name} should be an object, but got: <${value}>`
114
+ : `Parameter should be an object, but got: <${value}>`,
115
+ );
116
+ }
117
+ return value;
118
+ }
119
+
120
+ // https://graphics.stanford.edu/~seander/bithacks.html#RoundUpPowerOf2
121
+ export function nextPow2(_v) {
122
+ let v = _v | 0;
123
+ v -= 1;
124
+ v |= v >> 1;
125
+ v |= v >> 2;
126
+ v |= v >> 4;
127
+ v |= v >> 8;
128
+ v |= v >> 16;
129
+ v += 1;
130
+ return v;
131
+ }
132
+
133
+ /**
134
+ * If you need cryptographically safe randomness, consider using
135
+ * randomBetween from './random.js'.
136
+ */
137
+ export function randBetween(min, max) {
138
+ return min + Math.random() * (max - min);
139
+ }
140
+
141
+ export function clamp({ min, max, value }) {
142
+ return Math.min(Math.max(min, value), max);
143
+ }
144
+
145
+ export function intersectMapKeys(map1, map2) {
146
+ const small = map1.size <= map2.size ? map1 : map2;
147
+ const big = map1.size <= map2.size ? map2 : map1;
148
+ return [...small.keys()].filter((x) => big.has(x));
149
+ }
150
+
151
+ // Hint: enable for better local debugging
152
+ //
153
+ // Normally, we store only hashes (often intentionally weakened) to give users
154
+ // limited protection if an attacker gets access to their profile (on their
155
+ // local machine). Yet for local development, preserving the original values
156
+ // as keys can be beneficial, since it makes inspecting the local state easier.
157
+ const USE_CLEARTEXT_HASHES_IF_POSSIBLE = false;
158
+ if (USE_CLEARTEXT_HASHES_IF_POSSIBLE) {
159
+ logger.error(
160
+ 'cleartext hashes enabled (should never be shown in a production profile!)',
161
+ );
162
+ }
163
+
164
+ /**
165
+ * A non-cryptographic hash function for strings.
166
+ *
167
+ * Limitations:
168
+ * - Expect the output space to be (at most) 53 bits.
169
+ * - Expect the implementation to change at any point, and use it only
170
+ * for hashes that are stored locally on the profile.
171
+ *
172
+ * Options:
173
+ * - seed: overwrites the seed (may be ignored)
174
+ * - truncate: weakens the hash to 32 bits to make collisions more likely
175
+ * - output: 'string', 'number', but by default unspecified
176
+ *
177
+ * If you require the output to string or number, you should set the
178
+ * output parameter. Otherwise, leave it empty, so that the implementation
179
+ * can chose (see USE_CLEARTEXT_HASHES_IF_POSSIBLE).
180
+ */
181
+ export function fastHash(str, { seed = 0, truncate = false, output } = {}) {
182
+ let hash = cyrb53(str, seed);
183
+ if (truncate) {
184
+ // converts to unsigned 32-bit
185
+ hash = (hash & 0xffffffff) >>> 0;
186
+ }
187
+ if (USE_CLEARTEXT_HASHES_IF_POSSIBLE) {
188
+ if (output !== 'number') {
189
+ return str;
190
+ }
191
+ // If the caller requires an integer, the trick to keep the original string
192
+ // does not work. Logging is the best that we can do to help debugging.
193
+ logger.debug('fastHash:', str, '->', hash);
194
+ }
195
+ if (output === 'string') {
196
+ // No particular reason to use base36 encoding. It makes the strings
197
+ // a bit smaller, but you can anything here (e.g. hash.toString()).
198
+ return hash.toString(36);
199
+ }
200
+ return hash;
201
+ }
202
+
203
+ /**
204
+ * Example: chunk([1, 2, 3, 4, 5], 3) ==> [[1, 2, 3], [4, 5]]
205
+ */
206
+ export function chunk(array, size) {
207
+ if (size <= 0) {
208
+ throw new Error(`Batch size must be strictly positive, but got ${size}`);
209
+ }
210
+ const result = [];
211
+ for (let i = 0; i < array.length; i += size) {
212
+ result.push(array.slice(i, i + Math.min(array.length - i, size)));
213
+ }
214
+ return result;
215
+ }
216
+
217
+ /**
218
+ * Example: flattenObject({ x: 1, y: { z: 2 } }) ==> [{ path: ['x'], value: 1 }, { path: ['y', 'z'], value: 2 }]
219
+ */
220
+ export function flattenObject(obj, parentPath = []) {
221
+ return Object.entries(obj).reduce((acc, [key, value]) => {
222
+ const path = [...parentPath, key];
223
+ if (typeof value === 'object' && value !== null) {
224
+ acc.push(...flattenObject(value, path));
225
+ } else {
226
+ acc.push({ path, value });
227
+ }
228
+ return acc;
229
+ }, []);
230
+ }
231
+
232
+ function sortedObjectEntries(x) {
233
+ return Object.entries(x).sort((a, b) => {
234
+ if (a[0] < b[0]) return -1;
235
+ if (a[0] > b[0]) return 1;
236
+ return 0;
237
+ });
238
+ }
239
+
240
+ /**
241
+ * This is not a full deepEqual implementation. But it should be
242
+ * able to detect common data objects with primitive types.
243
+ *
244
+ * If it returns true, you may assume that both inputs represent
245
+ * the same data.
246
+
247
+ * WARN: This implemenation will not detect identity in all situations;
248
+ * you may still get false for identical objects.
249
+ * If you need stronger guarantees, use a real deepEqual implementation.
250
+ *
251
+ * Note: the implementation assumes that objects are free of cycles
252
+ */
253
+ export function equalityCanBeProven(x, y) {
254
+ if (
255
+ x === true ||
256
+ x === false ||
257
+ x === null ||
258
+ x === undefined ||
259
+ typeof x === 'string' ||
260
+ Number.isFinite(x)
261
+ ) {
262
+ return x === y;
263
+ }
264
+ if (x.constructor === Date) {
265
+ return y?.constructor === Date && +x === +y;
266
+ }
267
+
268
+ if (Array.isArray(x)) {
269
+ if (!Array.isArray(y) || x.length !== y.length) {
270
+ return false;
271
+ }
272
+ for (let i = 0; i < x.length; i += 1) {
273
+ if (!equalityCanBeProven(x[i], y[i])) {
274
+ return false;
275
+ }
276
+ }
277
+ return true;
278
+ }
279
+
280
+ if (x.constructor === Object) {
281
+ if (y?.constructor !== Object) {
282
+ return false;
283
+ }
284
+ return (
285
+ y.constructor === Object &&
286
+ equalityCanBeProven(sortedObjectEntries(x), sortedObjectEntries(y))
287
+ );
288
+ }
289
+
290
+ // we failed to prove identity, but we did not prove inequality either
291
+ return false;
292
+ }
293
+
294
+ export function roundUpToNextUTCMidnight(unixEpoch) {
295
+ const date = new Date(unixEpoch);
296
+ date.setUTCHours(24, 0, 0, 0);
297
+ return date.getTime();
298
+ }
299
+
300
+ /**
301
+ * split0(str, on) === str.split(on)[0]
302
+ */
303
+ export function split0(str, on) {
304
+ const pos = str.indexOf(on);
305
+ return pos < 0 ? str : str.slice(0, pos);
306
+ }
307
+
308
+ /**
309
+ * Lazy initialized variables:
310
+ * - evaluated once at the first request
311
+ * - never evaluated more than once
312
+ * - never evaluated unless requested
313
+ *
314
+ * Usage:
315
+ * const fooProvider = lazyInitAsync(async () => 1 + 1);
316
+ * const foo = await fooProvider(); // foo === 2
317
+ *
318
+ * Warning: avoid cyclic dependencies in the initialization; otherwise,
319
+ * you risk deadlocks. The implementation will not attempt to detect it.
320
+ */
321
+ export function lazyInitAsync(func) {
322
+ const criticalSection = new SeqExecutor();
323
+ let isFirstCall = true;
324
+ let initFailed = false;
325
+ let value;
326
+ let error;
327
+
328
+ return () => {
329
+ return criticalSection.run(async () => {
330
+ if (isFirstCall) {
331
+ try {
332
+ value = await func();
333
+ } catch (e) {
334
+ initFailed = true;
335
+ error = e;
336
+ }
337
+ isFirstCall = false;
338
+ }
339
+ if (initFailed) {
340
+ throw error;
341
+ }
342
+ return value;
343
+ });
344
+ };
345
+ }
@@ -0,0 +1,110 @@
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 ChromeStorageMap from '../request/utils/chrome-storage-map';
14
+
15
+ function checkUserAgent(pattern) {
16
+ return navigator.userAgent.indexOf(pattern) !== -1;
17
+ }
18
+
19
+ const isFirefox = checkUserAgent('Firefox');
20
+
21
+ async function withTimeout(promise, timeoutInMs) {
22
+ let timer;
23
+ try {
24
+ timer = new Promise((_, reject) => {
25
+ setTimeout(
26
+ () =>
27
+ reject(new Error(`Timed out after ${timeoutInMs / 1000} seconds`)),
28
+ timeoutInMs,
29
+ );
30
+ });
31
+ return await Promise.race([promise, timer]);
32
+ } finally {
33
+ clearTimeout(timer);
34
+ }
35
+ }
36
+
37
+ /**
38
+ * CNAME un-cloaking only works in Firefox and if `dns` API is available.
39
+ */
40
+ export function isCnameUncloakSupported(browser) {
41
+ return (
42
+ // Async webRequest only available in Firefox
43
+ isFirefox &&
44
+ // Feature discovery of `browser.dns.resolve(...)`
45
+ browser &&
46
+ browser.dns &&
47
+ browser.dns.resolve
48
+ );
49
+ }
50
+
51
+ export default class CnameUnloak {
52
+ /**
53
+ * @param {function} dnsResolve dns.resolve WebExtension API (Firefox)
54
+ */
55
+ constructor(dnsResolve, dnsTTL = 10 * 60 * 1000 /* 10 minutes */) {
56
+ this.dnsResolve = dnsResolve;
57
+ this.dnsCache = new ChromeStorageMap({
58
+ storageKey: 'wtm-request-reporting:webrequest-pipeline:dns-cache',
59
+ ttlInMs: dnsTTL,
60
+ });
61
+ this.dnsPending = new Map();
62
+ this.dnsTTL = dnsTTL;
63
+ }
64
+
65
+ unload() {}
66
+
67
+ /**
68
+ * Resolve CNAME for `hostname`.
69
+ */
70
+ resolveCNAME(hostname) {
71
+ // This means we already have a cached CNAME for this hostname.
72
+ const cached = this.dnsCache.get(hostname);
73
+ if (cached !== undefined && Date.now() - cached.ts <= this.dnsTTL) {
74
+ logger.debug('[cname] cached', { hostname, cname: cached.cname });
75
+ return cached.cname;
76
+ }
77
+
78
+ // This means we already have a request on-going for this hostname.
79
+ const pending = this.dnsPending.get(hostname);
80
+ if (pending !== undefined) {
81
+ logger.debug('[cname] pending', hostname);
82
+ return pending;
83
+ }
84
+
85
+ // Request CNAME from DNS for `hostname` with timeout of 2 seconds. We
86
+ // assume that 2 seconds should be enough to get an answer in all cases but
87
+ // we do not want to risk blocking the webRequest callback for too long.
88
+ const dnsRequest = withTimeout(
89
+ this.dnsResolve(hostname, ['canonical_name']),
90
+ 2000,
91
+ )
92
+ .catch((ex) => {
93
+ logger.error('[cname] error while resolving', hostname, ex);
94
+ return { canonicalName: '' };
95
+ })
96
+ .then(({ canonicalName = '' } = {}) => {
97
+ const cname = canonicalName === hostname ? '' : canonicalName;
98
+ logger.debug('[cname] got record', cname);
99
+ this.dnsCache.set(hostname, {
100
+ cname,
101
+ ts: Date.now(),
102
+ });
103
+ this.dnsPending.delete(hostname);
104
+ return cname;
105
+ });
106
+
107
+ this.dnsPending.set(hostname, dnsRequest);
108
+ return dnsRequest;
109
+ }
110
+ }