11import { BacktraceAttributeProvider , IdGenerator } from '@backtrace/sdk-core' ;
22import { execSync } from 'child_process' ;
3+ import crypto from 'crypto' ;
4+
5+ const UUID_REGEX = / ^ [ a - f 0 - 9 ] { 8 } - [ a - f 0 - 9 ] { 4 } - [ a - f 0 - 9 ] { 4 } - [ a - f 0 - 9 ] { 4 } - [ a - f 0 - 9 ] { 12 } $ / i;
6+ const DASHLESS_UUID_REGEX = / ^ [ a - f 0 - 9 ] { 32 } $ / i;
37
48export class MachineIdentitfierAttributeProvider implements BacktraceAttributeProvider {
59 public static readonly SUPPORTED_PLATFORMS = [ 'win32' , 'darwin' , 'linux' , 'freebsd' ] ;
@@ -15,15 +19,21 @@ export class MachineIdentitfierAttributeProvider implements BacktraceAttributePr
1519 public get type ( ) : 'scoped' | 'dynamic' {
1620 return 'scoped' ;
1721 }
22+
1823 public get ( ) : Record < string , unknown > {
19- const guid = this . generateGuid ( ) ?? IdGenerator . uuid ( ) ;
24+ let machineId = this . getMachineId ( ) ;
25+ if ( machineId ) {
26+ machineId = this . getValidGuid ( machineId ) ;
27+ } else {
28+ machineId = IdGenerator . uuid ( ) ;
29+ }
2030
2131 return {
22- [ this . MACHINE_ID_ATTRIBUTE ] : guid ,
32+ [ this . MACHINE_ID_ATTRIBUTE ] : machineId ,
2333 } ;
2434 }
2535
26- public generateGuid ( ) {
36+ public getMachineId ( ) {
2737 switch ( process . platform ) {
2838 case 'win32' : {
2939 return execSync ( this . COMMANDS [ 'win32' ] )
@@ -51,4 +61,21 @@ export class MachineIdentitfierAttributeProvider implements BacktraceAttributePr
5161 }
5262 }
5363 }
64+
65+ private getValidGuid ( input : string ) {
66+ if ( input . length === 36 && UUID_REGEX . test ( input ) ) {
67+ return input ;
68+ }
69+
70+ if ( input . length === 32 && DASHLESS_UUID_REGEX . test ( input ) ) {
71+ return this . addDashesToUuid ( input ) ;
72+ }
73+
74+ const sha = crypto . createHash ( 'sha1' ) . update ( input ) . digest ( 'hex' ) . substring ( 0 , 32 ) ;
75+ return this . addDashesToUuid ( sha ) ;
76+ }
77+
78+ private addDashesToUuid ( uuid : string ) {
79+ return `${ uuid . substring ( 0 , 8 ) } -${ uuid . substring ( 8 , 12 ) } -${ uuid . substring ( 12 , 16 ) } -${ uuid . substring ( 16 , 20 ) } -${ uuid . substring ( 20 , 32 ) } ` ;
80+ }
5481}
0 commit comments