|
| 1 | +import { UserDBScheme } from '@hawk.so/types'; |
| 2 | + |
| 3 | +/** |
| 4 | + * Validates UTM parameters |
| 5 | + * @param utm - Data form where user went to sign up. Used for analytics purposes |
| 6 | + * @returns boolean - true if valid, false if invalid |
| 7 | + */ |
| 8 | +export function validateUtmParams(utm: UserDBScheme['utm']): boolean { |
| 9 | + if (!utm) return true; |
| 10 | + |
| 11 | + const utmKeys = ['source', 'medium', 'campaign', 'content', 'term']; |
| 12 | + const providedKeys = Object.keys(utm); |
| 13 | + |
| 14 | + // Check if all provided keys are valid UTM keys |
| 15 | + const hasInvalidKeys = providedKeys.some((key) => !utmKeys.includes(key)); |
| 16 | + if (hasInvalidKeys) { |
| 17 | + return false; |
| 18 | + } |
| 19 | + |
| 20 | + // Check if values are strings and not too long |
| 21 | + for (const [key, value] of Object.entries(utm)) { |
| 22 | + if (value !== undefined && value !== null) { |
| 23 | + if (typeof value !== 'string' || value.length > 200) { |
| 24 | + return false; |
| 25 | + } |
| 26 | + // Basic sanitization - only allow alphanumeric, spaces, hyphens, underscores, dots |
| 27 | + if (!/^[a-zA-Z0-9\s\-_\.]+$/.test(value)) { |
| 28 | + return false; |
| 29 | + } |
| 30 | + } |
| 31 | + } |
| 32 | + |
| 33 | + return true; |
| 34 | +} |
| 35 | + |
| 36 | +/** |
| 37 | + * Sanitizes UTM parameters by removing invalid characters |
| 38 | + * @param utm - Data form where user went to sign up. Used for analytics purposes |
| 39 | + * @returns sanitized UTM parameters or undefined if invalid |
| 40 | + */ |
| 41 | +export function sanitizeUtmParams(utm: UserDBScheme['utm']): UserDBScheme['utm'] { |
| 42 | + if (!utm) return undefined; |
| 43 | + |
| 44 | + const utmKeys = ['source', 'medium', 'campaign', 'content', 'term']; |
| 45 | + const sanitized: UserDBScheme['utm'] = {}; |
| 46 | + |
| 47 | + for (const [key, value] of Object.entries(utm)) { |
| 48 | + if (utmKeys.includes(key) && value && typeof value === 'string') { |
| 49 | + // Sanitize value: keep only allowed characters and limit length |
| 50 | + const cleanValue = value |
| 51 | + .replace(/[^a-zA-Z0-9\s\-_\.]/g, '') |
| 52 | + .trim() |
| 53 | + .substring(0, 200); |
| 54 | + |
| 55 | + if (cleanValue.length > 0) { |
| 56 | + (sanitized as any)[key] = cleanValue; |
| 57 | + } |
| 58 | + } |
| 59 | + } |
| 60 | + |
| 61 | + return Object.keys(sanitized).length > 0 ? sanitized : undefined; |
| 62 | +} |
0 commit comments