|
1 |
| -import { machineIdSync } from "node-machine-id"; |
| 1 | +// modified from https://github.com/automation-stack/node-machine-id |
| 2 | + |
| 3 | +import { execSync } from 'child_process'; |
| 4 | +import { createHash } from 'crypto'; |
2 | 5 | import { v4 as uuid } from 'uuid';
|
3 | 6 |
|
| 7 | +const { platform } = process; |
| 8 | +const win32RegBinPath = { |
| 9 | + native: '%windir%\\System32', |
| 10 | + mixed: '%windir%\\sysnative\\cmd.exe /c %windir%\\System32', |
| 11 | +}; |
| 12 | +const guid = { |
| 13 | + darwin: 'ioreg -rd1 -c IOPlatformExpertDevice', |
| 14 | + win32: |
| 15 | + `${win32RegBinPath[isWindowsProcessMixedOrNativeArchitecture()]}\\REG.exe ` + |
| 16 | + 'QUERY HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Cryptography ' + |
| 17 | + '/v MachineGuid', |
| 18 | + linux: '( cat /var/lib/dbus/machine-id /etc/machine-id 2> /dev/null || hostname 2> /dev/null) | head -n 1 || :', |
| 19 | + freebsd: 'kenv -q smbios.system.uuid || sysctl -n kern.hostuuid', |
| 20 | +}; |
| 21 | + |
| 22 | +function isWindowsProcessMixedOrNativeArchitecture() { |
| 23 | + // eslint-disable-next-line no-prototype-builtins |
| 24 | + if (process.arch === 'ia32' && process.env.hasOwnProperty('PROCESSOR_ARCHITEW6432')) { |
| 25 | + return 'mixed'; |
| 26 | + } |
| 27 | + return 'native'; |
| 28 | +} |
| 29 | + |
| 30 | +function hash(guid: string): string { |
| 31 | + return createHash('sha256').update(guid).digest('hex'); |
| 32 | +} |
| 33 | + |
| 34 | +function expose(result: string): string { |
| 35 | + switch (platform) { |
| 36 | + case 'darwin': |
| 37 | + return result |
| 38 | + .split('IOPlatformUUID')[1] |
| 39 | + .split('\n')[0] |
| 40 | + .replace(/=|\s+|"/gi, '') |
| 41 | + .toLowerCase(); |
| 42 | + case 'win32': |
| 43 | + return result |
| 44 | + .toString() |
| 45 | + .split('REG_SZ')[1] |
| 46 | + .replace(/\r+|\n+|\s+/gi, '') |
| 47 | + .toLowerCase(); |
| 48 | + case 'linux': |
| 49 | + return result |
| 50 | + .toString() |
| 51 | + .replace(/\r+|\n+|\s+/gi, '') |
| 52 | + .toLowerCase(); |
| 53 | + case 'freebsd': |
| 54 | + return result |
| 55 | + .toString() |
| 56 | + .replace(/\r+|\n+|\s+/gi, '') |
| 57 | + .toLowerCase(); |
| 58 | + default: |
| 59 | + throw new Error(`Unsupported platform: ${process.platform}`); |
| 60 | + } |
| 61 | +} |
| 62 | + |
4 | 63 | export function getMachineId() {
|
5 |
| - // machineIdSync() is not compatible with non-shell hosts such as Vercel |
| 64 | + if (!(platform in guid)) { |
| 65 | + return uuid(); |
| 66 | + } |
6 | 67 | try {
|
7 |
| - return machineIdSync(); |
| 68 | + const value = execSync(guid[platform as keyof typeof guid]); |
| 69 | + const id = expose(value.toString()); |
| 70 | + return hash(id); |
8 | 71 | } catch {
|
9 | 72 | return uuid();
|
10 | 73 | }
|
|
0 commit comments