From f8a006fc1d25ddbd86a707f4fb85c435b79faab4 Mon Sep 17 00:00:00 2001 From: diegosouzapw Date: Tue, 28 Apr 2026 14:04:42 -0300 Subject: [PATCH] fix(security): replace insecure Math.random with crypto.getRandomValues for fallback UUID generation --- src/shared/utils/machineId.ts | 36 +++++++++++++++++++++++++++++++---- 1 file changed, 32 insertions(+), 4 deletions(-) diff --git a/src/shared/utils/machineId.ts b/src/shared/utils/machineId.ts index 2033f61967..710d791a1f 100644 --- a/src/shared/utils/machineId.ts +++ b/src/shared/utils/machineId.ts @@ -117,9 +117,23 @@ export async function getConsistentMachineId(salt = null) { const cryptoFallback = await import("crypto"); return cryptoFallback.randomUUID(); } catch { + if (typeof globalThis !== "undefined" && globalThis.crypto && globalThis.crypto.randomUUID) { + return globalThis.crypto.randomUUID(); + } return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, function (c) { - const r = (Math.random() * 16) | 0; - const v = c == "x" ? r : (r & 0x3) | 0x8; + let r = 0; + if ( + typeof globalThis !== "undefined" && + globalThis.crypto && + globalThis.crypto.getRandomValues + ) { + const arr = new Uint8Array(1); + globalThis.crypto.getRandomValues(arr); + r = arr[0] % 16; + } else { + r = (Date.now() % 16) | 0; + } + const v = c === "x" ? r : (r & 0x3) | 0x8; return v.toString(16); }); } @@ -140,9 +154,23 @@ export async function getRawMachineId() { const cryptoFallback = await import("crypto"); return cryptoFallback.randomUUID(); } catch { + if (typeof globalThis !== "undefined" && globalThis.crypto && globalThis.crypto.randomUUID) { + return globalThis.crypto.randomUUID(); + } return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, function (c) { - const r = (Math.random() * 16) | 0; - const v = c == "x" ? r : (r & 0x3) | 0x8; + let r = 0; + if ( + typeof globalThis !== "undefined" && + globalThis.crypto && + globalThis.crypto.getRandomValues + ) { + const arr = new Uint8Array(1); + globalThis.crypto.getRandomValues(arr); + r = arr[0] % 16; + } else { + r = (Date.now() % 16) | 0; + } + const v = c === "x" ? r : (r & 0x3) | 0x8; return v.toString(16); }); }