Files
ragusaitweb/src/utils/security.ts
google-labs-jules[bot] 57f7c5667f 🛡️ Sentinel: [HIGH] Implement strict email validation
- Implemented `isValidEmail` utility with strict regex validation (rejects `<` and `>`) to prevent XSS vectors.
- Updated `Contact.tsx` to use `isValidEmail` instead of weak regex.
- Added comprehensive tests for `isValidEmail` in `src/utils/security.test.ts`.
- Fixed flaky test in `src/pages/__tests__/Contact.test.tsx` by clearing `localStorage` in `afterEach`.
- Added test case for invalid email submission.
- Documented findings in `.jules/sentinel.md`.

Co-authored-by: ragusa-it <196988693+ragusa-it@users.noreply.github.com>
2026-01-27 01:56:08 +00:00

37 lines
1.2 KiB
TypeScript

/**
* 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, "&amp;")
.replace(/</g, "&lt;")
.replace(/>/g, "&gt;")
.replace(/"/g, "&quot;")
.replace(/'/g, "&#039;");
}
/**
* 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);
}