fix(security): replace insecure Math.random with crypto.getRandomValues for fallback UUID generation

This commit is contained in:
diegosouzapw
2026-04-28 14:04:42 -03:00
parent ca0956d43b
commit f8a006fc1d

View File

@@ -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);
});
}