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,21 +19,24 @@ 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' : {
29- return execSync ( this . COMMANDS [ 'win32' ] )
30- . toString ( )
31- . match ( / [ 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) ?. [ 0 ]
32- . toLowerCase ( ) ;
39+ return execSync ( this . COMMANDS [ 'win32' ] ) . toString ( ) . match ( UUID_REGEX ) ?. [ 0 ] . toLowerCase ( ) ;
3340 }
3441 case 'darwin' : {
3542 return execSync ( this . COMMANDS [ process . platform ] )
@@ -51,4 +58,21 @@ export class MachineIdentitfierAttributeProvider implements BacktraceAttributePr
5158 }
5259 }
5360 }
61+
62+ private getValidGuid ( input : string ) {
63+ if ( input . length === 36 && UUID_REGEX . test ( input ) ) {
64+ return input ;
65+ }
66+
67+ if ( input . length === 32 && DASHLESS_UUID_REGEX . test ( input ) ) {
68+ return this . addDashesToUuid ( input ) ;
69+ }
70+
71+ const sha = crypto . createHash ( 'sha1' ) . update ( input ) . digest ( 'hex' ) . substring ( 0 , 32 ) ;
72+ return this . addDashesToUuid ( sha ) ;
73+ }
74+
75+ private addDashesToUuid ( uuid : string ) {
76+ return `${ uuid . substring ( 0 , 8 ) } -${ uuid . substring ( 8 , 12 ) } -${ uuid . substring ( 12 , 16 ) } -${ uuid . substring ( 16 , 20 ) } -${ uuid . substring ( 20 , 32 ) } ` ;
77+ }
5478}
0 commit comments