summaryrefslogtreecommitdiffstats
path: root/src/js/utils.js
blob: 10729353164879a4e54b7d060781e27624772717 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
/*
 * This file is part of Privacy Badger <https://www.eff.org/privacybadger>
 * Copyright (C) 2014 Electronic Frontier Foundation
 *
 * Derived from Adblock Plus
 * Copyright (C) 2006-2013 Eyeo GmbH
 *
 * Privacy Badger is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License version 3 as
 * published by the Free Software Foundation.
 *
 * Privacy Badger is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with Privacy Badger.  If not, see <http://www.gnu.org/licenses/>.
 */

/* globals URI:false */

require.scopes.utils = (function() {

let mdfp = require("multiDomainFP");

/**
 * Generic interface to make an XHR request
 *
 * @param {String} url The url to get
 * @param {Function} callback The callback to call after request has finished
 * @param {String} method GET/POST
 * @param {Object} opts XMLHttpRequest options
 */
function xhrRequest(url, callback, method, opts) {
  if (!method) {
    method = "GET";
  }
  if (!opts) {
    opts = {};
  }

  let xhr = new XMLHttpRequest();

  for (let key in opts) {
    if (opts.hasOwnProperty(key)) {
      xhr[key] = opts[key];
    }
  }

  xhr.onload = function () {
    if (xhr.status == 200) {
      callback(null, xhr.response);
    } else {
      let error = {
        status: xhr.status,
        message: xhr.response,
        object: xhr
      };
      callback(error, error.message);
    }
  };

  // triggered by network problems
  xhr.onerror = function () {
    callback({ status: 0, message: "", object: xhr }, "");
  };

  xhr.open(method, url, true);
  xhr.send();
}

/**
 * Converts binary data to base64-encoded text suitable for use in data URIs.
 *
 * Adapted from https://stackoverflow.com/a/9458996.
 *
 * @param {ArrayBuffer} buffer binary data
 *
 * @returns {String} base64-encoded text
 */
function arrayBufferToBase64(buffer) {
  var binary = '';
  var bytes = new Uint8Array(buffer);
  var len = bytes.byteLength;
  for (var i = 0; i < len; i++) {
    binary += String.fromCharCode(bytes[i]);
  }
  return btoa(binary);
}

/**
 * Return an array of all subdomains in an FQDN, ordered from the FQDN to the
 * eTLD+1. e.g. [a.b.eff.org, b.eff.org, eff.org]
 * if 'all' is passed in then the array will include all domain levels, not
 * just down to the base domain
 * @param {String} fqdn the domain to split
 * @param {boolean} all whether to include all domain levels
 * @returns {Array} the subdomains
 */
function explodeSubdomains(fqdn, all) {
  var baseDomain;
  if (all) {
    baseDomain = fqdn.split('.').pop();
  } else {
    baseDomain = window.getBaseDomain(fqdn);
  }
  var baseLen = baseDomain.split('.').length;
  var parts = fqdn.split('.');
  var numLoops = parts.length - baseLen;
  var subdomains = [];
  for (var i=0; i<=numLoops; i++) {
    subdomains.push(parts.slice(i).join('.'));
  }
  return subdomains;
}

/*
 * Estimates the max possible entropy of string.
 *
 * @param {String} str the string to compute entropy for
 * @returns {Integer} bits of entropy
 */
function estimateMaxEntropy(str) {
  // Don't process strings longer than MAX_LS_LEN_FOR_ENTROPY_EST.
  // Note that default quota for local storage is 5MB and
  // storing fonts, scripts or images in for local storage for
  // performance is not uncommon. We wouldn't want to estimate entropy
  // for 5M chars.
  const MAX_LS_LEN_FOR_ENTROPY_EST = 256;

  // common classes of characters that a string might belong to
  const SEPS = "._-x";
  const BIN = "01";
  const DEC = "0123456789";

  // these classes are case-insensitive
  const HEX = "abcdef" + DEC;
  const ALPHA = "abcdefghijklmnopqrstuvwxyz";
  const ALPHANUM = ALPHA + DEC;

  // these classes are case-sensitive
  const B64 = ALPHANUM + ALPHA.toUpperCase() + "/+";
  const URL = ALPHANUM + ALPHA.toUpperCase() + "~%";

  if (str.length > MAX_LS_LEN_FOR_ENTROPY_EST) {
    // Just return a higher-than-threshold entropy estimate.
    // We assume 1 bit per char, which will be well over the
    // threshold (33 bits).
    return str.length;
  }

  let max_symbols;

  // If all characters are upper or lower case, don't consider case when
  // computing entropy.
  let sameCase = (str.toLowerCase() == str) || (str.toUpperCase() == str);
  if (sameCase) {
    str = str.toLowerCase();
  }

  // If all the characters come from one of these common character groups,
  // assume that the group is the domain of possible characters.
  for (let chr_class of [BIN, DEC, HEX, ALPHA, ALPHANUM, B64, URL]) {
    let group = chr_class + SEPS;
    // Ignore separator characters when computing entropy. For example, Google
    // Analytics IDs look like "14103492.1964907".

    // flag to check if each character of input string belongs to the group in question
    let each_char_in_group = true;

    for (let ch of str) {
      if (!group.includes(ch)) {
        each_char_in_group = false;
        break;
      }
    }

    // if the flag resolves to true, we've found our culprit and can break out of the loop
    if (each_char_in_group) {
      max_symbols = chr_class.length;
      break;
    }
  }

  // If there's not an obvious class of characters, use the heuristic
  // "max char code - min char code"
  if (!max_symbols) {
    let charCodes = Array.prototype.map.call(str, function (ch) {
      return String.prototype.charCodeAt.apply(ch);
    });
    let min_char_code = Math.min.apply(Math, charCodes);
    let max_char_code = Math.max.apply(Math, charCodes);
    max_symbols = max_char_code - min_char_code + 1;
  }

  // the entropy is (entropy per character) * (number of characters)
  let max_bits = (Math.log(max_symbols) / Math.LN2) * str.length;

  return max_bits;
}

function oneSecond() {
  return 1000;
}

function oneMinute() {
  return oneSecond() * 60;
}

function oneHour() {
  return oneMinute() * 60;
}

function oneDay() {
  return oneHour() * 24;
}

function nDaysFromNow(n) {
  return Date.now() + (oneDay() * n);
}

function oneDayFromNow() {
  return nDaysFromNow(1);
}

/**
 * Creates a rate-limited function that delays invoking `fn` until after
 * `interval` milliseconds have elapsed since the last time the rate-limited
 * function was invoked.
 *
 * Does not drop invocations (lossless), unlike `_.throttle`.
 *
 * Adapted from
 * http://stackoverflow.com/questions/23072815/throttle-javascript-function-calls-but-with-queuing-dont-discard-calls
 *
 * @param {Function} fn The function to rate-limit.
 * @param {number} interval The number of milliseconds to rate-limit invocations to.
 * @param {Object} context The context object (optional).
 * @returns {Function} Returns the new rate-limited function.
 */
function rateLimit(fn, interval, context) {
  let canInvoke = true,
    queue = [],
    timer_id,
    limited = function () {
      queue.push({
        context: context || this,
        arguments: Array.prototype.slice.call(arguments)
      });
      if (canInvoke) {
        canInvoke = false;
        timeEnd();
      }
    };

  function timeEnd() {
    let item;
    if (queue.length) {
      item = queue.splice(0, 1)[0];
      fn.apply(item.context, item.arguments); // invoke fn
      timer_id = window.setTimeout(timeEnd, interval);
    } else {
      canInvoke = true;
    }
  }

  // useful for debugging
  limited.cancel = function () {
    window.clearTimeout(timer_id);
    queue = [];
    canInvoke = true;
  };

  return limited;
}

function buf2hex(buffer) { // buffer is an ArrayBuffer
  return Array.prototype.map.call(new Uint8Array(buffer), x => ('00' + x.toString(16)).slice(-2)).join('');
}

function sha1(input, callback) {
  return window.crypto.subtle.digest(
    { name: "SHA-1", },
    new TextEncoder().encode(input)
  ).then(hashed => {
    return callback(buf2hex(hashed));
  });
}

function parseCookie(str, opts) {
  if (!str) {
    return {};
  }

  opts = opts || {};

  let COOKIE_ATTRIBUTES = [
    "domain",
    "expires",
    "httponly",
    "max-age",
    "path",
    "samesite",
    "secure",
  ];

  let parsed = {},
    cookies = str.replace(/\n/g, ";").split(";");

  for (let i = 0; i < cookies.length; i++) {
    let cookie = cookies[i],
      name,
      value,
      cut = cookie.indexOf("=");

    // it's a key=value pair
    if (cut != -1) {
      name = cookie.slice(0, cut).trim();
      value = cookie.slice(cut + 1).trim();

      // handle value quoting
      if (value[0] == '"') {
        value = value.slice(1, -1);
      }

    // not a key=value pair
    } else {
      if (opts.skipNonValues) {
        continue;
      }
      name = cookie.trim();
      value = "";
    }

    if (opts.skipAttributes &&
        COOKIE_ATTRIBUTES.indexOf(name.toLowerCase()) != -1) {
      continue;
    }

    if (!opts.noDecode) {
      let decode = opts.decode || decodeURIComponent;
      try {
        name = decode(name);
      } catch (e) {
        // invalid URL encoding probably (URIError: URI malformed)
        if (opts.skipInvalid) {
          continue;
        }
      }
      if (value) {
        try {
          value = decode(value);
        } catch (e) {
          // ditto
          if (opts.skipInvalid) {
            continue;
          }
        }
      }
    }

    if (!opts.noOverwrite || !parsed.hasOwnProperty(name)) {
      parsed[name] = value;
    }
  }

  return parsed;
}

function getHostFromDomainInput(input) {
  if (!input.startsWith("http")) {
    input = "http://" + input;
  }

  if (!input.endsWith("/")) {
    input += "/";
  }

  try {
    var uri = new URI(input);
  } catch (err) {
    return false;
  }

  return uri.host;
}

/**
 * check if a domain is third party
 * @param {String} domain1 an fqdn
 * @param {String} domain2 a second fqdn
 *
 * @return {Boolean} true if the domains are third party
 */
function isThirdPartyDomain(domain1, domain2) {
  if (window.isThirdParty(domain1, domain2)) {
    return !mdfp.isMultiDomainFirstParty(
      window.getBaseDomain(domain1),
      window.getBaseDomain(domain2)
    );
  }
  return false;
}


/**
 * Checks whether a given URL is a special browser page.
 * TODO account for browser-specific pages:
 * https://github.com/hackademix/noscript/blob/a8b35486571933043bb62e90076436dff2a34cd2/src/lib/restricted.js
 *
 * @param {String} url
 *
 * @return {Boolean} whether the URL is restricted
 */
function isRestrictedUrl(url) {
  // permitted schemes from
  // https://developer.chrome.com/extensions/match_patterns
  return !(
    url.startsWith('http') || url.startsWith('file') || url.startsWith('ftp')
  );
}

/************************************** exports */
let exports = {
  arrayBufferToBase64,
  estimateMaxEntropy,
  explodeSubdomains,
  getHostFromDomainInput,
  isRestrictedUrl,
  isThirdPartyDomain,
  nDaysFromNow,
  oneDay,
  oneDayFromNow,
  oneHour,
  oneMinute,
  oneSecond,
  parseCookie,
  rateLimit,
  sha1,
  xhrRequest,
};
return exports;
/************************************** exports */
})(); //require scopes