11import { UserDBScheme } from '@hawk.so/types' ;
22
3+ /**
4+ * Valid UTM parameter keys
5+ */
6+ const VALID_UTM_KEYS = [ 'source' , 'medium' , 'campaign' , 'content' , 'term' ] ;
7+
8+ /**
9+ * Regular expression for valid UTM characters
10+ * Allows: alphanumeric, spaces, hyphens, underscores, dots
11+ */
12+ const VALID_UTM_CHARACTERS = / ^ [ a - z A - Z 0 - 9 \s \- _ . ] + $ / ;
13+
14+ /**
15+ * Regular expression for invalid UTM characters (inverse of VALID_UTM_CHARACTERS)
16+ * Used for cleaning/sanitizing values
17+ */
18+ const INVALID_UTM_CHARACTERS = / [ ^ a - z A - Z 0 - 9 \s \- _ . ] / g;
19+
320/**
421 * Validates UTM parameters
522 * @param utm - Data form where user went to sign up. Used for analytics purposes
@@ -15,7 +32,6 @@ export function validateUtmParams(utm: UserDBScheme['utm']): boolean {
1532 return false ;
1633 }
1734
18- const utmKeys = [ 'source' , 'medium' , 'campaign' , 'content' , 'term' ] ;
1935 const providedKeys = Object . keys ( utm ) ;
2036
2137 // Check if utm object is not empty
@@ -24,7 +40,7 @@ export function validateUtmParams(utm: UserDBScheme['utm']): boolean {
2440 }
2541
2642 // Check if all provided keys are valid UTM keys
27- const hasInvalidKeys = providedKeys . some ( ( key ) => ! utmKeys . includes ( key ) ) ;
43+ const hasInvalidKeys = providedKeys . some ( ( key ) => ! VALID_UTM_KEYS . includes ( key ) ) ;
2844 if ( hasInvalidKeys ) {
2945 return false ;
3046 }
@@ -42,7 +58,7 @@ export function validateUtmParams(utm: UserDBScheme['utm']): boolean {
4258 }
4359
4460 // Check for valid characters - only allow alphanumeric, spaces, hyphens, underscores, dots
45- if ( ! / ^ [ a - z A - Z 0 - 9 \s \- _ . ] + $ / . test ( value ) ) {
61+ if ( ! VALID_UTM_CHARACTERS . test ( value ) ) {
4662 return false ;
4763 }
4864 }
@@ -61,16 +77,12 @@ export function sanitizeUtmParams(utm: UserDBScheme['utm']): UserDBScheme['utm']
6177 return undefined ;
6278 }
6379
64- const utmKeys = [ 'source' , 'medium' , 'campaign' , 'content' , 'term' ] ;
6580 const sanitized : UserDBScheme [ 'utm' ] = { } ;
6681
6782 for ( const [ key , value ] of Object . entries ( utm ) ) {
68- if ( utmKeys . includes ( key ) && value && typeof value === 'string' ) {
83+ if ( VALID_UTM_KEYS . includes ( key ) && value && typeof value === 'string' ) {
6984 // Sanitize value: keep only allowed characters and limit length
70- const cleanValue = value
71- . replace ( / [ ^ a - z A - Z 0 - 9 \s \- _ . ] / g, '' )
72- . trim ( )
73- . substring ( 0 , 200 ) ;
85+ const cleanValue = value . replace ( INVALID_UTM_CHARACTERS , '' ) . trim ( ) . substring ( 0 , 200 ) ;
7486
7587 if ( cleanValue . length > 0 ) {
7688 ( sanitized as any ) [ key ] = cleanValue ;
0 commit comments