Browse Source

refactor: make getUniqId more random + use safe calls

tophf 5 years ago
parent
commit
b50e2552c9
2 changed files with 17 additions and 8 deletions
  1. 14 6
      src/common/util.js
  2. 3 2
      src/injected/utils/helpers.js

+ 14 - 6
src/common/util.js

@@ -1,5 +1,10 @@
 import { forEachEntry } from './object';
 
+// used in an unsafe context so we need to save the original functions
+const perfNow = performance.now.bind(performance);
+const { random, floor } = Math;
+export const { toString: numberToString } = Number.prototype;
+
 export function toString(param) {
   if (param == null) return '';
   return `${param}`;
@@ -28,17 +33,17 @@ export function debounce(func, time) {
   time = Math.max(0, +time || 0);
   function checkTime() {
     timer = null;
-    if (performance.now() >= startTime) callback();
+    if (perfNow() >= startTime) callback();
     else checkTimer();
   }
   function checkTimer() {
     if (!timer) {
-      const delta = startTime - performance.now();
+      const delta = startTime - perfNow();
       timer = setTimeout(checkTime, delta);
     }
   }
   function debouncedFunction(...args) {
-    startTime = performance.now() + time;
+    startTime = perfNow() + time;
     callback = () => {
       callback = null;
       func.apply(this, args);
@@ -52,7 +57,7 @@ export function throttle(func, time) {
   let lastTime = 0;
   time = Math.max(0, +time || 0);
   function throttledFunction(...args) {
-    const now = performance.now();
+    const now = perfNow();
     if (lastTime + time < now) {
       lastTime = now;
       func.apply(this, args);
@@ -67,8 +72,11 @@ export function getRnd4() {
   return Math.floor((1 + Math.random()) * 0x10000).toString(16).slice(-4);
 }
 
-export function getUniqId(prefix) {
-  return (prefix || '') + Date.now().toString(36) + getRnd4();
+export function getUniqId(prefix = 'VM') {
+  const now = perfNow();
+  return prefix
+    + floor((now - floor(now)) * 1e12)::numberToString(36)
+    + floor(random() * 1e12)::numberToString(36);
 }
 
 export function buffer2string(buf, offset = 0, length = 1e99) {

+ 3 - 2
src/injected/utils/helpers.js

@@ -1,4 +1,6 @@
-// cache native properties to avoid being overridden, see violentmonkey/violentmonkey#151
+// caching native properties to avoid being overridden, see violentmonkey/violentmonkey#151
+import { numberToString } from '#/common';
+
 // Firefox sucks: `isFinite` is not defined on `window`, see violentmonkey/violentmonkey#300
 // eslint-disable-next-line no-restricted-properties
 export const {
@@ -21,7 +23,6 @@ export const {
   charCodeAt, match, slice, replace,
 } = String.prototype;
 export const { toString: objectToString } = Object.prototype;
-const { toString: numberToString } = Number.prototype;
 export const { fromCharCode } = String;
 export const { addEventListener, removeEventListener } = EventTarget.prototype;
 export const { append, remove, setAttribute } = Element.prototype;