@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,142 @@
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 { requireParam, requireString, lazyInitAsync } from './utils';
14
+
15
+ /**
16
+ * Responsible for generating information to be included in the "alive" message.
17
+ * The purpose of the additional information in the alive message is to detect
18
+ * unusual traffic, for instance, if a new browser version introduced a regression.
19
+ *
20
+ * The information will only be included if it has been seen by multiple users.
21
+ * The data itself should not be sensitive, still there is no point in including it
22
+ * as only "big hitters" are interesting. For instance, should there be a problem in
23
+ * an obscure setup, it is less interesting then if a recent Firefox or Chrome release
24
+ * breaks something on Windows.
25
+ */
26
+ export default class AliveMessageGenerator {
27
+ constructor({ browserInfoProvider, quorumChecker, storage, storageKey }) {
28
+ requireParam(browserInfoProvider);
29
+ this.quorumChecker = requireParam(quorumChecker);
30
+ this.storage = requireParam(storage);
31
+ this.storageKey = requireString(storageKey);
32
+
33
+ this.staticConfigProvider = lazyInitAsync(async () =>
34
+ this._generateBaseConfig(await browserInfoProvider()),
35
+ );
36
+ }
37
+
38
+ async generateMessage(ctry, hour) {
39
+ const config = {
40
+ ...(await this.staticConfigProvider()),
41
+ ctry,
42
+ };
43
+
44
+ try {
45
+ const reachedQuorum = await this._reachedQuorum(config);
46
+ if (reachedQuorum) {
47
+ config.t = hour;
48
+ logger.debug(
49
+ 'Found the following configuration safe to share:',
50
+ config,
51
+ );
52
+ return config;
53
+ }
54
+ logger.debug('Omitting the config, as it is not popular enough:', config);
55
+ } catch (e) {
56
+ logger.warn(
57
+ 'Failed to confirm that the configuration is popular enough:',
58
+ config,
59
+ e,
60
+ );
61
+ }
62
+
63
+ return {
64
+ browser: '',
65
+ version: '',
66
+ os: '',
67
+ language: '',
68
+ ctry: '--',
69
+ t: hour,
70
+ };
71
+ }
72
+
73
+ _generateBaseConfig(browserInfo) {
74
+ // extracts only the major version (e.g. "96.0.1" -> 96)
75
+ let version = parseInt(browserInfo.version, 10);
76
+ if (isNaN(version)) {
77
+ version = '';
78
+ } else {
79
+ version = String(version);
80
+ }
81
+
82
+ let language;
83
+ try {
84
+ language = navigator.language;
85
+ } catch (e) {
86
+ logger.warn(
87
+ 'Failed to access the "navigator" (should only happen when run in NodeJs)',
88
+ );
89
+ }
90
+ language = language || '';
91
+
92
+ return {
93
+ browser: browserInfo.browser || '',
94
+ version, // major version
95
+ os: browserInfo.os || '',
96
+ language: language || '', // e.g. 'en-US'
97
+ };
98
+ }
99
+
100
+ /**
101
+ * Checks that the additional configuration is popular enough to be shared.
102
+ * As long as the configuration does not change, keep the initial result of the
103
+ * quorum check. Otherwise, it might happen that it reaches quorum over time
104
+ * by itself (provided that we keep sharing it and it never changes).
105
+ *
106
+ * If there is a false positive (a popular config being not detected), it will
107
+ * eventually recover as the configuration will changed over time (e.g. after each
108
+ * browser update).
109
+ */
110
+ async _reachedQuorum(config) {
111
+ const newConfig = this._deterministicStringify(config);
112
+ let reachedQuorum = null;
113
+
114
+ try {
115
+ const oldValue = await this.storage.get(this.storageKey);
116
+ if (oldValue && newConfig === oldValue.config) {
117
+ reachedQuorum = oldValue.reachedQuorum;
118
+ }
119
+ } catch (e) {
120
+ logger.warn(
121
+ 'Ignore errors when reading the old state, but check the quorum again',
122
+ e,
123
+ );
124
+ }
125
+
126
+ if (reachedQuorum === null) {
127
+ await this.quorumChecker.sendQuorumIncrement({ text: newConfig });
128
+ reachedQuorum = await this.quorumChecker.checkQuorumConsent({
129
+ text: newConfig,
130
+ });
131
+ await this.storage.set(this.storageKey, {
132
+ config: newConfig,
133
+ reachedQuorum,
134
+ });
135
+ }
136
+ return reachedQuorum;
137
+ }
138
+
139
+ _deterministicStringify(obj) {
140
+ return JSON.stringify(Object.fromEntries(Object.entries(obj).sort()));
141
+ }
142
+ }
@@ -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 { fastHash } from './utils';
14
+ import PersistedBitarray from './persisted-bitarray';
15
+ import SelfCheck from './self-check';
16
+
17
+ const SECOND = 1000;
18
+ const MINUTE = 60 * SECOND;
19
+ const HOUR = 60 * MINUTE;
20
+ const DAY = 24 * HOUR;
21
+ const MONTH = 30 * DAY;
22
+
23
+ function gcd(a, b) {
24
+ return b === 0 ? a : gcd(b, a % b);
25
+ }
26
+
27
+ function allPairwiseRelativePrime(values) {
28
+ for (let i = 0; i < values.length; i += 1) {
29
+ for (let j = i + 1; j < values.length; j += 1) {
30
+ if (gcd(values[i], values[j]) !== 1) {
31
+ return false;
32
+ }
33
+ }
34
+ }
35
+ return true;
36
+ }
37
+
38
+ /**
39
+ * A bloom filter that is persisted.
40
+ *
41
+ * The implementation is bases on a "One-Hashing Bloom Filter"
42
+ * (see https://yangtonghome.github.io/uploads/One_Hashing.pdf).
43
+ * It uses only one hashing function, but splits the array in multiple partitions.
44
+ * The length of the partitions are expected to be pairwise relatively prime.
45
+ * That means, their gcd must be 1. For instance, you can take different prime numbers
46
+ * (https://gist.github.com/philipp-classen/318c870eb848b84548448eb4b80eed55).
47
+ *
48
+ * In OHBF, the number of partitions is comparable to "k" (the number of
49
+ * hashing functions) in a standard bloom filter and similar trade-offs apply.
50
+ */
51
+ export class BloomFilter {
52
+ constructor({
53
+ database,
54
+ name,
55
+ prefix = '',
56
+ version = 1,
57
+ partitions,
58
+ maxGenerations = 2,
59
+ rotationIntervalInMs = 3 * MONTH,
60
+ }) {
61
+ if (partitions.length === 0 || partitions.some((x) => x <= 0)) {
62
+ throw new Error('Partitions must be all non-empty and greater than zero');
63
+ }
64
+ this.partitions = partitions;
65
+ this.totalSize = partitions.reduce((x, y) => x + y);
66
+ this.db = database;
67
+
68
+ if (!name) {
69
+ throw new Error('Expected a name');
70
+ }
71
+ if (name.includes('|')) {
72
+ throw new Error(
73
+ `name=${name} it must not include the separator character |`,
74
+ );
75
+ }
76
+ this.name = name;
77
+
78
+ // bf|<name>|<version>|<generation>|<shard>
79
+ this.version = `v${version}`;
80
+ if (this.version.includes('|')) {
81
+ throw new Error(
82
+ `version=${this.version} it must not include the separator character |`,
83
+ );
84
+ }
85
+ this.keyPrefix = `${prefix}bf|${name}|`;
86
+ this.keyPrefixWithVersion = `${this.keyPrefix}${this.version}|`;
87
+
88
+ // rotation settings
89
+ if (maxGenerations <= 0) {
90
+ throw new Error(
91
+ `At least one generation is needed (got: ${maxGenerations})`,
92
+ );
93
+ }
94
+ if (rotationIntervalInMs < 0) {
95
+ throw new Error(
96
+ `Rotation interval must not be negative (got: ${rotationIntervalInMs})`,
97
+ );
98
+ }
99
+ if (maxGenerations > 1 && rotationIntervalInMs === 0) {
100
+ throw new Error(
101
+ 'Rotations can only be disabled if you also set one generation',
102
+ );
103
+ }
104
+ this.maxGenerations = maxGenerations;
105
+ this.rotationIntervalInMs = rotationIntervalInMs;
106
+
107
+ const logPrefix = `[bf=<${name}>]`;
108
+ this._debug = logger.debug.bind(logger.debug, logPrefix);
109
+ this._info = logger.info.bind(logger.info, logPrefix);
110
+ this._warn = logger.warn.bind(logger.warn, logPrefix);
111
+ this._error = logger.error.bind(logger.error, logPrefix);
112
+ }
113
+
114
+ _isOurKey(key) {
115
+ return key.startsWith(this.keyPrefix);
116
+ }
117
+
118
+ _isKeyFromCurrentVersion(key) {
119
+ return key.startsWith(this.keyPrefixWithVersion);
120
+ }
121
+
122
+ async ready(now = Date.now()) {
123
+ if (!this._ready) {
124
+ this._ready = (async () => {
125
+ // First, load all keys and detect keys that are own by the bloom filter.
126
+ // All keys that start with the prefix will be own by the bloom filter. Since the
127
+ // prefix includes its name, collisions should be unlikely. Yet it is still
128
+ // recommended to create separate databases to eliminate all potential clashes
129
+ // and to simplify the cleanup of obsolete values.
130
+ //
131
+ // Valid keys (owned by the bloom filter) have to follow this naming fconvention:
132
+ // <bf|<name>|<version>|<generation>|<shard>
133
+ //
134
+ // where
135
+ // <prefix>: "bf|<name>|<version>"
136
+ // <generation>: a Unix epoch (corresponding to the creation date)
137
+ // <shard>: unspecified (internal to the persisted bitarray)
138
+ const allKeys = await this.db.keys();
139
+ const keysByGen = new Map();
140
+ const obsoleteKeys = [];
141
+ const corruptedKeys = [];
142
+ const unknownKeys = [];
143
+
144
+ // Partition keys into:
145
+ // 1) valid keys (owned by us); group by generation
146
+ // 2) obsolete keys (owned by us but from old version)
147
+ // 3) corrupted keys (owned by us but invalid)
148
+ // 4) unknown (not owned by us)
149
+ for (const key of allKeys) {
150
+ if (this._isKeyFromCurrentVersion(key)) {
151
+ const [genString, shard] = key
152
+ .slice(this.keyPrefixWithVersion.length)
153
+ .split('|');
154
+ if (genString && shard) {
155
+ const gen = Number.parseInt(genString, 10);
156
+ if (gen > 0) {
157
+ const entry = keysByGen.get(gen);
158
+ if (entry) {
159
+ entry.push(key);
160
+ } else {
161
+ keysByGen.set(gen, [key]);
162
+ }
163
+ continue; // valid key
164
+ }
165
+ }
166
+ corruptedKeys.push(key);
167
+ } else if (this._isOurKey(key)) {
168
+ obsoleteKeys.push(key);
169
+ } else {
170
+ unknownKeys.push(key);
171
+ }
172
+ }
173
+
174
+ // Clean up obsolete and corrupted keys
175
+ const pendingCleanups = [];
176
+ if (corruptedKeys.length + obsoleteKeys.length > 0) {
177
+ if (corruptedKeys.length > 0) {
178
+ this._warn(
179
+ corruptedKeys.length,
180
+ 'corrupted keys found (will be deleted):',
181
+ corruptedKeys,
182
+ );
183
+ }
184
+ if (obsoleteKeys.length > 0) {
185
+ this._info(
186
+ obsoleteKeys.length,
187
+ 'keys from old version found (will be deleted):',
188
+ obsoleteKeys,
189
+ );
190
+ }
191
+ pendingCleanups.push(async () => {
192
+ try {
193
+ await Promise.all(
194
+ [...corruptedKeys, ...obsoleteKeys].map((key) =>
195
+ this.db.delete(key),
196
+ ),
197
+ );
198
+ this._info('Successfully cleaned up keys');
199
+ } catch (e) {
200
+ this._warn('Failed to cleanup keys', e);
201
+ }
202
+ });
203
+ }
204
+
205
+ // The presence of keys that are owned by us is not neccesarily a problem,
206
+ // although it is recommended to use a separate databases for each bloom filter.
207
+ // Doing that should fix the warning (or if you still get errors, it is an
208
+ // indicator that there is a bug in the persistence).
209
+ if (unknownKeys.length > 0) {
210
+ this._warn(
211
+ unknownKeys.length,
212
+ 'unknown keys found (use a dedicated database per bloom filter)',
213
+ );
214
+ this._debug('List of unknown keys:', unknownKeys);
215
+ }
216
+
217
+ const gensToDelete = [];
218
+ const currentGens = [...keysByGen.keys()].sort((x, y) => x - y);
219
+ if (currentGens.length === 0) {
220
+ this._debug('No existing generations found');
221
+ }
222
+
223
+ // remove everything that has a creation date far in the future
224
+ const isTooNew = (ts) => ts > now + 2 * this.rotationIntervalInMs;
225
+ while (
226
+ currentGens.length > 0 &&
227
+ isTooNew(currentGens[currentGens.length - 1])
228
+ ) {
229
+ const newestGen = currentGens.pop();
230
+ gensToDelete.push(newestGen);
231
+ this._warn(
232
+ 'Clock jump detected: purging corrupted generation:',
233
+ newestGen,
234
+ );
235
+ }
236
+
237
+ // if we use rotations, first remove generations that should be rotated out by age
238
+ if (this.maxGenerations > 1) {
239
+ const isTooOld = (ts) =>
240
+ ts < now - this.rotationIntervalInMs * this.maxGenerations;
241
+ while (currentGens.size > 0 && isTooOld(currentGens[0])) {
242
+ const oldestGen = currentGens.shift();
243
+ gensToDelete.push(oldestGen);
244
+ this._info('detected old generation:', oldestGen);
245
+ }
246
+ }
247
+
248
+ if (
249
+ currentGens.length === 0 ||
250
+ (this.maxGenerations > 1 &&
251
+ currentGens[currentGens.length - 1] <
252
+ now - this.rotationIntervalInMs)
253
+ ) {
254
+ this._info('Start new generation:', now);
255
+ currentGens.push(now);
256
+ }
257
+
258
+ const rotatedOut = currentGens.splice(
259
+ 0,
260
+ currentGens.length - this.maxGenerations,
261
+ );
262
+ if (rotatedOut.length > 0) {
263
+ this._info('Rotated out the following generations:', rotatedOut);
264
+ gensToDelete.push(...rotatedOut);
265
+ }
266
+
267
+ for (const gen of gensToDelete) {
268
+ pendingCleanups.push(async () => {
269
+ this._info('Deleting generation', gen);
270
+ const keys = keysByGen.get(gen);
271
+ try {
272
+ await Promise.all(keys.map((key) => this.db.delete(key)));
273
+ this._info(
274
+ `Generation ${gen} successfully deleted (${keys.length} keys in total)`,
275
+ );
276
+ } catch (e) {
277
+ this._warn('Failed to delete keys from generation', gen, e);
278
+ }
279
+ });
280
+ }
281
+ await Promise.all(pendingCleanups);
282
+
283
+ this.generations = currentGens.map(
284
+ (gen) =>
285
+ new PersistedBitarray({
286
+ database: this.db,
287
+ size: this.totalSize,
288
+ prefix: `${this.keyPrefixWithVersion}${gen}|`,
289
+ name: `bf=<${this.name}:${gen}}>`,
290
+ }),
291
+ );
292
+ })();
293
+ }
294
+ await this._ready;
295
+ }
296
+
297
+ async add(value) {
298
+ await this.ready();
299
+
300
+ const latestGeneration = this.generations[this.generations.length - 1];
301
+ const bitsToSet = this._computeBits(value);
302
+ await latestGeneration.setMany(bitsToSet);
303
+ }
304
+
305
+ async mightContain(value, { updateTTLIfFound = false } = {}) {
306
+ await this.ready();
307
+
308
+ const bitsToTest = this._computeBits(value);
309
+ for (let i = this.generations.length - 1; i >= 0; i -= 1) {
310
+ const generation = this.generations[i];
311
+ const found = await generation.testMany(bitsToTest);
312
+ if (found && updateTTLIfFound && i !== this.generations.length - 1) {
313
+ const latestGeneration = this.generations[this.generations.length - 1];
314
+ await latestGeneration.setMany(bitsToTest);
315
+ return true;
316
+ }
317
+ }
318
+ return false;
319
+ }
320
+
321
+ _computeBits(value) {
322
+ const hash = fastHash(value, { output: 'number' });
323
+ let offset = 0;
324
+ return this.partitions.map((partitionSize) => {
325
+ const posInPartition = hash % partitionSize;
326
+ const index = offset + posInPartition;
327
+ offset += partitionSize;
328
+ return index;
329
+ });
330
+ }
331
+
332
+ async selfChecks(check = new SelfCheck()) {
333
+ if (!allPairwiseRelativePrime(this.partitions)) {
334
+ check.warn('partitions should be pairwise relative prime', {
335
+ partitions: this.partitions,
336
+ });
337
+ }
338
+ if (this.generations) {
339
+ await Promise.all(
340
+ this.generations.map((gen) => gen.selfChecks(check.for(gen.name))),
341
+ );
342
+ }
343
+ return check;
344
+ }
345
+ }