@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,140 @@
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 const PAGE_LOADING_STATE = {
13
+ CREATED: 'created',
14
+ NAVIGATING: 'navigating',
15
+ COMMITTED: 'committed',
16
+ COMPLETE: 'complete',
17
+ };
18
+
19
+ export default class Page {
20
+ constructor({ id, active, url, incognito, created }) {
21
+ this.id = id || 0;
22
+ this.url = url;
23
+ this.isRedirect = false;
24
+ this.isPrivate = incognito;
25
+ this.isPrivateServer = false;
26
+ this.created = created || Date.now();
27
+ this.destroyed = null;
28
+ this.lastRequestId = null;
29
+ this.frames = {
30
+ 0: {
31
+ parentFrameId: -1,
32
+ url,
33
+ },
34
+ };
35
+ this.state = PAGE_LOADING_STATE.CREATED;
36
+
37
+ this.activeTime = 0;
38
+ this.activeFrom = active ? Date.now() : 0;
39
+
40
+ this.requestStats = {};
41
+ this.annotations = {};
42
+ this.counter = 0;
43
+
44
+ this.tsv = '';
45
+ this.tsvId = undefined;
46
+ }
47
+
48
+ setActive(active) {
49
+ if (active && this.activeFrom === 0) {
50
+ this.activeFrom = Date.now();
51
+ } else if (!active && this.activeFrom > 0) {
52
+ this.activeTime += Date.now() - this.activeFrom;
53
+ this.activeFrom = 0;
54
+ }
55
+ }
56
+
57
+ updateState(newState) {
58
+ this.state = newState;
59
+ }
60
+
61
+ stage() {
62
+ this.setActive(false);
63
+ this.destroyed = Date.now();
64
+ // unset previous (to prevent history chain memory leak)
65
+ this.previous = undefined;
66
+ }
67
+
68
+ getStatsForDomain(domain) {
69
+ let stats = this.requestStats[domain];
70
+ if (!stats) {
71
+ stats = {};
72
+ this.requestStats[domain] = stats;
73
+ }
74
+ return stats;
75
+ }
76
+
77
+ setTrackingStatus(status) {
78
+ this.tsv = status.value;
79
+ this.tsvId = status.statusId;
80
+ }
81
+
82
+ getFrameAncestors({ parentFrameId }) {
83
+ const ancestors = [];
84
+
85
+ // Reconstruct frame ancestors
86
+ let currentFrameId = parentFrameId;
87
+ while (currentFrameId !== -1) {
88
+ const frame = this.frames[currentFrameId];
89
+
90
+ // If `frame` if undefined, this means we do not have any information
91
+ // about the frame associated with `currentFrameId`. This can happen if
92
+ // the event for `main_frame` or `sub_frame` was not emitted from the
93
+ // webRequest API for this frame; this can happen when Service Workers
94
+ // are used. In this case, we consider that the parent frame is the main
95
+ // frame (which is very likely the case).
96
+ if (frame === undefined) {
97
+ ancestors.push({
98
+ frameId: 0,
99
+ url: this.url,
100
+ });
101
+ break;
102
+ }
103
+
104
+ // Continue going up the ancestors chain
105
+ ancestors.push({
106
+ frameId: currentFrameId,
107
+ url: frame.url,
108
+ });
109
+ currentFrameId = frame.parentFrameId;
110
+ }
111
+
112
+ return ancestors;
113
+ }
114
+
115
+ /**
116
+ * Return the URL of top-level document (i.e.: tab URL).
117
+ */
118
+ getTabUrl() {
119
+ return this.url;
120
+ }
121
+
122
+ /**
123
+ * Return the URL of the frame.
124
+ */
125
+ getFrameUrl(context) {
126
+ const { frameId } = context;
127
+
128
+ const frame = this.frames[frameId];
129
+
130
+ // In some cases, frame creation does not trigger a webRequest event (e.g.:
131
+ // if the iframe is specified in the HTML of the page directly). In this
132
+ // case we try to fall-back to something else: documentUrl, originUrl,
133
+ // initiator.
134
+ if (frame === undefined) {
135
+ return context.documentUrl || context.originUrl || context.initiator;
136
+ }
137
+
138
+ return frame.url;
139
+ }
140
+ }
@@ -0,0 +1,249 @@
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
+
14
+ /**
15
+ * Handles a set of function pipelines. These pipelines start with an initial state
16
+ * and empty object return-value, then flow these arguments through the functions in
17
+ * the pipeline until one returns false.
18
+ *
19
+ * @class Pipeline
20
+ * @namespace antitracking
21
+ */
22
+ export default class Pipeline {
23
+ /**
24
+ * Pipeline constructor. Creates an empty pipeline with the default
25
+ * stages (open, modify and response).
26
+ */
27
+ constructor(name, steps = [], isBreakable = true) {
28
+ this.name = name;
29
+ this.isBreakable = isBreakable;
30
+ this.verboseLogging = false;
31
+
32
+ // Init empty pipeline
33
+ this.unload({ shallow: true });
34
+
35
+ this.addAll(steps);
36
+ }
37
+
38
+ get length() {
39
+ return this.pipeline.length;
40
+ }
41
+
42
+ unload() {
43
+ this.pipeline = [];
44
+ this.stepNames = new Set();
45
+ }
46
+
47
+ /**
48
+ * Bulk add functions to stages
49
+ * @param {Array.<Function>} fns
50
+ */
51
+ addAll(steps) {
52
+ for (let i = 0; i < steps.length; i += 1) {
53
+ this.addPipelineStep(steps[i]);
54
+ }
55
+ }
56
+
57
+ /**
58
+ * Adds a step to the pipeline with the given constraints.
59
+ *
60
+ * By default the step is placed at the end of the pipeline. If after or
61
+ * before are specified, the step is placed at the first available position
62
+ * which satisfies these constraints.
63
+ *
64
+ * @param {String} step.name The name of the function. Must be unique.
65
+ * @param {String} step.spec The kind of step: collect, break, blocking, annotate.
66
+ * @param {Function} options.fn The step function
67
+ * @param {Array.<String>} options.after Array of step names for which this step should be
68
+ * put afterwards
69
+ * @param {Array.<String>} options.before Array of step names for which this step should be
70
+ * put before
71
+ */
72
+ addPipelineStep(step) {
73
+ const { name, fn, after = [], before = [], spec } = step;
74
+
75
+ if (name === undefined) {
76
+ throw new Error(
77
+ `Every step of the pipeline should be given a name in ${this.name}`,
78
+ );
79
+ }
80
+
81
+ if (this.stepNames.has(name)) {
82
+ throw new Error(`Trying to overwrite existing ${this.name}.${name}`);
83
+ }
84
+
85
+ if (
86
+ spec !== 'annotate' &&
87
+ spec !== 'collect' &&
88
+ spec !== 'blocking' &&
89
+ spec !== 'break'
90
+ ) {
91
+ throw new Error(
92
+ `Every step of the pipeline should be given a valid spec (got ${spec}): ${this.name}.${name}`,
93
+ );
94
+ }
95
+
96
+ if (fn === undefined) {
97
+ throw new Error(
98
+ `Every step of the pipeline should have a function ('fn' argument): ${this.name}.${name}`,
99
+ );
100
+ }
101
+
102
+ if (spec === 'break' && !this.isBreakable) {
103
+ throw new Error(
104
+ `Cannot add a break step '${name}' to an unbreakable pipeline`,
105
+ );
106
+ }
107
+
108
+ this.stepNames.add(name);
109
+
110
+ const emptyPipeline = this.pipeline.length === 0;
111
+ const hasAfter = after.length > 0;
112
+ const hasBefore = before.length > 0;
113
+
114
+ if ((!hasAfter && !hasBefore) || emptyPipeline) {
115
+ // just put it at the end
116
+ this.pipeline.push(step);
117
+ } else if (hasAfter && !hasBefore) {
118
+ // Find the first index which is after any of the step names in `after`
119
+ let insertAt = -1;
120
+ for (let i = 0; i < this.pipeline.length; i += 1) {
121
+ if (after.indexOf(this.pipeline[i].name) !== -1) {
122
+ insertAt = i + 1;
123
+ }
124
+ }
125
+
126
+ if (insertAt === -1) {
127
+ throw new Error(
128
+ `no step from 'after' list found, after=${JSON.stringify(
129
+ after,
130
+ )}, pipeline=${this.name}`,
131
+ );
132
+ } else if (insertAt === this.pipeline.length) {
133
+ this.pipeline.push(step);
134
+ } else {
135
+ this.pipeline.splice(insertAt, 0, step);
136
+ }
137
+ } else if (hasBefore && !hasAfter) {
138
+ // Find the last index which is before any of the step names in `before`
139
+ let insertAt = -1;
140
+ for (let i = 0; i < this.pipeline.length; i += 1) {
141
+ if (before.indexOf(this.pipeline[i].name) !== -1) {
142
+ insertAt = i;
143
+ break;
144
+ }
145
+ }
146
+
147
+ if (insertAt === -1) {
148
+ this.pipeline.push(step);
149
+ } else {
150
+ this.pipeline.splice(insertAt, 0, step);
151
+ }
152
+ } else {
153
+ throw new Error('cannot take both before and after constraints');
154
+ }
155
+ }
156
+
157
+ /**
158
+ * Removes the given step name from the pipeline
159
+ * @param {String} name of the step
160
+ */
161
+ removePipelineStep(name) {
162
+ this.pipeline = this.pipeline.filter((step) => step.name !== name);
163
+ this.stepNames.delete(name);
164
+ }
165
+
166
+ /**
167
+ * Run pipeline on the given `webRequestContext`. The `response` argument can
168
+ * be altered by steps and will be used to generate the blocking response for
169
+ * the webrequest listener.
170
+ */
171
+ execute(webRequestContext, response, canAlterRequest = true) {
172
+ for (let i = 0; i < this.pipeline.length; i += 1) {
173
+ // Measure time elapsed while running this step
174
+ const { name, fn, spec } = this.pipeline[i];
175
+ let cont = true;
176
+
177
+ // Execute step
178
+ switch (spec) {
179
+ case 'break':
180
+ // A `break` step is usually used to disrupt the pipeline
181
+ // life-cycle. It does not have access to the response (cannot
182
+ // block/redirect/change headers) and shall not mutate the
183
+ // webRequestContext.
184
+ cont = fn(webRequestContext);
185
+ break;
186
+ case 'annotate':
187
+ // An `annotate` step is used to mutate/annotate the
188
+ // webRequestContext. For example it might be used to keep track of
189
+ // some information on the page-load (statistics about number of
190
+ // cookies blocked, etc.). It does not have access to the response
191
+ // (cannot block/redirect/change headers).
192
+ cont = fn(webRequestContext);
193
+ break;
194
+ case 'collect':
195
+ // A `collect` step is used to only observe the http life-cycle and
196
+ // is never used to alter it in any way. It does not have access to
197
+ // the response either. Because of these constraints, we can safely
198
+ // run these steps asynchronously to not block the processing of
199
+ // requests.
200
+ setTimeout(fn.bind(null, webRequestContext), 1);
201
+ break;
202
+ case 'blocking':
203
+ // A `blocking` step is used to alter the life-cycle of a request:
204
+ // blocking, redirecting, modifying headers. It can also mutate the
205
+ // webRequestContext, although it would be better to use an
206
+ // `annotate` step for this purpose.
207
+ //
208
+ // When `canAlterRequest` is `false`, blocking steps are ignored.
209
+ // This can be the case if a domain has been white-listed at the
210
+ // webrequest-pipeline level.
211
+ if (canAlterRequest === true) {
212
+ cont = fn(webRequestContext, response);
213
+ }
214
+ break;
215
+ default:
216
+ logger.error('Invalid spec for step', this.pipeline[i]);
217
+ break;
218
+ }
219
+
220
+ // Handle early termination of the pipeline. If a step returns `false` and
221
+ // this pipeline is allowed to be 'broken', then we ignore the remaining
222
+ // steps.
223
+ if (cont === false) {
224
+ if (this.isBreakable === true) {
225
+ if (this.verboseLogging) {
226
+ logger.debug(this.name, webRequestContext.url, 'Break at', name);
227
+ }
228
+ break;
229
+ }
230
+ // we only reach here if the pipeline is not breakable: show a warning
231
+ // that we ignored the break
232
+ logger.error(
233
+ this.name,
234
+ webRequestContext.url,
235
+ 'ignoring attempted break of unbreakable pipeline at',
236
+ name,
237
+ );
238
+ }
239
+ }
240
+ }
241
+
242
+ safeExecute(context, response, canAlterRequest) {
243
+ try {
244
+ this.execute(context, response, canAlterRequest);
245
+ } catch (ex) {
246
+ logger.error('while running pipeline', context, ex);
247
+ }
248
+ }
249
+ }
@@ -0,0 +1,113 @@
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
+
14
+ export const VALID_RESPONSE_PROPERTIES = {
15
+ onBeforeRequest: ['cancel', 'redirectUrl'],
16
+ onBeforeSendHeaders: ['cancel', 'requestHeaders'],
17
+ onHeadersReceived: ['cancel', 'redirectUrl', 'responseHeaders'],
18
+ onAuthRequired: ['cancel'],
19
+ onBeforeRedirect: [],
20
+ onCompleted: [],
21
+ onErrorOccurred: [],
22
+ };
23
+
24
+ const HAS_WEB_REQUEST_BLOCKING = chrome?.runtime
25
+ ?.getManifest()
26
+ ?.permissions.includes('webRequestBlocking');
27
+
28
+ function getOptionArray(options) {
29
+ if (!options) {
30
+ return [];
31
+ }
32
+ // get subset of options which are defined
33
+ const optionsSubset = [
34
+ // firefox and chrome disagree on how to name these
35
+ options.REQUEST_HEADERS || options.REQUESTHEADERS,
36
+ options.RESPONSE_HEADERS || options.RESPONSEHEADERS,
37
+ // extra headers: Chrome 72:
38
+ // https://groups.google.com/a/chromium.org/forum/#!topic/chromium-extensions/vYIaeezZwfQ
39
+ options.EXTRA_HEADERS,
40
+ // request body disabled to avoid the overhead when not needed
41
+ // options.REQUEST_BODY,
42
+ ];
43
+
44
+ if (HAS_WEB_REQUEST_BLOCKING) {
45
+ optionsSubset.push(options.BLOCKING);
46
+ }
47
+
48
+ return optionsSubset.filter((o) => !!o);
49
+ }
50
+
51
+ // build allowed extraInfo options from <Step>Options objects.
52
+ export const EXTRA_INFO_SPEC = {
53
+ onBeforeRequest: getOptionArray(chrome.webRequest.OnBeforeRequestOptions),
54
+ onBeforeSendHeaders: getOptionArray(
55
+ chrome.webRequest.OnBeforeSendHeadersOptions,
56
+ ),
57
+ onHeadersReceived: getOptionArray(chrome.webRequest.OnHeadersReceivedOptions),
58
+ onAuthRequired: getOptionArray(chrome.webRequest.OnAuthRequiredOptions),
59
+ onBeforeRedirect: getOptionArray(chrome.webRequest.OnBeforeRedirectOptions),
60
+ onCompleted: getOptionArray(chrome.webRequest.OnCompletedOptions),
61
+ onErrorOccurred: undefined,
62
+ };
63
+
64
+ const HANDLERS = {};
65
+ const urls = ['http://*/*', 'https://*/*'];
66
+
67
+ for (const event of Object.keys(EXTRA_INFO_SPEC)) {
68
+ // It might be that the platform does not support all listeners:
69
+ if (chrome.webRequest[event] === undefined) {
70
+ logger.warn(`chrome.webRequest.${event} is not supported`);
71
+ continue;
72
+ }
73
+
74
+ // Get allowed options for this event (e.g.: 'blocking', 'requestHeaders',
75
+ // etc.)
76
+ const extraInfoSpec = EXTRA_INFO_SPEC[event];
77
+
78
+ let firstCall = true;
79
+ const callback = (...args) => {
80
+ if (!HANDLERS[event]) {
81
+ if (firstCall) {
82
+ firstCall = false;
83
+ logger.info(
84
+ `webRequest.${event} called without listener being assigned`,
85
+ );
86
+ }
87
+ return;
88
+ }
89
+ return HANDLERS[event](...args);
90
+ };
91
+
92
+ if (extraInfoSpec === undefined) {
93
+ chrome.webRequest[event].addListener(callback, { urls });
94
+ } else {
95
+ chrome.webRequest[event].addListener(callback, { urls }, extraInfoSpec);
96
+ }
97
+ }
98
+
99
+ export function addListener(event, listener) {
100
+ if (HANDLERS[event]) {
101
+ throw new Error(
102
+ `webRequest.${event} expects only one listener as this all WebRequestPipeline should need`,
103
+ );
104
+ }
105
+ HANDLERS[event] = listener;
106
+ }
107
+
108
+ export function removeListener(event, listener) {
109
+ if (HANDLERS[event] !== listener) {
110
+ throw new Error(`webRequest.${event} trying to remove wrong listener`);
111
+ }
112
+ HANDLERS[event] = null;
113
+ }
@@ -0,0 +1,153 @@
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 { parse } from '../utils/url';
13
+ import logger from './logger';
14
+
15
+ /**
16
+ * Transform an array of headers (i.e.: `{ name, value }`) into a `Map`.
17
+ */
18
+ function createHeadersGetter(headers) {
19
+ const headersMap = new Map();
20
+
21
+ for (let i = 0; i < headers.length; i += 1) {
22
+ const { name, value } = headers[i];
23
+ headersMap.set(name.toLowerCase(), value);
24
+ }
25
+
26
+ return headersMap;
27
+ }
28
+
29
+ /**
30
+ * Wrap webRequest's details to provide convenient helpers.
31
+ */
32
+ export default class WebRequestContext {
33
+ /**
34
+ * "Smart" constructor for `WebRequestContext`. It will make sure that the same
35
+ * information is provided for different browsers (e.g.: Chrome and Firefox) as
36
+ * well as provide convenient helpers for parsed URLs, etc. It will also not
37
+ * return a wrapper for background requests.
38
+ */
39
+ static fromDetails(details, pageStore, event) {
40
+ const context = details;
41
+
42
+ // Check if we have a URL
43
+ if (!context.url) {
44
+ logger.log('Ignoring request with empty url', context);
45
+ return null;
46
+ }
47
+
48
+ // Main frames book keeping
49
+ if (context.type === 'main_frame') {
50
+ pageStore.onMainFrame(context, event);
51
+ }
52
+
53
+ // Sub frames book keeping
54
+ if (context.type === 'sub_frame') {
55
+ pageStore.onSubFrame(context);
56
+ }
57
+
58
+ // Get context on this page
59
+ const page = pageStore.getPageForRequest(context);
60
+
61
+ // **Chromium addition**
62
+ // frameAncestors
63
+ if (context.frameAncestors === undefined) {
64
+ context.frameAncestors = page ? page.getFrameAncestors(context) : [];
65
+ }
66
+
67
+ // Cliqz-specific extensions to webRequest details
68
+ context.page = page;
69
+ context.tabUrl = context.tabUrl || (page && page.getTabUrl());
70
+ context.frameUrl = context.frameUrl || (page && page.getFrameUrl(context));
71
+ context.isPrivate = page ? page.isPrivate : null;
72
+ context.isMainFrame = context.type === 'main_frame';
73
+ context.isRedirect = page && context.isMainFrame && page.isRedirect;
74
+
75
+ if (!context.tabUrl) {
76
+ context.tabUrl =
77
+ context.originUrl || context.initiator || context.documentUrl;
78
+ }
79
+
80
+ if (!context.frameUrl) {
81
+ context.frameUrl =
82
+ context.documentUrl || context.originUrl || context.initiator;
83
+ }
84
+
85
+ if (!context.originUrl) {
86
+ context.originUrl =
87
+ context.initiator ||
88
+ context.documentUrl ||
89
+ context.frameUrl ||
90
+ context.tabUrl;
91
+ }
92
+
93
+ return new WebRequestContext(context);
94
+ }
95
+
96
+ constructor(details) {
97
+ Object.assign(this, details);
98
+
99
+ // Lazy attributes
100
+ this._frameUrlParts = null;
101
+
102
+ this._requestHeadersMap = null;
103
+ this._responseHeadersMap = null;
104
+
105
+ this.urlParts = parse(this.url);
106
+ this.frameUrlParts = parse(this.frameUrl);
107
+ this.tabUrlParts = parse(this.tabUrl);
108
+ this.originUrlParts = parse(this.originUrl);
109
+ }
110
+
111
+ /**
112
+ * Optionally, a CNAME record can be requested from DNS for `this.url`. If
113
+ * available, it will be communicated by calling this method. We then set two
114
+ * new attributes on the WebRequestContext object so that users of the
115
+ * pipeline can access this information.
116
+ */
117
+ setCNAME(cname) {
118
+ this.cnameUrl = this.url.replace(this.urlParts.hostname, cname);
119
+ this.cnameUrlParts = parse(this.cnameUrl);
120
+ }
121
+
122
+ getRequestHeader(name) {
123
+ if (this._requestHeadersMap === null) {
124
+ this._requestHeadersMap = createHeadersGetter(this.requestHeaders || []);
125
+ }
126
+
127
+ return this._requestHeadersMap.get(name.toLowerCase());
128
+ }
129
+
130
+ getResponseHeader(name) {
131
+ if (this._responseHeadersMap === null) {
132
+ this._responseHeadersMap = createHeadersGetter(
133
+ this.responseHeaders || [],
134
+ );
135
+ }
136
+
137
+ return this._responseHeadersMap.get(name.toLowerCase());
138
+ }
139
+
140
+ getCookieData() {
141
+ return this.getRequestHeader('Cookie');
142
+ }
143
+
144
+ getReferrer() {
145
+ return this.getRequestHeader('Referer');
146
+ }
147
+
148
+ isBackgroundRequest() {
149
+ return (
150
+ this.tabId === -1 && this.originUrlParts?.protocol.endsWith('extension:')
151
+ );
152
+ }
153
+ }
@@ -0,0 +1,2 @@
1
+ Please add you spec to `index.js`.
2
+ We do that (instead of listing files in karma config) to generate a single bundle.