Shield: Add input sanitization and length validation to Contact form
Added `sanitizeInput` utility to escape HTML characters. Updated `Contact.tsx` to sanitize inputs before sending via `emailjs`. Added max length validation for Name (100), Subject (200), and Message (5000). Updated tests to cover sanitization and validation logic, including adding `cleanup()` to prevent test leakage.
This commit is contained in:
@@ -4,8 +4,13 @@ import emailjs from "@emailjs/browser";
|
||||
import { useTranslation } from "../i18n";
|
||||
import { config } from "../config";
|
||||
import { Button, Input, Textarea } from "../components/ui";
|
||||
import { sanitizeInput } from "../utils/security";
|
||||
import styles from "./Contact.module.css";
|
||||
|
||||
const NAME_MAX_LENGTH = 100;
|
||||
const SUBJECT_MAX_LENGTH = 200;
|
||||
const MESSAGE_MAX_LENGTH = 5000;
|
||||
|
||||
interface FormData {
|
||||
name: string;
|
||||
email: string;
|
||||
@@ -39,6 +44,8 @@ export function Contact() {
|
||||
|
||||
if (!formData.name.trim()) {
|
||||
newErrors.name = "Required";
|
||||
} else if (formData.name.length > NAME_MAX_LENGTH) {
|
||||
newErrors.name = `Max ${NAME_MAX_LENGTH} characters`;
|
||||
}
|
||||
|
||||
if (!formData.email.trim()) {
|
||||
@@ -49,10 +56,14 @@ export function Contact() {
|
||||
|
||||
if (!formData.subject.trim()) {
|
||||
newErrors.subject = "Required";
|
||||
} else if (formData.subject.length > SUBJECT_MAX_LENGTH) {
|
||||
newErrors.subject = `Max ${SUBJECT_MAX_LENGTH} characters`;
|
||||
}
|
||||
|
||||
if (!formData.message.trim()) {
|
||||
newErrors.message = "Required";
|
||||
} else if (formData.message.length > MESSAGE_MAX_LENGTH) {
|
||||
newErrors.message = `Max ${MESSAGE_MAX_LENGTH} characters`;
|
||||
}
|
||||
|
||||
setErrors(newErrors);
|
||||
@@ -69,10 +80,10 @@ export function Contact() {
|
||||
|
||||
try {
|
||||
const templateParams = {
|
||||
name: formData.name,
|
||||
email: formData.email,
|
||||
title: formData.subject,
|
||||
message: formData.message,
|
||||
name: sanitizeInput(formData.name),
|
||||
email: formData.email, // Email doesn't typically need HTML sanitization if validated by regex, but good practice to handle it if used in HTML context.
|
||||
title: sanitizeInput(formData.subject),
|
||||
message: sanitizeInput(formData.message),
|
||||
reply_to: formData.email,
|
||||
};
|
||||
|
||||
|
||||
Reference in New Issue
Block a user