/** * Sanitizes user input by encoding special HTML characters. * Prevents XSS attacks by ensuring input is treated as text, not HTML. * * @param input - The raw string input from the user. * @returns The sanitized string with special characters encoded. */ export function sanitizeInput(input: string): string { if (typeof input !== "string") { return input; } return input .replace(/&/g, "&") .replace(//g, ">") .replace(/"/g, """) .replace(/'/g, "'"); } /** * Validates an email address format securely. * Rejects inputs containing dangerous characters like <, >, or whitespace. * * @param email - The email string to validate. * @returns True if the email is valid and safe, false otherwise. */ export function isValidEmail(email: string): boolean { // Basic format check + rejection of XSS vectors (<, >) // [^\s@<>]+ : Local part - no whitespace, @, <, or > // @ : Literal @ // [^\s@<>]+ : Domain part - no whitespace, @, <, or > // \. : Literal . // [^\s@<>]+ : TLD part - no whitespace, @, <, or > const emailRegex = /^[^\s@<>]+@[^\s@<>]+\.[^\s@<>]+$/; return emailRegex.test(email); }