import { networkInterfaces } from 'os'; import { createHash, randomBytes } from 'crypto'; /** * Check to see if the input is a valid JSON string * * @param {*} str The string to check for valud JSON * @returns {true|false} */ export function isJsonString (str) { try { JSON.parse(str); } catch (e) { return false; } return true; } /** * Generate a unique ID for a given device, this will also be unique on the same device at a different time. * @returns {string} A generated unique ID */ export function generateUniqueID () { const netInterfaces = networkInterfaces(); let macAddress = ''; // Find the first non-internal MAC address for (const key in netInterfaces) { const iface = netInterfaces[key][0]; if (!iface.internal) { macAddress = iface.mac; break; } } // If no non-internal MAC address is found, fallback to a random value if (!macAddress) { macAddress = randomBytes(6).toString('hex').toUpperCase(); } // Use MAC address and current timestamp to create a unique ID const timestamp = Date.now(); const uniqueID = createHash('sha256') .update(macAddress + timestamp) .digest('hex'); return uniqueID; }