From 6a56b27b0112e18e591de5fee52aa978b55ff934 Mon Sep 17 00:00:00 2001 From: root Date: Thu, 1 Oct 2026 16:33:20 -0400 Subject: [PATCH] Add security headers and make the contact form actually submit The contact section collected input and discarded it on submit. There is no backend contact endpoint and no mail provider, so the form opens the visitor's mail client with a prefilled Persian subject and body. Validation is client-side with inline Persian errors, an accessible alert summary, and focus moved to the first invalid field; a persistent hint states up front that nothing is stored on the server and shows the address to copy if no mail client is registered. Also add the response headers the site was missing: HSTS, nosniff, frame denial, a strict referrer policy, a restrictive permissions policy, and a CSP. The CSP still needs 'unsafe-inline' for scripts because nonces are not implemented yet; that is the next hardening step. poweredByHeader is off so the framework is not advertised. --- next.config.mjs | 52 ++++ .../(website)/components/contact/contact.tsx | 52 +--- .../components/contact/contactForm.tsx | 293 ++++++++++++++++++ 3 files changed, 350 insertions(+), 47 deletions(-) create mode 100644 src/app/(routes)/(website)/components/contact/contactForm.tsx diff --git a/next.config.mjs b/next.config.mjs index d50233e..715ae63 100644 --- a/next.config.mjs +++ b/next.config.mjs @@ -5,6 +5,7 @@ import withBundleAnalyzer from '@next/bundle-analyzer'; const nextConfig = { output: 'standalone', reactStrictMode: false, + poweredByHeader: false, turbopack: {}, images: { remotePatterns: [ @@ -40,6 +41,57 @@ const nextConfig = { }, ]; }, + async headers() { + // `upgrade-insecure-requests` is a CSP directive, not a header, so it lives inside + // the policy value below. `connect-src` allows the production backend only; the dev + // API runs on plain http://localhost:8000 (see .env.development), so that origin is + // appended outside of production to keep `next dev` working. + const connectSrc = ["'self'", 'https://backend.parsaaghayi.ir']; + if (process.env.NODE_ENV === 'development') { + connectSrc.push('http://localhost:8000', 'http://127.0.0.1:8000'); + } + + // TODO follow-up: ship a nonce-based policy (`script-src 'nonce-'` plus + // `'strict-dynamic'`). `'unsafe-inline'` is still required for scripts because + // Next.js emits inline bootstrap scripts (hydration payload, next-themes script) + // and framer-motion/next-themes are not wired up to receive a nonce yet. The nonce + // can be threaded through the root layout + middleware, which is what lets us drop + // `'unsafe-inline'` from script-src. + const contentSecurityPolicy = [ + "default-src 'self'", + "script-src 'self' 'unsafe-inline'", + "style-src 'self' 'unsafe-inline'", + "img-src 'self' data: blob: https:", + "font-src 'self' data:", + `connect-src ${connectSrc.join(' ')}`, + "media-src 'self' blob:", + "object-src 'none'", + "base-uri 'self'", + "frame-ancestors 'none'", + "form-action 'self'", + 'upgrade-insecure-requests', + ].join('; '); + + return [ + { + source: '/:path*', + headers: [ + { + key: 'Strict-Transport-Security', + value: 'max-age=63072000; includeSubDomains; preload', + }, + { key: 'X-Content-Type-Options', value: 'nosniff' }, + { key: 'X-Frame-Options', value: 'DENY' }, + { key: 'Referrer-Policy', value: 'strict-origin-when-cross-origin' }, + { + key: 'Permissions-Policy', + value: 'camera=(), microphone=(), geolocation=(), interest-cohort=()', + }, + { key: 'Content-Security-Policy', value: contentSecurityPolicy }, + ], + }, + ]; + }, webpack(config, { isServer }) { if (!isServer) { config.optimization.splitChunks = { diff --git a/src/app/(routes)/(website)/components/contact/contact.tsx b/src/app/(routes)/(website)/components/contact/contact.tsx index 77fd05b..e00c9a0 100644 --- a/src/app/(routes)/(website)/components/contact/contact.tsx +++ b/src/app/(routes)/(website)/components/contact/contact.tsx @@ -1,8 +1,7 @@ "use client"; -import React, { useState } from "react"; import { motion } from "framer-motion"; -import { Send } from "lucide-react"; +import ContactForm from "./contactForm"; interface ContactProps { dict: { @@ -20,19 +19,6 @@ interface ContactProps { } export default function Contact({ dict }: ContactProps) { - const [isSubmitting, setIsSubmitting] = useState(false); - const [submitted, setSubmitted] = useState(false); - - const handleSubmit = async (e: React.FormEvent) => { - e.preventDefault(); - setIsSubmitting(true); - // Simulate API call - await new Promise((resolve) => setTimeout(resolve, 2000)); - setIsSubmitting(false); - setSubmitted(true); - setTimeout(() => setSubmitted(false), 5000); - }; - return (
-
-
- -
- - {isSubmitting ? ( -
- ) : submitted ? ( - - Sent! - - ) : ( - <> - {dict.website.homePage.contact.button} - - - )} - - +
); diff --git a/src/app/(routes)/(website)/components/contact/contactForm.tsx b/src/app/(routes)/(website)/components/contact/contactForm.tsx new file mode 100644 index 0000000..5c54380 --- /dev/null +++ b/src/app/(routes)/(website)/components/contact/contactForm.tsx @@ -0,0 +1,293 @@ +"use client"; + +import { + ChangeEvent, + FormEvent, + useEffect, + useId, + useRef, + useState, +} from "react"; +import { AlertCircle, CheckCircle2, Mail, Send } from "lucide-react"; + +/** + * Inbox that receives every message submitted through this form. It matches the address + * already published in the Person JSON-LD of the website layout (`ceo@parsaaghayi.ir`). + * Change it here (and only here) to move the contact form to a different mailbox. + */ +const CONTACT_FORM_RECIPIENT_EMAIL = "ceo@parsaaghayi.ir"; + +const SUBJECT_PREFIX = "پیام جدید از فرم تماس سایت"; + +/** Deliberately simple shape check; the mail app does the real validation. */ +const EMAIL_SHAPE = /^[^\s@]+@[^\s@]+\.[^\s@]{2,}$/; + +type FieldName = "name" | "email" | "message"; + +type FormValues = Record; +type FieldErrors = Partial>; + +const EMPTY_VALUES: FormValues = { name: "", email: "", message: "" }; + +const ERROR_MESSAGES = { + nameRequired: "لطفاً نام خود را وارد کنید.", + emailRequired: "لطفاً ایمیل خود را وارد کنید.", + emailInvalid: "لطفاً یک ایمیل معتبر وارد کنید. مثال: name@example.com", + messageRequired: "لطفاً متن پیام خود را بنویسید.", +} as const; + +function validate(values: FormValues): FieldErrors { + const errors: FieldErrors = {}; + const name = values.name.trim(); + const email = values.email.trim(); + const message = values.message.trim(); + + if (!name) errors.name = ERROR_MESSAGES.nameRequired; + if (!email) { + errors.email = ERROR_MESSAGES.emailRequired; + } else if (!EMAIL_SHAPE.test(email)) { + errors.email = ERROR_MESSAGES.emailInvalid; + } + if (!message) errors.message = ERROR_MESSAGES.messageRequired; + + return errors; +} + +interface ContactFormProps { + buttonLabel: string; + emailPlaceholder: string; +} + +export default function ContactForm({ + buttonLabel, + emailPlaceholder, +}: ContactFormProps) { + const [values, setValues] = useState(EMPTY_VALUES); + const [errors, setErrors] = useState({}); + const [mailClientOpened, setMailClientOpened] = useState(false); + const formRef = useRef(null); + const focusFirstInvalidField = useRef(false); + const uid = useId(); + const nameId = `${uid}-name`; + const emailId = `${uid}-email`; + const messageId = `${uid}-message`; + const errorSummaryId = `${uid}-error-summary`; + + const errorEntries = Object.entries(errors) as [FieldName, string][]; + + // Runs after a failed submit only, so typing in a field is never interrupted by a + // focus jump while another field is still invalid. + useEffect(() => { + if (!focusFirstInvalidField.current) return; + focusFirstInvalidField.current = false; + formRef.current + ?.querySelector('[aria-invalid="true"]') + ?.focus(); + }, [errors]); + + const handleChange = + (field: FieldName) => + (event: ChangeEvent) => { + const { value } = event.target; + setValues((previous) => ({ ...previous, [field]: value })); + // Clear the message as soon as the visitor starts fixing the field. + setErrors((previous) => + previous[field] ? { ...previous, [field]: undefined } : previous, + ); + }; + + const handleSubmit = (event: FormEvent) => { + event.preventDefault(); + + const trimmed: FormValues = { + name: values.name.trim(), + email: values.email.trim(), + message: values.message.trim(), + }; + + const nextErrors = validate(trimmed); + + if (Object.keys(nextErrors).length > 0) { + setMailClientOpened(false); + // Ask for focus to move to the first field that needs fixing, so the announced + // errors are actionable. Done in an effect because the `aria-invalid` flags are + // only in the DOM after this state update is rendered. + focusFirstInvalidField.current = true; + setErrors(nextErrors); + return; + } + + const subject = `${SUBJECT_PREFIX} — ${trimmed.name}`; + const body = [ + `نام فرستنده: ${trimmed.name}`, + `ایمیل فرستنده: ${trimmed.email}`, + "", + "متن پیام:", + trimmed.message, + ].join("\n"); + + // There is no backend endpoint for contact submissions, so the form hands the draft + // to the visitor's own mail client. Nothing is sent or stored by this site. + window.location.href = `mailto:${CONTACT_FORM_RECIPIENT_EMAIL}?subject=${encodeURIComponent( + subject, + )}&body=${encodeURIComponent(body)}`; + + setMailClientOpened(true); + }; + + const inputClassName = + "w-full px-5 py-3 rounded-2xl border bg-background text-foreground placeholder:text-muted-foreground outline-none transition-all duration-300 focus:ring-2 focus:ring-primary/50"; + const invalidInputClassName = "border-destructive focus:ring-destructive/50"; + + return ( +
0 ? errorSummaryId : undefined} + > +

+

+ + {errorEntries.length > 0 && ( + + )} + +
+
+ + + {errors.name && ( +

+ {errors.name} +

+ )} +
+ +
+ + + {errors.email && ( +

+ {errors.email} +

+ )} +
+
+ +
+ +