@whotracksme/reporting 7.12.3 → 8.0.1

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 (44) hide show
  1. package/.eslintignore +1 -0
  2. package/CHANGELOG.md +24 -0
  3. package/communication/test/helpers/in-memory-database.js +45 -0
  4. package/package.json +1 -1
  5. package/reporting/README.md +26 -0
  6. package/reporting/example/README.md +65 -0
  7. package/reporting/example/logs/.gitignore +2 -0
  8. package/reporting/example/run.mjs +288 -0
  9. package/reporting/karma.conf.cjs +3 -2
  10. package/reporting/package.json +8 -2
  11. package/reporting/rollup.common-config.cjs +7 -1
  12. package/reporting/scenarios/README.md +77 -0
  13. package/reporting/src/hash-detector-v2/index.js +164 -0
  14. package/reporting/src/hash-detector-v2/prob.js +599 -0
  15. package/reporting/src/hash-detector-v2.js +18 -0
  16. package/reporting/src/observable.js +43 -0
  17. package/reporting/src/pages.js +11 -12
  18. package/reporting/src/paused-domains-reporter.js +50 -0
  19. package/reporting/src/persisted-counters.js +158 -0
  20. package/reporting/src/popularity-estimator.js +625 -0
  21. package/reporting/src/popularity-vote-handler.js +219 -0
  22. package/reporting/src/popularity-vote-sanitizer.js +384 -0
  23. package/reporting/src/random.js +90 -1
  24. package/reporting/src/reporting.js +98 -13
  25. package/reporting/src/utils.js +41 -1
  26. package/reporting/test/README.md +42 -2
  27. package/reporting/test/activity-estimator.spec.js +3 -2
  28. package/reporting/test/alive-check.spec.js +2 -2
  29. package/reporting/test/country-provider.spec.js +2 -2
  30. package/reporting/test/helpers/scenarios.js +4 -1
  31. package/reporting/test/index.js +6 -0
  32. package/reporting/test/job-scheduler.spec.js +2 -2
  33. package/reporting/test/observable.spec.js +72 -0
  34. package/reporting/test/page-aggregator.spec.js +3 -0
  35. package/reporting/test/patterns-updater.spec.js +2 -2
  36. package/reporting/test/persisted-counters.spec.js +132 -0
  37. package/reporting/test/popularity-estimator.spec.js +710 -0
  38. package/reporting/test/popularity-vote-handler.spec.js +420 -0
  39. package/reporting/test/popularity-vote-sanitizer.spec.js +635 -0
  40. package/reporting/test/random.spec.js +157 -0
  41. package/reporting/test/reporting.spec.js +202 -180
  42. package/reporting/test/request/index.test.js +6 -2
  43. package/reporting/test/request.js +14 -0
  44. package/reporting/test/utils.spec.js +42 -0
@@ -0,0 +1,219 @@
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 { random32Bit } from './random';
14
+ import { requireParam, requireString } from './utils';
15
+ import { BadJobError } from './errors';
16
+
17
+ import { isLegalVoteCount } from './popularity-estimator';
18
+ import {
19
+ sanitizeHostname,
20
+ sanitizePathSegment,
21
+ } from './popularity-vote-sanitizer';
22
+
23
+ const SECOND = 1000;
24
+ const MINUTE = 60 * SECOND;
25
+
26
+ function throwBadJobError(text, job) {
27
+ const job_ = JSON.stringify(job, null, 2);
28
+ throw new BadJobError(`${text}\n--- begin job ---\n${job_}\n--- end job ---`);
29
+ }
30
+
31
+ /**
32
+ * Processes the results from the PopularityEstimator. These two classes are
33
+ * tightly coupled but with different responsibilities:
34
+ * 1) The PopularityEstimator does all the bookkeeping (all locally)
35
+ * - it counts visited websites
36
+ * - in fixed intervals, it picks samples to vote on (e.g. visited a domain)
37
+ * 2) The PopularityVoteHandler prepares the votes (includes network calls):
38
+ * - masking fields if necessary (using static checks, followed by a quorum request)
39
+ * - once a vote is ready, it triggers the actual message sending
40
+ */
41
+ export default class PopularityVoteHandler {
42
+ constructor({
43
+ jobScheduler,
44
+ communication,
45
+ quorumChecker,
46
+ countryProvider,
47
+ pauseState,
48
+ }) {
49
+ this.jobScheduler = requireParam(jobScheduler);
50
+ this.communication = requireParam(communication);
51
+ this.quorumChecker = requireParam(quorumChecker);
52
+ this.countryProvider = requireParam(countryProvider);
53
+ this.pauseState = pauseState; // optional
54
+
55
+ jobScheduler.registerHandler(
56
+ 'popularity-estimator:prepare-voting:v1',
57
+ async (job) => {
58
+ const { urlProjection, countType, intervalType, sample } = job.args;
59
+ const validate = (actual, allowed) => {
60
+ if (!allowed.includes(actual)) {
61
+ const options = `[${allowed.join(', ')}]`;
62
+ throwBadJobError(
63
+ `Job failed check ('${actual}' not in ${options})`,
64
+ job,
65
+ );
66
+ }
67
+ };
68
+ validate(urlProjection, ['domain', 'hostname', 'hostnamePath']);
69
+ validate(countType, ['visits']);
70
+ validate(intervalType, ['1d', '1w', '4w']);
71
+
72
+ // Validate the vote. First structurally ...
73
+ const unmaskedVote = sample?.value;
74
+ const numVotes = sample?.count;
75
+ if (typeof unmaskedVote !== 'string' || !Number.isInteger(numVotes)) {
76
+ throwBadJobError('Corrupted vote sample in job', job);
77
+ }
78
+
79
+ // ... but also logically. Protect against clients starting to send too many messages.
80
+ if (!isLegalVoteCount({ numVotes, intervalType })) {
81
+ throwBadJobError(
82
+ `Found too many votes in job (numVotes=${numVotes})`,
83
+ job,
84
+ );
85
+ }
86
+
87
+ const vote = await this.prepareVote(
88
+ urlProjection,
89
+ countType,
90
+ intervalType,
91
+ unmaskedVote,
92
+ );
93
+ logger.info('Vote ready:', `${numVotes}x for`, vote);
94
+
95
+ const sendVoteJob = {
96
+ type: 'popularity-estimator:send-vote:v1',
97
+ args: { vote },
98
+ config: {
99
+ readyIn: { min: 2 * SECOND, max: 20 * MINUTE },
100
+ },
101
+ };
102
+ return Array(numVotes).fill(sendVoteJob);
103
+ },
104
+ {
105
+ priority: -100, // preparing the vote can be delayed
106
+ maxJobsTotal: 100,
107
+ cooldownInMs: 4 * SECOND,
108
+ },
109
+ );
110
+
111
+ jobScheduler.registerHandler(
112
+ 'popularity-estimator:send-vote:v1',
113
+ async (job) => {
114
+ const { vote } = job.args;
115
+ if (!vote) {
116
+ throwBadJobError('Vote missing in job', job);
117
+ }
118
+
119
+ // It is important here that we send directly and not via the MessageSender.
120
+ // The MessageSender automatically deduplicates message. It most cases, this
121
+ // is want you want but not here. By design, votes can be duplicates;
122
+ // filtering them out would introduce bias.
123
+ await this.communication.send({
124
+ action: 'wtm.popularity',
125
+ payload: vote,
126
+ ver: 3, // Note: no need to keep this number in sync among messages
127
+ 'anti-duplicates': random32Bit(),
128
+ });
129
+ logger.info('Voted successfully for:', vote);
130
+ },
131
+ {
132
+ priority: 100, // prioritize sending the final message out
133
+ maxJobsTotal: 100,
134
+ cooldownInMs: 8 * SECOND,
135
+ },
136
+ );
137
+
138
+ // (exported for testing only)
139
+ this._sanitizeHostname = sanitizeHostname;
140
+ this._sanitizePathSegment = sanitizePathSegment;
141
+ }
142
+
143
+ async prepareVote(urlProjection, countType, intervalType, unmaskedVote) {
144
+ const { hostname: unsafeHostname, path: unsafePath } =
145
+ this._ensureThatVoteIsValid(urlProjection, unmaskedVote);
146
+
147
+ const hostname = sanitizeHostname(unsafeHostname);
148
+ const path = unsafePath.map(sanitizePathSegment);
149
+
150
+ let vote = [hostname, ...path].join('/');
151
+
152
+ // Prepare to include additional information from the adblocker if available.
153
+ let adblocker;
154
+ if (this.pauseState) {
155
+ adblocker = {
156
+ paused: this.pauseState.isHostnamePaused(unsafeHostname),
157
+ mode: this.pauseState.getFilteringMode(),
158
+ };
159
+ }
160
+
161
+ // At this point, the information in the vote should be safe to share.
162
+ // Run an additional quorum check to mask all votes that have not be
163
+ // shared by multiple clients.
164
+ await this.quorumChecker.sendQuorumIncrement({ text: vote });
165
+ const quorumReached = await this.quorumChecker.checkQuorumConsent({
166
+ text: vote,
167
+ });
168
+ if (!quorumReached) {
169
+ logger.info('Vote failed quorum. Discard value:', vote);
170
+ vote = '--';
171
+ }
172
+
173
+ const payload = {
174
+ type: {
175
+ urlProjection,
176
+ countType,
177
+ intervalType,
178
+ },
179
+ vote,
180
+ ctry: this.countryProvider.getSafeCountryCode(),
181
+ };
182
+ if (adblocker) {
183
+ payload.adblocker = adblocker;
184
+ }
185
+ return payload;
186
+ }
187
+
188
+ _ensureThatVoteIsValid(urlProjection, unmaskedVote) {
189
+ requireString(unmaskedVote);
190
+
191
+ switch (urlProjection) {
192
+ case 'domain':
193
+ case 'hostname':
194
+ return {
195
+ hostname: this._validateHostname(unmaskedVote),
196
+ path: [],
197
+ };
198
+ case 'hostnamePath': {
199
+ const [hostname, ...path] = unmaskedVote.split('/');
200
+ return {
201
+ hostname: this._validateHostname(hostname),
202
+ path,
203
+ };
204
+ }
205
+ default:
206
+ throw new BadJobError(
207
+ `Unexpected urlProjection type: ${urlProjection}`,
208
+ );
209
+ }
210
+ }
211
+
212
+ _validateHostname(hostname) {
213
+ const hostnameRegex = /^([a-zA-Z0-9-]+\.)*[a-zA-Z0-9-]+$/;
214
+ if (!hostnameRegex.test(hostname)) {
215
+ throw new BadJobError(`Invalid hostname: ${hostname}`);
216
+ }
217
+ return hostname;
218
+ }
219
+ }
@@ -0,0 +1,384 @@
1
+ /**
2
+ * WhoTracks.Me
3
+ * https://whotracks.me/
4
+ *
5
+ * Copyright 2017-present Ghostery GmbH. All rights reserved.
6
+ *
7
+ * This Source Code Form is subject to the terms of the Mozilla Public
8
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
9
+ * file, You can obtain one at http://mozilla.org/MPL/2.0
10
+ */
11
+
12
+ import * as tldts from 'tldts-experimental';
13
+
14
+ import logger from './logger';
15
+ import { includesMiddleChar } from './utils';
16
+ import { isHash } from './hash-detector-v2';
17
+
18
+ // Note that this cannot be part of a hostname or a URL path
19
+ // ('#' is not a valid character in hostnames and URL paths)
20
+ const MASKED = '#??#';
21
+
22
+ export function sanitizeHostname(hostname) {
23
+ const { domain } = tldts.parse(hostname, {
24
+ extractHostname: false,
25
+ mixedInputs: false,
26
+ validateHostname: false,
27
+ });
28
+ if (hostname === domain) {
29
+ return hostname;
30
+ }
31
+
32
+ return hostname
33
+ .split('.')
34
+ .map((part) => sanitizePart(part))
35
+ .join('.');
36
+ }
37
+
38
+ export function sanitizePathSegment(path) {
39
+ return sanitizePart(path);
40
+ }
41
+
42
+ // Protect against large URL path segments. First, they are in most cases
43
+ // degenerated cases that should not be shared. But it defends against
44
+ // performance regression, since our masking algorithm will perform O(n^2)
45
+ // hash checks. Since each hash detector check will likely have to look at
46
+ // all characters, we have already O(n^3) in the most optimistic scenario.
47
+ // There are URLs in the wild where the URL path segments exceed 1000 chars.
48
+ const MAX_TEXT_LENGTH = 128;
49
+
50
+ function ensureTextIsNotHuge(str) {
51
+ if (str.length > MAX_TEXT_LENGTH) {
52
+ throw new Error(
53
+ `Internal error: Long text should have been truncated before. Failed at text with ${str.length} > ${MAX_TEXT_LENGTH} characters: <<${str}>>`,
54
+ );
55
+ }
56
+ }
57
+
58
+ function sanitizePart(str) {
59
+ // By construction, this should never be reachable. By including this test,
60
+ // we have strong guarantees that we will never have to face it in.
61
+ if (str.includes(MASKED)) {
62
+ logger.warn(
63
+ `Found the reserved MASKED sequence (${MASKED}) in the input text: ${str}`,
64
+ );
65
+ return MASKED;
66
+ }
67
+
68
+ // First pass on the original text
69
+ const sanitized = sanitizePart__fixedButNotYetTruncated__(str);
70
+ if (sanitized === str) {
71
+ return str; // no sanitization needed ==> text is safe
72
+ }
73
+
74
+ // The original text was not accepted, but there can be false-positives
75
+ // if the text contains percent-encoded parts.
76
+ if (str.includes('%')) {
77
+ let decodedStr;
78
+ try {
79
+ decodedStr = decodeURIComponent(str);
80
+ if (decodedStr.includes(MASKED)) {
81
+ logger.warn(
82
+ 'Ignoring unlikely edge case where the reserved MASKED sequence was percent encoded:',
83
+ str,
84
+ );
85
+ decodedStr = undefined;
86
+ }
87
+ } catch {
88
+ // ignore (not well formed)
89
+ }
90
+ if (decodedStr !== undefined && decodedStr !== str) {
91
+ const decodedSanitized =
92
+ sanitizePart__fixedButNotYetTruncated__(decodedStr);
93
+ if (decodedSanitized === decodedStr) {
94
+ return str; // URL decoded text is safe ==> the original text is also safe
95
+ }
96
+
97
+ return backportMaskToOriginalText(str, decodedStr, decodedSanitized);
98
+ }
99
+ }
100
+
101
+ return sanitized;
102
+ }
103
+
104
+ // Phase 2: text is fixed, but not yet truncated.
105
+ function sanitizePart__fixedButNotYetTruncated__(str) {
106
+ if (str.length >= MAX_TEXT_LENGTH) {
107
+ const truncated = str.slice(0, MAX_TEXT_LENGTH - MASKED.length);
108
+ logger.debug('Truncating long text segment:', str, '->', truncated);
109
+ const sanitized = sanitizePart__fixedText__(truncated);
110
+ return sanitized.endsWith(MASKED) ? sanitized : sanitized + MASKED;
111
+ }
112
+
113
+ return sanitizePart__fixedText__(str);
114
+ }
115
+
116
+ // Phase 3 (final): text is fixed and truncated
117
+ function sanitizePart__fixedText__(str) {
118
+ ensureTextIsNotHuge(str);
119
+
120
+ if (shouldBeMasked(str)) {
121
+ return MASKED;
122
+ }
123
+
124
+ // Some sites keep searches or edited text in the URL. These are often
125
+ // '+' separated ("example.com/search/searching+for+foo+bar").
126
+ // Though there are false-positives, filtering out is most of the time
127
+ // the right thing to do.
128
+ if (str.length >= 12 && includesMiddleChar(str, '+')) {
129
+ return MASKED;
130
+ }
131
+
132
+ const { safePrefix, rest } = findSafePrefix(str);
133
+ return mergeMaskInterruptions(safePrefix + maskHashes(rest));
134
+ }
135
+
136
+ function findSafePrefix(str, maxWords = 10) {
137
+ if (maxWords <= 0) {
138
+ return { safePrefix: '', rest: str };
139
+ }
140
+
141
+ let i = 0;
142
+ while (i < str.length) {
143
+ const code = str.charCodeAt(i);
144
+ if (i > 0 && code === '-'.charCodeAt(0)) {
145
+ let { safePrefix: nextSafePrefix, rest } = findSafePrefix(
146
+ str.slice(i + 1),
147
+ maxWords - 1,
148
+ );
149
+ if (shouldBeMasked(nextSafePrefix)) {
150
+ nextSafePrefix = MASKED;
151
+ }
152
+ let thisSafePrefix = str.slice(0, i);
153
+ const text = thisSafePrefix.endsWith('-')
154
+ ? thisSafePrefix.slice(0, thisSafePrefix.length - 1)
155
+ : thisSafePrefix;
156
+ if (shouldBeMasked(text)) {
157
+ thisSafePrefix = MASKED;
158
+ }
159
+ const safePrefix = `${thisSafePrefix}-${nextSafePrefix}`;
160
+ return { safePrefix, rest };
161
+ }
162
+
163
+ if (
164
+ isAsciiLowerCase(code) ||
165
+ isGreekLowerCase(code) ||
166
+ isArabic(code) ||
167
+ isGeorgian(code) ||
168
+ isCyrillicLowerCase(code) ||
169
+ isArmenianLowerCase(code)
170
+ ) {
171
+ i += 1;
172
+ } else {
173
+ break;
174
+ }
175
+ }
176
+ return { safePrefix: '', rest: str };
177
+ }
178
+
179
+ const MIN_SIZE_TO_BE_MASKED = 8;
180
+ if (MASKED.length > MIN_SIZE_TO_BE_MASKED) {
181
+ throw new Error('Masking should never increase the length of the text');
182
+ }
183
+
184
+ function shouldBeMasked(str) {
185
+ if (str.length < MIN_SIZE_TO_BE_MASKED) {
186
+ return false;
187
+ }
188
+
189
+ // geo-coordinates (e.g. "@45.5335096,9.5914633,6z")
190
+ if (str.length >= 8 && str.match(/^@?[\d,.]+z?$/)) {
191
+ return true;
192
+ }
193
+
194
+ // look for identifiers, but first eliminate known false-positives
195
+ return !skipHashDetection(str) && isHash(str);
196
+ }
197
+
198
+ function maskHashes(str) {
199
+ ensureTextIsNotHuge(str);
200
+
201
+ for (let size = str.length; size >= MIN_SIZE_TO_BE_MASKED; size -= 1) {
202
+ for (let start = str.length - size; start >= 0; start -= 1) {
203
+ const substring = str.slice(start, start + size);
204
+ if (shouldBeMasked(substring)) {
205
+ let prefix = '';
206
+ if (start > 0) {
207
+ prefix = maskHashes(str.slice(0, start));
208
+ }
209
+
210
+ let postfix = '';
211
+ const beginPostfix = start + size;
212
+ if (beginPostfix < str.length) {
213
+ postfix = maskHashes(str.slice(beginPostfix));
214
+ }
215
+
216
+ const prefixMergable = prefix.endsWith(MASKED);
217
+ const postfixMergable = postfix.startsWith(MASKED);
218
+ if (prefixMergable && postfixMergable) {
219
+ return prefix + postfix.slice(MASKED.length);
220
+ }
221
+ if (prefixMergable || postfixMergable) {
222
+ return prefix + postfix;
223
+ }
224
+ return prefix + MASKED + postfix;
225
+ }
226
+ }
227
+ }
228
+
229
+ return str;
230
+ }
231
+
232
+ function mergeMaskInterruptions(str) {
233
+ const lastMatch = str.lastIndexOf(MASKED);
234
+ if (lastMatch === -1) {
235
+ return str;
236
+ }
237
+ if (str === MASKED) {
238
+ return MASKED;
239
+ }
240
+
241
+ const remainingCharsAfter = str.length - lastMatch - MASKED.length;
242
+ if (remainingCharsAfter > 0 && remainingCharsAfter <= 8) {
243
+ // aggressively cut text at the end after masked text
244
+ return mergeMaskInterruptions(
245
+ str.slice(0, str.length - remainingCharsAfter),
246
+ );
247
+ }
248
+
249
+ const prevMatch = str.lastIndexOf(MASKED, lastMatch - 1);
250
+ if (prevMatch === -1) {
251
+ return str;
252
+ }
253
+
254
+ const charsBetween = lastMatch - prevMatch - MASKED.length;
255
+ if (charsBetween <= 6) {
256
+ return mergeMaskInterruptions(str.slice(0, prevMatch + MASKED.length));
257
+ }
258
+ return str;
259
+ }
260
+
261
+ function isAsciiLowerCase(code) {
262
+ return code >= 97 && code <= 122; // a to z
263
+ }
264
+
265
+ function isGreekLowerCase(code) {
266
+ return code >= 0x03b1 && code <= 0x03c9; // α to ω
267
+ }
268
+
269
+ function isGeorgian(code) {
270
+ return code >= 0x10d0 && code <= 0x10ff; // ა to ჿ
271
+ }
272
+
273
+ function isArabic(code) {
274
+ return code >= 0x0600 && code <= 0x06ff;
275
+ }
276
+
277
+ function isCyrillicLowerCase(code) {
278
+ return (
279
+ (code >= 0x0430 && code <= 0x044f) || (code >= 0x0450 && code <= 0x045f)
280
+ );
281
+ }
282
+
283
+ function isArmenianLowerCase(code) {
284
+ return code >= 0x0561 && code <= 0x0587;
285
+ }
286
+
287
+ function skipHashDetection(str) {
288
+ const lowercaseWordDetectors = [
289
+ { matches: isAsciiLowerCase, threshold: 6 },
290
+ { matches: isGreekLowerCase, threshold: 3 },
291
+ { matches: isArabic, threshold: 3 },
292
+ { matches: isGeorgian, threshold: 3 },
293
+ { matches: isCyrillicLowerCase, threshold: 4 },
294
+ { matches: isArmenianLowerCase, threshold: 3 },
295
+ ];
296
+ lowercaseWordDetectors.forEach((x) => (x.current = 0));
297
+
298
+ for (let i = 0; i < str.length; i += 1) {
299
+ const code = str.charCodeAt(i);
300
+ for (const detector of lowercaseWordDetectors) {
301
+ if (detector.matches(code)) {
302
+ detector.current += 1;
303
+ if (detector.current >= detector.threshold) {
304
+ return true;
305
+ }
306
+ } else {
307
+ detector.current = 0;
308
+ }
309
+ }
310
+ }
311
+
312
+ return false;
313
+ }
314
+
315
+ // visible for testing
316
+ export function backportMaskToOriginalText(
317
+ originalText,
318
+ decodedText,
319
+ maskedDecodedText,
320
+ ) {
321
+ if (maskedDecodedText.length === 0) {
322
+ return '';
323
+ }
324
+
325
+ let nextMasked = maskedDecodedText.indexOf(MASKED);
326
+ if (nextMasked === -1) {
327
+ return originalText;
328
+ }
329
+
330
+ const matches = [];
331
+ let posOrig = 0; // originalText
332
+ let posDecoded = 0; // decodedText
333
+ let posMasked = 0; // maskedDecodedText
334
+
335
+ while (posMasked < maskedDecodedText.length) {
336
+ const decodedPart = maskedDecodedText.slice(posMasked, nextMasked);
337
+ const posDecodedMaskingBegins = posDecoded;
338
+ posDecoded = decodedText.indexOf(decodedPart, posDecoded);
339
+ if (posDecoded === -1) {
340
+ logger.error('[backportMaskToOriginalText] Failed for example:', {
341
+ originalText,
342
+ decodedText,
343
+ maskedDecodedText,
344
+ });
345
+ throw new Error('Illegal state: expected a match.');
346
+ }
347
+ if (
348
+ posDecoded > 0 &&
349
+ decodedText.indexOf(decodedPart, posDecoded + 1) !== -1
350
+ ) {
351
+ // Edge case: there are multiple candidates from which could continue.
352
+ // Be conservative and mask to the end.
353
+ const result = matches.join(MASKED) + MASKED;
354
+ logger.warn('Conservative matching hit:', {
355
+ originalText,
356
+ decodedText,
357
+ maskedDecodedText,
358
+ result,
359
+ });
360
+ return result;
361
+ }
362
+
363
+ const skipped = decodedText.slice(posDecodedMaskingBegins, posDecoded);
364
+ posOrig += encodeURIComponent(skipped).length;
365
+
366
+ const encodedPart = encodeURIComponent(decodedPart);
367
+ matches.push(originalText.slice(posOrig, posOrig + encodedPart.length));
368
+
369
+ posOrig += encodedPart.length;
370
+ posDecoded += decodedPart.length;
371
+ posMasked = nextMasked + MASKED.length;
372
+
373
+ nextMasked = maskedDecodedText.indexOf(MASKED, posMasked);
374
+ if (nextMasked === -1) {
375
+ const fromEnd = encodeURIComponent(
376
+ maskedDecodedText.slice(posMasked),
377
+ ).length;
378
+ matches.push(originalText.slice(originalText.length - fromEnd));
379
+ break; // end of text is masked
380
+ }
381
+ }
382
+
383
+ return matches.join(MASKED);
384
+ }
@@ -11,13 +11,39 @@
11
11
 
12
12
  /* eslint-disable no-bitwise */
13
13
 
14
+ // Random float in the interval [0, 1]
14
15
  export default function random() {
16
+ return random53Bit() / 2 ** 53;
17
+ }
18
+
19
+ // Random unsigned integer in the interval { 0, .., Number.MAX_SAFE_INTEGER }.
20
+ // In other words, a random unsigned 53-bit integer.
21
+ function random53Bit() {
15
22
  const values = crypto.getRandomValues(new Uint32Array(2));
16
- return (2 ** 32 * (values[0] & 0x1fffff) + values[1]) / 2 ** 53;
23
+ return 2 ** 32 * (values[0] & 0x1fffff) + values[1]; // 0x1fffff masks 21 bits (21 + 32 == 53)
24
+ }
25
+
26
+ // Random unsigned integer in the interval { 0, .., 2 ** 32 - 1 }
27
+ export function random32Bit() {
28
+ return crypto.getRandomValues(new Uint32Array(1))[0];
29
+ }
30
+
31
+ // Random unsigned integer in the interval { -Number.MAX_SAFE_INTEGER, .., Number.MAX_SAFE_INTEGER }
32
+ function randomSafeInteger() {
33
+ const values = crypto.getRandomValues(new Uint32Array(2));
34
+ const x = 2 ** 32 * (values[0] & 0x1fffff) + values[1]; // 0x1fffff masks 21 bits (21 + 32 == 53)
35
+ const positive = values[0] & (2 ** 22); // use bit 22 for the sign
36
+ if (x === 0 && !positive) {
37
+ // re-roll to avoid bias towards 0 (otherwise, we count it twice)
38
+ return randomSafeInteger();
39
+ }
40
+ return positive ? x : -x;
17
41
  }
18
42
 
19
43
  /**
20
44
  * Returns a floating point (not integer!) that lies between the boundaries.
45
+ *
46
+ * Hint: if you need an unbiased integer, use "randomSafeIntBetween".
21
47
  */
22
48
  export function randomBetween(minInclusive, maxInclusive) {
23
49
  if (!Number.isFinite(minInclusive)) {
@@ -37,3 +63,66 @@ export function randomBetween(minInclusive, maxInclusive) {
37
63
  }
38
64
  return minInclusive + random() * diff;
39
65
  }
66
+
67
+ /**
68
+ * Return an unbiased random integer that lies between the boundaries (both inclusive).
69
+ */
70
+ export function randomSafeIntBetween(minInclusive, maxInclusive) {
71
+ if (!Number.isSafeInteger(minInclusive)) {
72
+ throw new Error(`minInclusive=${minInclusive} must be a safe integer`);
73
+ }
74
+ if (!Number.isSafeInteger(maxInclusive)) {
75
+ throw new Error(`maxInclusive=${maxInclusive} must be a safe integer`);
76
+ }
77
+ if (maxInclusive < minInclusive) {
78
+ throw new Error(
79
+ `maxInclusive=${maxInclusive} must be at least minInclusive=${minInclusive}`,
80
+ );
81
+ }
82
+
83
+ const diff = maxInclusive - minInclusive;
84
+ if (diff === 0) {
85
+ return minInclusive;
86
+ }
87
+
88
+ if (Number.isSafeInteger(diff)) {
89
+ const fitsIn32Bit = diff < 2 ** 32;
90
+ const randGen = fitsIn32Bit ? random32Bit : random53Bit;
91
+
92
+ let nextPow2 = 1;
93
+ while (diff >= nextPow2) {
94
+ nextPow2 *= 2;
95
+ }
96
+
97
+ for (let attempts = 0; attempts < 1000; attempts += 1) {
98
+ const x = randGen() % nextPow2;
99
+ if (x <= diff) {
100
+ return minInclusive + x;
101
+ }
102
+ }
103
+ } else {
104
+ for (let attempts = 0; attempts < 1000; attempts += 1) {
105
+ const x = randomSafeInteger();
106
+ if (x >= minInclusive && x <= maxInclusive) {
107
+ return x;
108
+ }
109
+ }
110
+ }
111
+
112
+ // Since each pick had a chance of over 50 %, reaching this point should be
113
+ // practically impossible (less likely than losing 1000 coin flips in a row).
114
+ // Reaching it indicates that it is either a bug or the underlying random number
115
+ // generator (provided by the environment) is broken.
116
+ throw new Error(
117
+ `Internal error: unable to pick a random number between ${minInclusive} and ${maxInclusive}`,
118
+ );
119
+ }
120
+
121
+ // Fisher-Yates shuffle algorithm
122
+ export function shuffleInPlace(array) {
123
+ for (let i = array.length - 1; i > 0; i -= 1) {
124
+ const j = randomSafeIntBetween(0, i);
125
+ [array[i], array[j]] = [array[j], array[i]];
126
+ }
127
+ return array;
128
+ }